Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(refactoring): unify recommendation contracts (#1784)

Raghav Chamadiya9c162335f222
diff --git a/packages/api-client/src/__fixtures__/hosted/recommendation-plans.json b/packages/api-client/src/__fixtures__/hosted/recommendation-plans.json
new file mode 100644
index 000000000..2496cef0b
--- /dev/null
+++ b/packages/api-client/src/__fixtures__/hosted/recommendation-plans.json
@@ -0,0 +1,24 @@
+{
+ "summary": {
+ "total": 1,
+ "by_type": [{ "type": "extract_method", "count": 1 }]
+ },
+ "plans": [
+ {
+ "id": "legacy-plan",
+ "refactoring_type": "extract_method",
+ "file_path": "src/app.py",
+ "target_symbol": "run",
+ "line_start": 10,
+ "line_end": 40,
+ "plan": {},
+ "evidence": {},
+ "impact_delta": 1.25,
+ "effort_bucket": "M",
+ "blast_radius": {},
+ "confidence": "medium",
+ "source_biomarker": "complex_method",
+ "rank_score": 1.5
+ }
+ ]
+}
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index c1ca20adb..bcaad4873 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -14,8 +14,8 @@ import type {
HealthFileBreakdownResponse,
HealthOverviewResponse,
HealthTrendResponse,
- RefactoringQuery,
- RefactoringTargetsResponse,
+ HealthWorkQueueQuery,
+ HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
import { apiGet, apiPatch } from "./client";
@@ -39,6 +39,9 @@ export type {
HealthModuleRow,
HealthOverviewResponse,
HealthTrendResponse,
+ HealthWorkItem,
+ HealthWorkQueueQuery,
+ HealthWorkQueueResponse,
ModuleCoverageRow,
RefactoringQuery,
RefactoringTarget,
@@ -128,16 +131,19 @@ export async function getTestsReaching(
);
}
-export async function getRefactoringTargets(
+export async function getHealthWorkQueue(
repoId: string,
- opts?: RefactoringQuery,
-): Promise<RefactoringTargetsResponse> {
- return apiGet<RefactoringTargetsResponse>(
+ opts?: HealthWorkQueueQuery,
+): Promise<HealthWorkQueueResponse> {
+ return apiGet<HealthWorkQueueResponse>(
`/api/repos/${repoId}/health/refactoring-targets`,
opts as Record<string, string | number | boolean | undefined>,
);
}
+/** @deprecated Use getHealthWorkQueue; the response is file triage, not plans. */
+export const getRefactoringTargets = getHealthWorkQueue;
+
export async function getChurnComplexity(
repoId: string,
opts?: { limit?: number },
diff --git a/packages/api-client/src/hosted.fixtures.test.ts b/packages/api-client/src/hosted.fixtures.test.ts
index e11885bfd..c0acd83f4 100644
--- a/packages/api-client/src/hosted.fixtures.test.ts
+++ b/packages/api-client/src/hosted.fixtures.test.ts
@@ -21,9 +21,10 @@ import type {
HealthFinding,
HealthOverviewResponse,
HealthTrendResponse,
- RefactoringTargetsResponse,
+ HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import type { RefactoringTargets } from "@repowise-dev/types/refactoring";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import { createHostedProvider, type HostedProvider } from "./hosted";
import type {
@@ -85,6 +86,7 @@ describe("hosted fixtures satisfy the OSS contracts", () => {
["/health/trend", "health-trend"],
["/health/churn-complexity", "churn-complexity"],
["/health/refactoring-targets", "refactoring-targets"],
+ ["/refactoring/targets", "recommendation-plans"],
]);
const overview: HealthOverviewResponse = await p.getHealthOverview("repo-1");
expect(overview.summary.file_count).toBeGreaterThan(0);
@@ -109,8 +111,15 @@ describe("hosted fixtures satisfy the OSS contracts", () => {
const churn: ChurnComplexityResponse = await p.getChurnComplexity("repo-1");
expect(Array.isArray(churn.points)).toBe(true);
- const targets: RefactoringTargetsResponse = await p.getRefactoringTargets("repo-1");
+ const targets: HealthWorkQueueResponse = await p.getHealthWorkQueue("repo-1");
expect(Array.isArray(targets.targets)).toBe(true);
+ const legacyTargets: HealthWorkQueueResponse = await p.getRefactoringTargets("repo-1");
+ expect(legacyTargets).toEqual(targets);
+
+ const plans: RefactoringTargets = await p.getRefactoringPlans("repo-1");
+ expect(plans.plans[0]?.rank_score).toBeTypeOf("number");
+ // Recorded older-server payload: the newer fields are intentionally absent.
+ expect(plans.plans[0]?.validation).toBeUndefined();
});
it("overview summary and stats highlights", async () => {
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index d3469e8a2..6874d1068 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -27,14 +27,16 @@ import type {
HealthFinding,
HealthOverviewResponse,
HealthTrendResponse,
- RefactoringQuery,
- RefactoringTargetsResponse,
+ HealthWorkQueueQuery,
+ HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import type { RefactoringTargets } from "@repowise-dev/types/refactoring";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";
import { ApiClientError } from "./client";
import type { ModuleHealthSortKey } from "./modules";
+import type { RefactoringTargetsParams } from "./refactoring";
import type {
ArchitectureGraphResponse,
CommunitySliceResponse,
@@ -369,10 +371,19 @@ export interface HostedProvider {
repoId: string,
opts?: { file_path?: string; limit?: number },
): Promise<HealthCoverageResponse>;
+ getHealthWorkQueue(
+ repoId: string,
+ opts?: HealthWorkQueueQuery,
+ ): Promise<HealthWorkQueueResponse>;
+ /** @deprecated Use getHealthWorkQueue. */
getRefactoringTargets(
repoId: string,
- opts?: RefactoringQuery,
- ): Promise<RefactoringTargetsResponse>;
+ opts?: HealthWorkQueueQuery,
+ ): Promise<HealthWorkQueueResponse>;
+ getRefactoringPlans(
+ repoId: string,
+ opts?: RefactoringTargetsParams,
+ ): Promise<RefactoringTargets>;
getChurnComplexity(repoId: string, opts?: { limit?: number }): Promise<ChurnComplexityResponse>;
// Modules
@@ -739,8 +750,17 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
};
},
getHealthCoverage: (repoId, opts) => snapGet(repoId, "/health/coverage", opts),
+ getHealthWorkQueue: (repoId, opts) =>
+ snapGet(repoId, "/health/refactoring-targets", opts as QueryParams),
getRefactoringTargets: (repoId, opts) =>
snapGet(repoId, "/health/refactoring-targets", opts as QueryParams),
+ getRefactoringPlans: (repoId, opts = {}) =>
+ snapGet(repoId, "/refactoring/targets", {
+ refactoring_type: opts.refactoringType,
+ min_confidence: opts.minConfidence,
+ file_path: opts.filePath,
+ view: opts.view,
+ }),
getChurnComplexity: (repoId, opts) => snapGet(repoId, "/health/churn-complexity", opts),
listModuleHealth: (repoId, options = {}) => snapGet(repoId, "/modules/health", options),
diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.ts
index 8e8c86aab..3cd511ab0 100644
--- a/packages/api-client/src/refactoring.ts
+++ b/packages/api-client/src/refactoring.ts
@@ -4,7 +4,11 @@
*/
import { apiGet, apiPost, apiPut } from "./client";
-import type { GeneratedCode, RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+import type {
+ GeneratedCode,
+ RefactoringPlan,
+ RefactoringTargets,
+} from "@repowise-dev/types/refactoring";
export interface RefactoringSettings {
enabled: boolean;
@@ -22,6 +26,7 @@ export interface RefactoringTargetsParams {
minConfidence?: string;
/** Repo-relative path; narrows plans to one file (summary stays global). */
filePath?: string;
+ view?: "canonical" | "file_spread";
}
export async function getRefactoringTargets(
@@ -32,6 +37,7 @@ export async function getRefactoringTargets(
refactoring_type: params.refactoringType,
min_confidence: params.minConfidence,
file_path: params.filePath,
+ view: params.view,
});
}
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index ae378f678..d2cdd93d0 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -25,7 +25,7 @@ from repowise.cli.helpers import (
)
from .codegen import _generate_refactoring_code
-from .persist import _load_persisted_coverage_map, _persist_health
+from .persist import _load_persisted_coverage_map, _load_recommendations, _persist_health
from .refactoring_targets import _render_refactoring_targets
from .summary import (
_render_badge,
@@ -280,6 +280,9 @@ def health_command(
suggestions = [s for s in suggestions if s.file_path == file_filter]
if module_filter:
suggestions = [s for s in suggestions if s.file_path.startswith(module_filter)]
+ # Attaches the same batched validation block the read surfaces emit;
+ # code generation remains explicitly requested and never auto-applies.
+ _load_recommendations(repo_path, suggestions, metrics_sorted)
_generate_refactoring_code(repo_path, suggestions, generate_code, fmt=fmt)
return
@@ -289,7 +292,8 @@ def health_command(
suggestions = [s for s in suggestions if s.file_path == file_filter]
if module_filter:
suggestions = [s for s in suggestions if s.file_path.startswith(module_filter)]
- _render_refactoring_targets(metrics_sorted, findings, suggestions, fmt=fmt)
+ recommendations = _load_recommendations(repo_path, suggestions, metrics_sorted)
+ _render_refactoring_targets(metrics_sorted, findings, recommendations, fmt=fmt)
return
if badge_view:
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
index a3de3634e..f06683590 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
@@ -8,6 +8,9 @@ per-test map. A ``repowise health`` run must not overwrite that data.
from __future__ import annotations
import json
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
from repowise.cli.helpers import console, run_async
@@ -63,6 +66,47 @@ def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:
return {}
+def _load_recommendations(
+ repo_path: Path, suggestions: Sequence[Any], metrics: Sequence[Any]
+) -> list[dict[str, Any]]:
+ """Canonical CLI recommendations, enriched from the local store in bulk."""
+ from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort
+ from repowise.core.analysis.health.refactoring.recommendations import (
+ build_recommendations,
+ hydrate_recommendations,
+ serialize_recommendations,
+ )
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import get_repository_by_path
+
+ async def _do() -> list[dict[str, 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:
+ return []
+ recommendations = await hydrate_recommendations(
+ session, repo.id, suggestions, metric_rows=metrics
+ )
+ return serialize_recommendations(recommendations)
+
+ try:
+ hydrated = run_async(_do())
+ if hydrated:
+ return hydrated
+ except Exception:
+ pass
+ return serialize_recommendations(
+ build_recommendations(
+ suggestions,
+ metric_by_path={getattr(metric, "file_path", ""): metric for metric in metrics},
+ )
+ )
+
+
def _persist_health(repo_path: object, *, report: object) -> None:
"""Write the analyzer's health output to the repo's wiki.db.
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.py
index ea6e2f366..f50adedf6 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
@@ -8,6 +8,8 @@ Split File) for both console and Markdown output.
from __future__ import annotations
import json
+from collections.abc import Mapping
+from typing import Any, cast
import click
from rich.table import Table
@@ -25,11 +27,19 @@ def _effort_bucket(nloc: int) -> tuple[str, int]:
return "XL", 5
-def _suggestion_to_dict(s: object) -> dict:
+def _suggestion_to_dict(s: object) -> dict[str, Any]:
"""Serialize a ``RefactoringSuggestion`` dataclass to a plain dict."""
import dataclasses
- return dataclasses.asdict(s) if dataclasses.is_dataclass(s) else dict(s)
+ if dataclasses.is_dataclass(s) and not isinstance(s, type):
+ return dataclasses.asdict(s)
+ return dict(cast(Mapping[str, Any], s))
+
+
+def _suggestion_path(s: object) -> str:
+ if isinstance(s, dict):
+ return str(s.get("file_path") or "")
+ return str(getattr(s, "file_path", "") or "")
def _render_refactoring_targets(
@@ -44,7 +54,7 @@ def _render_refactoring_targets(
suggestions = suggestions or []
sugg_by_file: dict[str, list] = {}
for s in suggestions:
- sugg_by_file.setdefault(s.file_path, []).append(s)
+ sugg_by_file.setdefault(_suggestion_path(s), []).append(s)
by_file: dict[str, list] = {}
for f in findings:
@@ -80,10 +90,19 @@ def _render_refactoring_targets(
# 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 engine's unified rank (impact x centrality x blast
- # radius across all detector types), so we preserve it rather than
- # re-sorting per type.
- ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]
+ # 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]
if fmt == "json":
click.echo(json.dumps({"targets": targets, "refactoring_plans": ranked_plans}, indent=2))
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index 05db0ccb3..13cdd64f2 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -399,6 +399,7 @@ def _build_user_prompt(suggestion: Any, spans: list[SourceSpan]) -> str:
"plan": suggestion.plan or {},
"evidence": suggestion.evidence or {},
"blast_radius": suggestion.blast_radius or {},
+ "validation": getattr(suggestion, "validation", {}) or {},
},
indent=2,
sort_keys=True,
@@ -471,6 +472,7 @@ def _cache_key(suggestion: Any, spans: list[SourceSpan], model: str) -> str:
"target": suggestion.target_symbol,
"file": suggestion.file_path,
"plan": suggestion.plan or {},
+ "validation": getattr(suggestion, "validation", {}) or {},
"spans": [
[s.file, s.start_line, s.end_line, hashlib.sha256(s.source.encode()).hexdigest()]
for s in spans
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 40343a1fb..6be0df786 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -216,3 +216,6 @@ class RefactoringSuggestion:
confidence: str
# The biomarker finding this suggestion answers (e.g. "low_cohesion").
source_biomarker: str = ""
+ # Read-side validation plan. Detectors leave it empty; the canonical
+ # recommendation service attaches measured/inferred tests in one batch.
+ validation: dict[str, Any] = field(default_factory=dict)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/rank.py b/packages/core/src/repowise/core/analysis/health/refactoring/rank.py
index 68adfe9a0..d78ab40d2 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/rank.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/rank.py
@@ -1,72 +1,21 @@
-"""Unified ranking across every refactoring detector.
+"""Compatibility facade for the canonical recommendation rank.
-Each detector sorts its own output deterministically, but the surfaces (CLI,
-MCP, web) present a single mixed list — so the *global* order is what the user
-actually sees. This module imposes one ranking over all types so the top of
-the list is always the most valuable refactoring regardless of kind, instead
-of a churn-only or impact-only sort that buries cross-file wins.
-
-The key blends three orthogonal signals as a product of ``(1 + signal)``
-factors (so a zero in any one dimension shapes the order without annihilating
-the suggestion):
-
-- **recovered impact** — the health the refactoring buys back (0 for the
- graph-native types that answer no biomarker);
-- **target centrality** — how depended-upon the file is, so a refactoring on a
- hub file outranks the same refactoring on a leaf;
-- **blast radius** — how much else moves, as a mild amplifier (a wide, real
- refactoring is worth surfacing) rather than a penalty;
-- **confidence** — a final weight so a high-confidence plan edges out a
- borderline one at the same score.
-
-Because impact-free types still rank via centrality and blast, Move Method and
-Break Cycle interleave fairly with Extract Class / Extract Helper rather than
-sinking below every impact-bearing suggestion.
+Analysis-time callers still ask for suggestions rather than serialized read
+models. The semantic owner is :mod:`.recommendations`; this module preserves
+the old API while delegating benefit/cost/risk and deterministic ordering.
"""
from __future__ import annotations
-import math
from collections.abc import Mapping, Sequence
from .models import RefactoringSuggestion
-
-_CONFIDENCE_WEIGHT = {"high": 1.25, "medium": 1.0, "low": 0.75}
-
-
-def _blast_size(s: RefactoringSuggestion) -> int:
- """A single 'how much else moves' integer, read from whichever blast-radius
- shape this refactoring type carries."""
- br = s.blast_radius or {}
- for key in ("file_count", "dependents_count", "callers"):
- value = br.get(key)
- if isinstance(value, (int, float)) and value:
- return int(value)
- files = br.get("files")
- return len(files) if isinstance(files, list) else 0
-
-
-def _enrich_blast_radius(s: RefactoringSuggestion, centrality: Mapping[str, float]) -> None:
- """Give every plan a caller/dependents rollup so the 'what else moves'
- signal is uniform across types. Extract Helper carries only its
- co-occurrence files; here we add the importing-file count summed over the
- occurrences (the callers that ride along), which the ranking then reads."""
- br = dict(s.blast_radius or {})
- if "callers" not in br and "dependents_count" not in br:
- files = br.get("files")
- if isinstance(files, list) and files:
- br["callers"] = sum(int(centrality.get(f, 0)) for f in files)
- s.blast_radius = br
+from .recommendations import build_recommendations
def score(s: RefactoringSuggestion, centrality: Mapping[str, float]) -> float:
- """The unified rank score (higher = surface sooner)."""
- impact_factor = 1.0 + max(0.0, float(s.impact_delta or 0.0))
- cen = float(centrality.get(s.file_path, 0.0))
- centrality_factor = 1.0 + math.log1p(max(0.0, cen))
- blast_factor = 1.0 + math.log1p(_blast_size(s))
- confidence_weight = _CONFIDENCE_WEIGHT.get(s.confidence, 1.0)
- return impact_factor * centrality_factor * blast_factor * confidence_weight
+ """Compatibility priority without persisted health/validation enrichment."""
+ return build_recommendations([s], centrality=centrality)[0].rank_score
def rank_suggestions(
@@ -82,15 +31,5 @@ def rank_suggestions(
enriches each suggestion's blast radius in place so the persisted/rendered
plan carries the same caller rollup the ranking used.
"""
- cen = centrality or {}
- for s in suggestions:
- _enrich_blast_radius(s, cen)
- return sorted(
- suggestions,
- key=lambda s: (
- -score(s, cen),
- s.refactoring_type,
- s.file_path,
- s.target_symbol,
- ),
- )
+ recommendations = build_recommendations(suggestions, centrality=centrality or {})
+ return [recommendation.suggestion for recommendation in recommendations]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
new file mode 100644
index 000000000..be319f286
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -0,0 +1,667 @@
+"""Canonical recommendation read model, ranking, validation, and serialization.
+
+Detector suggestions and persisted ORM rows are deliberately small write-side
+facts. This module is the one read-side owner that turns either shape into the
+recommendation contract consumed by REST, MCP, and CLI. Every database read is
+batched across the complete plan set; adding plans never adds SQL statements.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.health.grading import HEALTHY_MIN
+from repowise.core.analysis.test_reachability import ReachedBy, tests_reaching_by_tier
+
+from .models import RefactoringSuggestion
+
+RecommendationView = Literal["canonical", "file_spread"]
+ValidationBasis = Literal["measured", "inferred", "mixed", "unknown"]
+ValidationVia = Literal["coverage", "call-graph", "import-graph", "mixed"]
+
+DEFAULT_TEST_LIMIT = 12
+_EFFORT_COST = {"S": 1.0, "M": 2.0, "L": 3.0, "XL": 5.0}
+_CONFIDENCE_RISK = {"high": 0.0, "medium": 0.5, "low": 1.25}
+_WEAK_PROVENANCE = {"name-fallback", "global_unique", "unknown"}
+
+
+def _loads_dict(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return dict(value)
+ if not value:
+ return {}
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+def _attr(row: Any, name: str, default: Any = None) -> Any:
+ return row.get(name, default) if isinstance(row, Mapping) else getattr(row, name, default)
+
+
+def rehydrate_suggestion(row: Any) -> RefactoringSuggestion:
+ """Normalize an ORM row, dataclass, or compatible object once."""
+ if isinstance(row, RefactoringSuggestion):
+ suggestion = row
+ else:
+ suggestion = RefactoringSuggestion(
+ refactoring_type=str(_attr(row, "refactoring_type", "")),
+ file_path=str(_attr(row, "file_path", "")),
+ target_symbol=str(_attr(row, "target_symbol", "")),
+ line_start=_attr(row, "line_start", None),
+ line_end=_attr(row, "line_end", None),
+ plan=_loads_dict(_attr(row, "plan", None) or _attr(row, "plan_json", None)),
+ evidence=_loads_dict(_attr(row, "evidence", None) or _attr(row, "evidence_json", None)),
+ impact_delta=float(_attr(row, "impact_delta", 0.0) or 0.0),
+ effort_bucket=str(_attr(row, "effort_bucket", "") or ""),
+ blast_radius=_loads_dict(
+ _attr(row, "blast_radius", None) or _attr(row, "blast_radius_json", None)
+ ),
+ confidence=str(_attr(row, "confidence", "medium") or "medium"),
+ source_biomarker=str(_attr(row, "source_biomarker", "") or ""),
+ )
+ row_id = _attr(row, "id", None)
+ if row_id is not None:
+ suggestion.id = str(row_id) # type: ignore[attr-defined]
+ return suggestion
+
+
+def _string_list(value: Any) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return [item for item in value if isinstance(item, str) and item]
+
+
+def _dict_list(value: Any) -> list[dict[str, Any]]:
+ if not isinstance(value, list):
+ return []
+ return [item for item in value if isinstance(item, dict)]
+
+
+def _named_strings(row: Mapping[str, Any], keys: Sequence[str]) -> set[str]:
+ return {value for key in keys if isinstance((value := row.get(key)), str) and value}
+
+
+def _location_values(plan: Mapping[str, Any], key: str) -> set[str]:
+ return {
+ value
+ for location in _dict_list(plan.get("affected_locations"))
+ if isinstance((value := location.get(key)), str) and value
+ }
+
+
+def _cut_edge_files(plan: Mapping[str, Any]) -> set[str]:
+ return set().union(
+ *(_named_strings(edge, ("from", "to")) for edge in _dict_list(plan.get("cut_edges"))),
+ set(),
+ )
+
+
+def _suggested_group_files(plan: Mapping[str, Any]) -> set[str]:
+ return {
+ value
+ for group in _dict_list(plan.get("groups"))
+ if isinstance((value := group.get("suggested_file")), str) and value
+ }
+
+
+def affected_files(suggestion: RefactoringSuggestion) -> list[str]:
+ """Files the plan explicitly says it changes or must keep consistent."""
+ plan = suggestion.plan or {}
+ blast = suggestion.blast_radius or {}
+ files = {suggestion.file_path} if suggestion.file_path else set()
+ files.update(_string_list(blast.get("files")))
+ files.update(_string_list(blast.get("dependent_files")))
+ files.update(_location_values(plan, "file_path"))
+ files.update(_named_strings(plan, ("to_file", "intervention_file")))
+ files.update(_string_list(plan.get("cycle")))
+ files.update(_cut_edge_files(plan))
+ files.update(_suggested_group_files(plan))
+ return sorted(files)
+
+
+def affected_symbols(suggestion: RefactoringSuggestion) -> list[str]:
+ symbols = {suggestion.target_symbol} if suggestion.target_symbol else set()
+ plan = suggestion.plan or {}
+ symbols.update(
+ _named_strings(plan, ("intervention_symbol", "method", "from_class", "to_class"))
+ )
+ symbols.update(_location_values(plan, "function_name"))
+ return sorted(symbols)
+
+
+def blast_size(suggestion: RefactoringSuggestion) -> int:
+ """True change surface from every compatible persisted blast shape."""
+ blast = suggestion.blast_radius or {}
+ counts = [
+ int(value)
+ for key in (
+ "file_count",
+ "dependents_count",
+ "dependent_count",
+ "callers",
+ "call_sites",
+ )
+ if isinstance((value := blast.get(key)), (int, float)) and value > 0
+ ]
+ counts.extend(len(_string_list(blast.get(key))) for key in ("files", "dependent_files"))
+ return max(counts, default=max(0, len(affected_files(suggestion)) - 1))
+
+
+def enrich_blast_radius(suggestion: RefactoringSuggestion, centrality: Mapping[str, float]) -> None:
+ """Preserve the legacy caller rollup while centrality has one owner."""
+ blast = dict(suggestion.blast_radius or {})
+ if "callers" not in blast and "dependents_count" not in blast:
+ files = _string_list(blast.get("files"))
+ if files:
+ blast["callers"] = sum(int(centrality.get(path, 0.0) or 0.0) for path in files)
+ suggestion.blast_radius = blast
+
+
+def _performance_benefit(evidence: Mapping[str, Any]) -> float:
+ factors = evidence.get("rank_factors")
+ if isinstance(factors, Mapping):
+ raw = sum(
+ float(value)
+ for name, value in factors.items()
+ if name != "affected_call_sites" and isinstance(value, (int, float))
+ )
+ else:
+ # Older persisted rows may only carry the combined legacy rank. It included
+ # blast radius, so use a conservative detector-native floor rather than
+ # relabeling that mixed score as benefit.
+ raw = 1.0 if evidence.get("rank_score") is not None else 0.0
+ return math.log1p(max(0.0, raw))
+
+
+def _cycle_benefit(evidence: Mapping[str, Any]) -> float:
+ return 1.0 + math.log1p(
+ max(float(evidence.get("cycle_size") or 0), float(evidence.get("cut_count") or 0))
+ )
+
+
+def _move_benefit(evidence: Mapping[str, Any]) -> float:
+ foreign = float(evidence.get("foreign_calls") or 0)
+ own = float(evidence.get("own_calls") or 0)
+ return 1.0 + math.log1p(max(0.0, foreign - own))
+
+
+def _split_benefit(evidence: Mapping[str, Any]) -> float:
+ groups = float(evidence.get("group_count") or 0)
+ return 1.0 + math.log1p(max(0.0, groups - 1.0))
+
+
+_DETECTOR_BENEFIT: dict[str, Callable[[Mapping[str, Any]], float]] = {
+ "performance_fix": _performance_benefit,
+ "break_cycle": _cycle_benefit,
+ "move_method": _move_benefit,
+ "split_file": _split_benefit,
+}
+
+
+def detector_native_benefit(suggestion: RefactoringSuggestion) -> float:
+ """Recoverable health or a detector-owned structural/performance gain."""
+ impact = max(0.0, float(suggestion.impact_delta or 0.0))
+ if impact:
+ return impact
+ benefit = _DETECTOR_BENEFIT.get(suggestion.refactoring_type)
+ if benefit is not None:
+ return benefit(suggestion.evidence or {})
+ # A detector that emitted a concrete graph-native plan has a real but
+ # deliberately small gain even when it is not a defect-health deduction.
+ return 1.0 if suggestion.refactoring_type else 0.0
+
+
+@dataclass(frozen=True, slots=True)
+class ValidationTarget:
+ file_path: str
+ basis: ValidationBasis
+ via: ValidationVia | None
+ total: int
+ tests: list[str]
+ truncated: bool
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "file_path": self.file_path,
+ "basis": self.basis,
+ "via": self.via,
+ "total": self.total,
+ "tests": self.tests,
+ "truncated": self.truncated,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ValidationPlan:
+ basis: ValidationBasis
+ via: ValidationVia | None
+ total: int
+ tests: list[str]
+ truncated: bool
+ affected_files: list[str]
+ affected_symbols: list[str]
+ commands: list[str]
+ targets: list[ValidationTarget] = field(default_factory=list)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "basis": self.basis,
+ "via": self.via,
+ "total": self.total,
+ "tests": self.tests,
+ "truncated": self.truncated,
+ "affected_files": self.affected_files,
+ "affected_symbols": self.affected_symbols,
+ "commands": self.commands,
+ "targets": [target.as_dict() for target in self.targets],
+ }
+
+
+def _commands(tests: list[str], files: list[str], *, total: int | None = None) -> list[str]:
+ """A command that runs at least everything the plan says validates it.
+
+ When the displayed list is capped, enumerating only the shown tests would
+ read as a complete validation run while silently skipping the rest, so the
+ selection widens to the files those tests live in: bounded by file count
+ rather than test count, and never narrower than the evidence.
+ """
+ if total is not None and total > len(tests):
+ tests = sorted({test.split("::", 1)[0] for test in tests})
+ python_tests = sorted(test for test in tests if ".py" in test)
+ js_tests = sorted(
+ test for test in tests if any(ext in test for ext in (".ts", ".tsx", ".js", ".jsx"))
+ )
+ commands: list[str] = []
+ if python_tests:
+ commands.append("pytest " + " ".join(python_tests))
+ if js_tests:
+ commands.append("npm test -- " + " ".join(js_tests))
+ if commands:
+ return commands
+ if any(path.endswith(".py") for path in files):
+ return ["pytest"]
+ if any(path.endswith((".ts", ".tsx", ".js", ".jsx")) for path in files):
+ return ["npm test", "npm run type-check"]
+ return ["npm run test"]
+
+
+def _line_ranges(suggestion: RefactoringSuggestion) -> dict[str, set[int] | None]:
+ """Lines each affected file changes, or ``None`` when the plan says only the file.
+
+ Locations accumulate per file rather than replacing one another: a
+ ``performance_fix`` emits one ``affected_locations`` entry per call site, and
+ an N+1 routinely puts several of them in the same file. Overwriting kept only
+ the last site, so a test covering any earlier one stopped intersecting, the
+ plan fell back from ``measured`` to ``unknown``, and its rank dropped with it.
+ """
+ ranges: dict[str, set[int] | None] = {path: None for path in affected_files(suggestion)}
+ if suggestion.file_path and suggestion.line_start:
+ end = suggestion.line_end or suggestion.line_start
+ ranges[suggestion.file_path] = set(range(suggestion.line_start, end + 1))
+ for location in _dict_list((suggestion.plan or {}).get("affected_locations")):
+ path = location.get("file_path")
+ start = location.get("line_start")
+ end = location.get("line_end") or start
+ if isinstance(path, str) and isinstance(start, int) and isinstance(end, int):
+ ranges[path] = (ranges.get(path) or set()) | set(range(start, end + 1))
+ return ranges
+
+
+def _measured_labels(rows: list[dict[str, Any]], lines: set[int] | None) -> set[str]:
+ labels: set[str] = set()
+ for row in rows:
+ covered = set(row.get("covered_lines") or [])
+ if lines is not None and not lines.intersection(covered):
+ continue
+ label = row.get("test_id") or row.get("test_file")
+ if isinstance(label, str) and label:
+ labels.add(label)
+ return labels
+
+
+def _validation_target(
+ file_path: str,
+ lines: set[int] | None,
+ measured: Mapping[str, list[dict[str, Any]]],
+ inferred: Mapping[str, ReachedBy],
+ cap: int,
+) -> tuple[ValidationTarget, set[str], bool]:
+ labels = _measured_labels(measured.get(file_path, []), lines)
+ if labels:
+ basis: ValidationBasis = "measured"
+ via: ValidationVia | None = "coverage"
+ total = len(labels)
+ identities_complete = True
+ else:
+ reached = inferred.get(file_path)
+ labels = set(reached.all_tests or reached.tests) if reached is not None else set()
+ basis = "inferred" if reached is not None and reached.total else "unknown"
+ via = reached.via if reached is not None and reached.total else None
+ total = reached.total if reached is not None else 0
+ identities_complete = (
+ reached is None or reached.all_tests is not None or total == len(labels)
+ )
+ ordered = sorted(labels)
+ return (
+ ValidationTarget(
+ file_path=file_path,
+ basis=basis,
+ via=via,
+ total=total,
+ tests=ordered[:cap],
+ truncated=total > cap,
+ ),
+ labels,
+ identities_complete,
+ )
+
+
+def build_validation_plan(
+ suggestion: RefactoringSuggestion,
+ measured: Mapping[str, list[dict[str, Any]]],
+ inferred: Mapping[str, ReachedBy],
+ *,
+ test_limit: int = DEFAULT_TEST_LIMIT,
+) -> ValidationPlan:
+ """Resolve target evidence in strict measured/call/import precedence."""
+ cap = max(0, test_limit)
+ target_rows: list[ValidationTarget] = []
+ union: set[str] = set()
+ identities_complete = True
+ for file_path, lines in sorted(_line_ranges(suggestion).items()):
+ target, labels, target_complete = _validation_target(
+ file_path, lines, measured, inferred, cap
+ )
+ union.update(labels)
+ identities_complete = identities_complete and target_complete
+ target_rows.append(target)
+
+ evidence_targets = [target for target in target_rows if target.total]
+ bases = {target.basis for target in target_rows}
+ vias = {target.via for target in evidence_targets if target.via is not None}
+ aggregate_basis: ValidationBasis = (
+ "unknown" if not bases else next(iter(bases)) if len(bases) == 1 else "mixed"
+ )
+ aggregate_via: ValidationVia | None = (
+ None if not vias else next(iter(vias)) if len(vias) == 1 else "mixed"
+ )
+ ordered_tests = sorted(union)
+ aggregate_total = (
+ len(ordered_tests)
+ if identities_complete
+ else target_rows[0].total
+ if len(target_rows) == 1
+ else sum(target.total for target in target_rows)
+ )
+ files = affected_files(suggestion)
+ return ValidationPlan(
+ basis=aggregate_basis,
+ via=aggregate_via,
+ total=aggregate_total,
+ tests=ordered_tests[:cap],
+ truncated=aggregate_total > len(ordered_tests[:cap]),
+ affected_files=files,
+ affected_symbols=affected_symbols(suggestion),
+ commands=_commands(ordered_tests[:cap], files, total=aggregate_total),
+ targets=target_rows,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Recommendation:
+ suggestion: RefactoringSuggestion = field(repr=False, compare=False)
+ benefit: float
+ leverage: float
+ cost: float
+ risk: float
+ rank_score: float
+ dependents: int
+ file_nloc: int
+ file_weighted_deficit: int
+ validation: ValidationPlan
+
+ @property
+ def id(self) -> str:
+ return str(getattr(self.suggestion, "id", "") or "")
+
+ def as_dict(self) -> dict[str, Any]:
+ suggestion = self.suggestion
+ return {
+ "id": self.id,
+ "refactoring_type": suggestion.refactoring_type,
+ "file_path": suggestion.file_path,
+ "target_symbol": suggestion.target_symbol,
+ "line_start": suggestion.line_start,
+ "line_end": suggestion.line_end,
+ "plan": suggestion.plan or {},
+ "evidence": suggestion.evidence or {},
+ "impact_delta": round(float(suggestion.impact_delta or 0.0), 3),
+ "effort_bucket": suggestion.effort_bucket,
+ "blast_radius": suggestion.blast_radius or {},
+ "confidence": suggestion.confidence,
+ "source_biomarker": suggestion.source_biomarker,
+ "benefit": self.benefit,
+ "leverage": self.leverage,
+ "cost": self.cost,
+ "risk": self.risk,
+ "rank_score": self.rank_score,
+ "dependents": self.dependents,
+ "file_nloc": self.file_nloc,
+ "file_weighted_deficit": self.file_weighted_deficit,
+ "validation": self.validation.as_dict(),
+ }
+
+
+def _priority_components(
+ suggestion: RefactoringSuggestion,
+ *,
+ nloc: int,
+ health_score: float,
+ dependents: int,
+ validation: ValidationPlan,
+) -> tuple[float, float, float, float, float, int]:
+ weighted_deficit = round(max(HEALTHY_MIN - health_score, 0.0) * max(nloc, 1))
+ benefit = detector_native_benefit(suggestion)
+ entry_bonus = 0.5 if (suggestion.evidence or {}).get("reliable_entry_reachability") else 0.0
+ leverage = 0.5 * math.log1p(weighted_deficit) + math.log1p(max(0, dependents)) + entry_bonus
+ surface = max(blast_size(suggestion), max(0, len(affected_files(suggestion)) - 1))
+ cost = _EFFORT_COST.get(suggestion.effort_bucket, 3.0) + math.log1p(surface)
+ provenance = str((suggestion.evidence or {}).get("provenance") or "")
+ weak_graph = 1.0 if provenance in _WEAK_PROVENANCE else 0.0
+ validation_risk = {
+ "measured": 0.0,
+ "mixed": 0.5,
+ "inferred": 0.75,
+ "unknown": 1.5,
+ }[validation.basis]
+ risk = (
+ math.log1p(surface)
+ + _CONFIDENCE_RISK.get(suggestion.confidence, 0.75)
+ + weak_graph
+ + validation_risk
+ )
+ priority = (1.0 + benefit) * (1.0 + leverage) / (1.0 + cost + risk)
+ return (
+ round(benefit, 4),
+ round(leverage, 4),
+ round(cost, 4),
+ round(risk, 4),
+ round(priority, 4),
+ weighted_deficit,
+ )
+
+
+def build_recommendations(
+ rows: Sequence[Any],
+ *,
+ metric_by_path: Mapping[str, Any] | None = None,
+ centrality: Mapping[str, float] | None = None,
+ validations: Mapping[int, ValidationPlan] | None = None,
+) -> list[Recommendation]:
+ """Pure recommendation construction used by every surface and tests."""
+ metrics = metric_by_path or {}
+ centrality = centrality or {}
+ validations = validations or {}
+ out: list[Recommendation] = []
+ for index, row in enumerate(rows):
+ suggestion = rehydrate_suggestion(row)
+ enrich_blast_radius(suggestion, centrality)
+ metric = metrics.get(suggestion.file_path)
+ nloc = int(_attr(metric, "nloc", 0) or 0)
+ raw_health_score = _attr(metric, "score", HEALTHY_MIN)
+ health_score = float(HEALTHY_MIN if raw_health_score is None else raw_health_score)
+ dependents = int(float(centrality.get(suggestion.file_path, 0.0) or 0.0))
+ validation = validations.get(index) or build_validation_plan(suggestion, {}, {})
+ benefit, leverage, cost, risk, rank_score, deficit = _priority_components(
+ suggestion,
+ nloc=nloc,
+ health_score=health_score,
+ dependents=dependents,
+ validation=validation,
+ )
+ suggestion.validation = validation.as_dict()
+ out.append(
+ Recommendation(
+ suggestion=suggestion,
+ benefit=benefit,
+ leverage=leverage,
+ cost=cost,
+ risk=risk,
+ rank_score=rank_score,
+ dependents=dependents,
+ file_nloc=nloc,
+ file_weighted_deficit=deficit,
+ validation=validation,
+ )
+ )
+ return canonical_order(out)
+
+
+def canonical_order(recommendations: Sequence[Recommendation]) -> list[Recommendation]:
+ return sorted(
+ recommendations,
+ key=lambda recommendation: (
+ -recommendation.rank_score,
+ recommendation.suggestion.refactoring_type,
+ recommendation.suggestion.file_path,
+ recommendation.suggestion.target_symbol,
+ recommendation.id,
+ ),
+ )
+
+
+def apply_view(
+ recommendations: Sequence[Recommendation], view: RecommendationView = "canonical"
+) -> list[Recommendation]:
+ ranked = canonical_order(recommendations)
+ if view == "canonical":
+ return ranked
+ if view != "file_spread":
+ raise ValueError(f"unknown recommendation view: {view}")
+ by_file: dict[str, list[Recommendation]] = {}
+ for recommendation in ranked:
+ by_file.setdefault(recommendation.suggestion.file_path, []).append(recommendation)
+ spread: list[Recommendation] = []
+ while by_file:
+ for file_path in list(by_file):
+ spread.append(by_file[file_path].pop(0))
+ if not by_file[file_path]:
+ del by_file[file_path]
+ return spread
+
+
+async def hydrate_recommendations(
+ session: AsyncSession,
+ repository_id: str,
+ rows: Sequence[Any],
+ *,
+ metric_rows: Sequence[Any] | None = None,
+ view: RecommendationView = "canonical",
+ test_limit: int = DEFAULT_TEST_LIMIT,
+) -> list[Recommendation]:
+ """Hydrate, enrich, validate, rank, and serialize-ready all *rows*.
+
+ Query shape is constant in plan/test count: health metrics and graph metrics
+ are bulk reads, measured coverage is one ``IN`` query, and inferred walks
+ use their existing bounded level queries over the complete unanswered set.
+ """
+ from repowise.core.persistence import crud
+ from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
+
+ if not rows:
+ return []
+ suggestions = [rehydrate_suggestion(row) for row in rows]
+ metrics = (
+ list(metric_rows)
+ if metric_rows is not None
+ else await crud.get_health_metrics(session, repository_id)
+ )
+ graph_metrics = await crud.get_graph_metrics(session, repository_id)
+ centrality = {
+ node_id: float(metric.get("in_degree") or 0.0) for node_id, metric in graph_metrics.items()
+ }
+ target_files = sorted(
+ {path for suggestion in suggestions for path in affected_files(suggestion)}
+ )
+ measured = await tests_covering_files(session, repository_id, set(target_files))
+
+ # A measured row only answers a target when it intersects the plan's line
+ # range (if one exists). Seed inference once with every file that remains
+ # unanswered for at least one plan.
+ unanswered: set[str] = set()
+ for suggestion in suggestions:
+ for file_path, lines in _line_ranges(suggestion).items():
+ if not _measured_labels(measured.get(file_path, []), lines):
+ unanswered.add(file_path)
+ inferred = (
+ await tests_reaching_by_tier(session, repository_id, sorted(unanswered))
+ if unanswered
+ else {}
+ )
+ validations = {
+ index: build_validation_plan(suggestion, measured, inferred, test_limit=test_limit)
+ for index, suggestion in enumerate(suggestions)
+ }
+ recommendations = build_recommendations(
+ suggestions,
+ metric_by_path={metric.file_path: metric for metric in metrics},
+ centrality=centrality,
+ validations=validations,
+ )
+ return apply_view(recommendations, view)
+
+
+def serialize_recommendations(
+ recommendations: Sequence[Recommendation],
+) -> list[dict[str, Any]]:
+ return [recommendation.as_dict() for recommendation in recommendations]
+
+
+__all__ = [
+ "DEFAULT_TEST_LIMIT",
+ "Recommendation",
+ "RecommendationView",
+ "ValidationPlan",
+ "ValidationTarget",
+ "affected_files",
+ "affected_symbols",
+ "apply_view",
+ "blast_size",
+ "build_recommendations",
+ "build_validation_plan",
+ "canonical_order",
+ "detector_native_benefit",
+ "enrich_blast_radius",
+ "hydrate_recommendations",
+ "rehydrate_suggestion",
+ "serialize_recommendations",
+]
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 0012e0cf5..216b11132 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -215,6 +215,9 @@ class ReachedBy:
tests: list[str]
via: ReachedVia
total: int = 0
+ # Internal uncapped identities let downstream aggregators de-duplicate one
+ # test that reaches several targets while public lists remain bounded.
+ all_tests: tuple[str, ...] | None = None
def call_graph_from_graph(graph: Any) -> CallGraphView:
@@ -370,20 +373,22 @@ async def tests_reaching_by_tier(
if call_depth >= 1:
found = await _call_reaching(session, repo_id, seeds, test_files, call_depth)
for seed, tests in found.items():
- out[seed] = ReachedBy(_cut(tests), "call-graph", len(tests))
+ ordered = tuple(sorted(tests))
+ out[seed] = ReachedBy(
+ list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered
+ )
unanswered = [seed for seed in seeds if seed not in out]
if unanswered and import_depth >= 1:
found = await _import_reaching(session, repo_id, unanswered, test_files, import_depth)
for seed, tests in found.items():
- out[seed] = ReachedBy(_cut(tests), "import-graph", len(tests))
+ ordered = tuple(sorted(tests))
+ out[seed] = ReachedBy(
+ list(ordered[:MAX_TESTS_PER_TARGET]), "import-graph", len(ordered), ordered
+ )
return out
-def _cut(tests: set[str]) -> list[str]:
- return sorted(tests)[:MAX_TESTS_PER_TARGET]
-
-
async def _call_reaching(
session: AsyncSession,
repo_id: str,
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index 74980b89e..83bdcec99 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -20,6 +20,7 @@ from .coverage_map import (
get_test_coverage_summary,
save_test_coverage,
tests_covering,
+ tests_covering_files,
)
from .dead_code import (
get_dead_code_findings,
@@ -96,6 +97,7 @@ __all__ = [
"save_test_coverage",
"sort_metrics_worst_first",
"tests_covering",
+ "tests_covering_files",
"update_dead_code_status",
"update_health_finding_status",
"upsert_health_findings",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py
index 67238ba5f..e6d5f4f30 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage_map.py
@@ -135,6 +135,47 @@ async def tests_covering(
return out
+async def tests_covering_files(
+ session: AsyncSession,
+ repository_id: str,
+ source_files: set[str],
+) -> dict[str, list[dict[str, Any]]]:
+ """Bulk reverse index for recommendation validation.
+
+ Unlike :func:`tests_covering`, this performs one indexed query for the
+ complete target set. Callers may then apply plan-specific line ranges in
+ memory without turning recommendation hydration into one query per plan.
+ Rows and buckets are ordered deterministically; ``covered_lines`` remains
+ complete so a caller can distinguish a measured line hit from a file-only
+ match.
+ """
+ if not source_files:
+ return {}
+ result = await session.execute(
+ select(TestCoverageEntry)
+ .where(
+ TestCoverageEntry.repository_id == repository_id,
+ TestCoverageEntry.source_file.in_(sorted(source_files)),
+ )
+ .order_by(
+ TestCoverageEntry.source_file.asc(),
+ TestCoverageEntry.test_id.asc(),
+ TestCoverageEntry.test_file.asc(),
+ )
+ )
+ out: dict[str, list[dict[str, Any]]] = {}
+ for row in result.scalars().all():
+ out.setdefault(row.source_file, []).append(
+ {
+ "test_id": row.test_id,
+ "test_file": row.test_file,
+ "covered_lines": _decode_lines(row),
+ "source_format": row.source_format,
+ }
+ )
+ return out
+
+
async def covered_source_files(
session: AsyncSession,
repository_id: str,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index c9d1ad603..ef37ad6fe 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -19,6 +19,11 @@ from repowise.core.analysis.health.grading import HEALTHY_MIN, band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics
from repowise.core.analysis.health.perf.opportunities import build_performance_opportunities
+from repowise.core.analysis.health.refactoring.recommendations import (
+ Recommendation,
+ build_recommendations,
+ hydrate_recommendations,
+)
from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
@@ -222,36 +227,10 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:
def _serialize_refactoring(r: Any) -> dict[str, Any]:
- """Serialize a ``RefactoringSuggestion`` ORM row into a structured plan.
-
- The ``*_json`` columns are decoded back into their open dicts so an agent
- reads the concrete plan (the split groups, the evidence, the blast radius)
- rather than a prose string.
- """
-
- def _load(raw: str | None) -> Any:
- try:
- return json.loads(raw) if raw else {}
- except Exception:
- return {}
-
- return {
- # The persisted row id — pass it to ``generate_refactoring_code`` to
- # turn this plan into actual code + a diff (opt-in).
- "id": getattr(r, "id", None),
- "refactoring_type": r.refactoring_type,
- "file_path": r.file_path,
- "target_symbol": r.target_symbol,
- "line_start": r.line_start,
- "line_end": r.line_end,
- "plan": _load(r.plan_json),
- "evidence": _load(r.evidence_json),
- "impact_delta": round(r.impact_delta, 3),
- "effort_bucket": r.effort_bucket,
- "blast_radius": _load(r.blast_radius_json),
- "confidence": r.confidence,
- "source_biomarker": r.source_biomarker,
- }
+ """Compatibility adapter; request paths hydrate through the async service."""
+ if isinstance(r, Recommendation):
+ return r.as_dict()
+ return build_recommendations([r])[0].as_dict()
# ``include`` and ``only`` were different vocabularies: the block a caller
@@ -704,9 +683,12 @@ def _directive(
)
else:
out["plan_note"] = (
- f"No stored plan addresses {lead_biomarker!r}, and this file has no "
- f"plans at all. plan_via will return plans for other files."
+ f"No plan addresses {lead_biomarker!r}; this file has no plans. "
+ "Use the finding itself."
)
+ out["next_action"] = f"investigate {lead_biomarker}"
+ elif addresses:
+ out["next_action"] = "inspect matching plan via plan_via"
return out
@@ -914,6 +896,7 @@ async def get_health(
repo: str | None = None,
limit: int = 20,
only: list[str] | None = None,
+ refactoring_view: str = "canonical",
) -> dict:
"""Code-health scores and findings — self-check a file before/after editing.
@@ -932,23 +915,26 @@ async def get_health(
include: ``biomarkers`` | ``refactoring`` | ``trend`` | ``coverage`` |
``accuracy`` | ``signals`` | ``churn_complexity`` |
``performance``/``defect``/``maintainability`` (dimension).
- ``performance`` also adds causal ``performance_opportunities``;
- raw findings remain available for line inspection. This only adds
- blocks; pair it with ``only`` to project the response. Over-budget
- responses set ``_meta.truncated_to_fit``.
+ ``performance`` adds causal ``performance_opportunities``; with
+ ``refactoring``, a compact ``recommendation_lede``. Only adds
+ blocks; pair with ``only``. Over cap sets ``_meta.truncated_to_fit``.
only: top-level keys to keep; ``["directive"]`` is cheapest and
- ``*_total`` siblings survive. The block names ``biomarkers``,
- ``accuracy`` and ``refactoring`` alias. Dimension names
- ``performance``, ``defect`` and ``maintainability`` do not;
- unknown keys are reported.
+ ``*_total`` siblings survive. Only ``biomarkers``, ``accuracy``
+ and ``refactoring`` alias; ``performance``, ``defect``,
+ ``maintainability`` and ``signals`` do not and land in
+ ``unknown_only_keys``.
repo: usually omitted.
limit: max rows per ranked list (max 50, ``0`` for none).
+ refactoring_view: ``canonical`` (default) or diversified
+ ``file_spread``.
"""
started = perf_counter()
# ``0`` means none, matching the ``module_limit`` convention on the REST
# coverage route. It used to clamp up to 1, so the documented way to ask for
# "the totals, none of the rows" silently returned a row.
limit = min(max(limit, 0), 50)
+ if refactoring_view not in {"canonical", "file_spread"}:
+ refactoring_view = "canonical"
include_set = set(include or [])
only_list = [_ONLY_ALIASES.get(k, k) for k in (only or [])]
only_set = set(only_list)
@@ -974,7 +960,9 @@ async def get_health(
# block that carries findings survives the projection.
wants_findings = wants("findings") or wants("top_findings")
wants_test_findings = wants("test_findings")
- wants_performance_opportunities = wants("performance_opportunities")
+ wants_performance_opportunities = wants("performance_opportunities") or wants(
+ "recommendation_lede"
+ )
# Everything downstream of the test/production split, in one place.
#
# Keep this list exhaustive. The read it gates is not free (the column list
@@ -1288,7 +1276,12 @@ async def get_health(
# Structured refactoring plans (Extract Class, ...) — loaded only when
# asked for, scoped to the same targets, exclude-filtered like findings.
refactoring_rows: list[Any] = []
- if "refactoring" in include_set and not nothing_resolved:
+ refactoring_recommendations: list[Recommendation] = []
+ if (
+ "refactoring" in include_set
+ and (wants("refactoring_plans") or wants("recommendation_lede"))
+ and not nothing_resolved
+ ):
refactoring_rows = filter_rows_by_attr(
await get_refactoring_suggestions(
session,
@@ -1298,6 +1291,13 @@ async def get_health(
"file_path",
exclude_spec,
)
+ refactoring_recommendations = await hydrate_recommendations(
+ session,
+ repository.id,
+ refactoring_rows,
+ metric_rows=all_metrics,
+ view=refactoring_view, # type: ignore[arg-type]
+ )
coverage_rows: list[Any] = []
coverage_summary: dict[str, Any] = {}
@@ -1628,58 +1628,10 @@ async def get_health(
result["test_findings_total"] = test_findings_total
if "refactoring" in include_set:
- # Structured refactoring plans (the concrete split groups / evidence /
- # blast radius) for detectors that have one — the upgrade over the old
- # prose-string suggestions.
- #
- # Rank by the *file's* weighted deficit first, per-plan impact_delta
- # second, and cap to ``limit``. Two reasons: an un-capped dump is a
- # thousands-of-plans firehose that blows the token budget, and a pure
- # impact_delta sort buries the highest-leverage plans — a Split File on a
- # 1200-line hotspot recovers the most repo-average yet can carry a modest
- # per-file delta, so file leverage has to lead. ``refactoring_plans_total``
- # keeps the truncation honest.
- deficit_by_path = {
- m.file_path: round(max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1))
- for m in all_metrics
- }
- # A "plans matching the file's lead biomarker sort first" tiebreak was
- # tried here and removed: measured on this repo, 0 of the top 20 files
- # by deficit have any plan addressing their lead, so it could not move a
- # row inside the cap, while ``deficit`` rounds to an int and ties across
- # files — which would have let the boost reorder *between* files. The
- # honest fix for the mismatch is ``directive.plan_addresses_reason``,
- # which reports it rather than reshuffling around it.
- ranked = sorted(
- refactoring_rows,
- key=lambda r: (deficit_by_path.get(r.file_path, 0), r.impact_delta or 0.0),
- reverse=True,
- )
- # ...then spread the cap across files. Deficit is a *file* property, so a
- # pure deficit sort puts every plan on the worst file ahead of every plan
- # on the second worst: asking for the top 8 returned 8 plans on one file
- # out of 1,903, and an agent asking "what should I refactor?" saw no view
- # of the repo at all. Round-robin one plan per file per pass, files in
- # their ranked order (a file ranks by its best plan) and plans in theirs,
- # so the head spans as many files as it has rows. The order is otherwise
- # unchanged — the worst file still leads, it just no longer owns the list.
- by_file: dict[str, list[Any]] = {}
- for r in ranked:
- by_file.setdefault(r.file_path, []).append(r)
- spread: list[Any] = []
- while len(spread) < limit and by_file:
- for path in list(by_file):
- spread.append(by_file[path].pop(0))
- if not by_file[path]:
- del by_file[path]
- if len(spread) >= limit:
- break
+ # Canonical is the shared REST/MCP/CLI order. File diversity remains
+ # available only through the explicitly named ``file_spread`` view.
result["refactoring_plans"] = [
- {
- **_serialize_refactoring(r),
- "file_weighted_deficit": deficit_by_path.get(r.file_path, 0),
- }
- for r in spread
+ recommendation.as_dict() for recommendation in refactoring_recommendations[:limit]
]
result["refactoring_plans_total"] = len(refactoring_rows)
# The deterministic prose suggestion is the fallback for biomarkers
@@ -1716,6 +1668,7 @@ async def get_health(
"recent": recent_kpis(snapshots, limit=10),
}
+ opportunities = []
if "performance" in include_set and wants_performance_opportunities:
opportunities = build_performance_opportunities(
[row for row in lead_rows if _in_dimensions(row, {"performance"})],
@@ -1726,6 +1679,64 @@ async def get_health(
]
result["performance_opportunities_total"] = len(opportunities)
+ if {"performance", "refactoring"} <= include_set and wants("recommendation_lede"):
+ performance_lead = opportunities[0] if opportunities else None
+ recommendation_lead = (
+ refactoring_recommendations[0] if refactoring_recommendations else None
+ )
+ matching = next(
+ (
+ recommendation
+ for recommendation in refactoring_recommendations
+ if performance_lead is not None
+ and recommendation.suggestion.refactoring_type == "performance_fix"
+ and (recommendation.suggestion.evidence or {}).get("opportunity_id")
+ == performance_lead.opportunity_id
+ ),
+ None,
+ )
+ lead_payload = recommendation_lead.as_dict() if recommendation_lead else None
+ result["recommendation_lede"] = {
+ "performance_opportunities_total": len(opportunities),
+ "refactoring_plans_total": len(refactoring_recommendations),
+ "performance_lead": (
+ {
+ "opportunity_id": performance_lead.opportunity_id,
+ "intervention_symbol": performance_lead.intervention_symbol,
+ "boundary_kind": performance_lead.boundary_kind,
+ "execution_context": performance_lead.execution_context,
+ "affected_call_sites_total": performance_lead.affected_call_sites_total,
+ "rank_score": performance_lead.rank_score,
+ }
+ if performance_lead
+ else None
+ ),
+ "recommendation_lead": (
+ {
+ key: lead_payload[key]
+ for key in (
+ "id",
+ "refactoring_type",
+ "file_path",
+ "target_symbol",
+ "benefit",
+ "leverage",
+ "cost",
+ "risk",
+ "rank_score",
+ "validation",
+ )
+ }
+ if lead_payload
+ else None
+ ),
+ "performance_plan_id": matching.id if matching else None,
+ "next_call": (
+ "get_health(include=['performance','refactoring'], limit=3, "
+ "only=['performance_opportunities','refactoring_plans'])"
+ ),
+ }
+
if "coverage" in include_set:
# Drop the bulky covered-lines arrays from dashboard mode; full
# detail is available in targeted mode.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
index 7979fa6ee..d7d8bf7f5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
@@ -10,10 +10,9 @@ needs the working tree on disk, so it is a local-server capability.
from __future__ import annotations
-import json
from pathlib import Path
-from typing import Any
+from repowise.core.analysis.health.refactoring.recommendations import hydrate_recommendations
from repowise.core.persistence.crud import get_refactoring_suggestion
from repowise.core.persistence.database import get_session
from repowise.core.registry import mcp_tool_registry as mcp
@@ -21,42 +20,6 @@ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context
from repowise.server.mcp_server._meta import build_meta as _build_meta
-def _row_to_suggestion(row: Any) -> Any:
- """Re-hydrate a persisted ORM row into a ``RefactoringSuggestion`` dataclass.
-
- Mirrors the web router's adapter; the enrichment engine reads the open
- ``plan`` / ``evidence`` / ``blast_radius`` dicts, which the DB stores as
- ``*_json`` text.
- """
- from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
-
- def _loads(value: Any) -> dict[str, Any]:
- if not value:
- return {}
- try:
- parsed = json.loads(value)
- except (TypeError, ValueError):
- return {}
- return parsed if isinstance(parsed, dict) else {}
-
- sug = RefactoringSuggestion(
- refactoring_type=row.refactoring_type,
- file_path=row.file_path,
- target_symbol=row.target_symbol,
- line_start=row.line_start,
- line_end=row.line_end,
- plan=_loads(row.plan_json),
- evidence=_loads(row.evidence_json),
- impact_delta=row.impact_delta,
- effort_bucket=row.effort_bucket,
- blast_radius=_loads(row.blast_radius_json),
- confidence=row.confidence,
- source_biomarker=row.source_biomarker,
- )
- sug.id = row.id # type: ignore[attr-defined]
- return sug
-
-
@mcp.tool(default=False)
async def generate_refactoring_code(suggestion_id: str, repo: str | None = None) -> dict:
"""Generate refactored code + a unified diff for one refactoring plan.
@@ -104,7 +67,7 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)
"detail": f"No refactoring plan with id {suggestion_id!r} in this repo.",
"_meta": _build_meta(repository=repository),
}
- sug = _row_to_suggestion(row)
+ sug = (await hydrate_recommendations(session, repository.id, [row]))[0].suggestion
meta = _build_meta(repository=repository)
try:
diff --git a/packages/server/src/repowise/server/routers/code_health/churn_routes.py b/packages/server/src/repowise/server/routers/code_health/churn_routes.py
index 5212e55f9..6d30dd866 100644
--- a/packages/server/src/repowise/server/routers/code_health/churn_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/churn_routes.py
@@ -29,7 +29,7 @@ async def churn_complexity(
One point per recently-changed file: x = 90-day commit count (churn),
y = max cyclomatic complexity, dot size = NLOC, color = health band. The
top-right corner is where churn and complexity collide -- the highest-value
- refactoring targets, plotted instead of listed.
+ health work items, plotted instead of listed.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index 17ac8bfb3..36e41863f 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -1,4 +1,8 @@
-"""Refactoring-target ranking route (impact / effort)."""
+"""Health work/triage queue (impact / effort).
+
+The legacy URL is retained for compatibility; these file-level findings are
+not structured refactoring plans.
+"""
from __future__ import annotations
@@ -47,7 +51,7 @@ def _effort_for_nloc(nloc: int) -> str:
@router.get("/api/repos/{repo_id}/health/refactoring-targets")
-async def refactoring_targets(
+async def health_work_queue(
repo_id: str,
limit: int = Query(200, ge=1, le=500),
module: str | None = Query(None, description="Filter to files in this module path"),
@@ -59,7 +63,7 @@ async def refactoring_targets(
),
session: AsyncSession = Depends(get_db_session),
) -> dict:
- """Refactoring candidates ranked by impact / effort.
+ """Health work items ranked by impact / effort.
A target carries its *primary* finding plus ``finding_count``, not the
findings themselves. Serializing every file's full finding list here cost
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 54a939f44..116ceae13 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -2,10 +2,9 @@
The refactoring layer writes one structured ``RefactoringSuggestion`` row per
opportunity (Extract Class, Extract Helper, Move Method, Break Cycle). These
-endpoints read those rows from SQL and re-apply the unified rank so the order
-the web tab shows matches every other surface (CLI / MCP): a plan on a central
-hub file outranks the same plan on a leaf, blast radius amplifies, confidence
-breaks ties.
+endpoints read those rows through the canonical recommendation service so the
+web tab, CLI, and MCP share priority components and ordering. Centrality is
+leverage; a larger change surface raises cost and risk rather than benefit.
No on-disk work happens here, so this works on hosted backends without a
checkout — the same property the C4 endpoints rely on.
@@ -13,27 +12,17 @@ checkout — the same property the C4 endpoints rely on.
from __future__ import annotations
-import json
from pathlib import Path
-from typing import Any
+from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
-from repowise.core.analysis.health.refactoring.rank import rank_suggestions, score
+from repowise.core.analysis.health.refactoring.recommendations import hydrate_recommendations
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
-
-def blast_files(sug: RefactoringSuggestion) -> list[str]:
- """The other files a plan drags along, from whichever blast-radius shape it
- carries — used to scope the detail endpoint's centrality lookup."""
- files = (sug.blast_radius or {}).get("files")
- return [f for f in files if isinstance(f, str)] if isinstance(files, list) else []
-
-
router = APIRouter(
prefix="/api/repos",
tags=["refactoring"],
@@ -63,6 +52,10 @@ class RefactoringPlanResponse(BaseModel):
blast_radius: dict[str, Any] = Field(default_factory=dict)
confidence: str = "medium"
source_biomarker: str = ""
+ benefit: float = 0.0
+ leverage: float = 0.0
+ cost: float = 0.0
+ risk: float = 0.0
# The unified-rank score (higher = surface sooner). Carried so the tab can
# plot/sort without recomputing the blend client-side.
rank_score: float = 0.0
@@ -79,6 +72,8 @@ class RefactoringPlanResponse(BaseModel):
# same place a missing field would have.
dependents: int = 0
file_nloc: int = 0
+ file_weighted_deficit: int = 0
+ validation: dict[str, Any] = Field(default_factory=dict)
class RefactoringTypeCount(BaseModel):
@@ -101,79 +96,8 @@ class RefactoringTargetsResponse(BaseModel):
# ---------------------------------------------------------------------------
-def _row_to_suggestion(row: Any) -> RefactoringSuggestion:
- """Re-hydrate a persisted ORM row into the ranking dataclass.
-
- The rank module operates on ``RefactoringSuggestion`` dataclasses (open
- ``plan`` / ``blast_radius`` dicts); the DB stores those as ``*_json`` text.
- We stash the row id on the instance so the ranked order can be serialized
- back with its id intact (dataclass instances accept extra attributes)."""
-
- def _loads(value: Any) -> dict[str, Any]:
- if not value:
- return {}
- try:
- parsed = json.loads(value)
- except (TypeError, ValueError):
- return {}
- return parsed if isinstance(parsed, dict) else {}
-
- sug = RefactoringSuggestion(
- refactoring_type=row.refactoring_type,
- file_path=row.file_path,
- target_symbol=row.target_symbol,
- line_start=row.line_start,
- line_end=row.line_end,
- plan=_loads(row.plan_json),
- evidence=_loads(row.evidence_json),
- impact_delta=row.impact_delta,
- effort_bucket=row.effort_bucket,
- blast_radius=_loads(row.blast_radius_json),
- confidence=row.confidence,
- source_biomarker=row.source_biomarker,
- )
- sug.id = row.id # type: ignore[attr-defined]
- return sug
-
-
-def _to_response(
- sug: RefactoringSuggestion,
- centrality: dict[str, float],
- nloc: dict[str, int] | None = None,
-) -> RefactoringPlanResponse:
- return RefactoringPlanResponse(
- id=getattr(sug, "id", ""),
- refactoring_type=sug.refactoring_type,
- file_path=sug.file_path,
- target_symbol=sug.target_symbol,
- line_start=sug.line_start,
- line_end=sug.line_end,
- plan=sug.plan or {},
- evidence=sug.evidence or {},
- impact_delta=sug.impact_delta,
- effort_bucket=sug.effort_bucket,
- blast_radius=sug.blast_radius or {},
- confidence=sug.confidence,
- source_biomarker=sug.source_biomarker,
- rank_score=round(score(sug, centrality), 4),
- dependents=int(centrality.get(sug.file_path, 0.0)),
- file_nloc=int((nloc or {}).get(sug.file_path, 0)),
- )
-
-
-async def _nloc_map(session: AsyncSession, repo_id: str) -> dict[str, int]:
- """File-path → line count, from the health pass. Empty when no health
- snapshot exists yet, which leaves every plan's ``file_nloc`` at 0."""
- metrics = await crud.get_health_metrics(session, repo_id)
- return {m.file_path: int(m.nloc or 0) for m in metrics}
-
-
-async def _centrality_map(session: AsyncSession, repo_id: str) -> dict[str, float]:
- """File-path → in-degree (importer count), the cheap dependency-centrality
- proxy the unified rank reads. Empty when no graph metrics are materialized
- (the rank then degrades to impact × blast × confidence)."""
- metrics = await crud.get_graph_metrics(session, repo_id)
- return {node_id: float(m.get("in_degree") or 0) for node_id, m in metrics.items()}
+def _to_response(data: dict[str, Any]) -> RefactoringPlanResponse:
+ return RefactoringPlanResponse(**data)
# ---------------------------------------------------------------------------
@@ -191,6 +115,9 @@ async def get_refactoring_targets(
),
min_confidence: str | None = Query(None, description="low | medium | high"),
file_path: str | None = Query(None, description="Filter plans to one repo-relative file path"),
+ view: Literal["canonical", "file_spread"] = Query(
+ "canonical", description="Named ordering view; canonical is the product default"
+ ),
session: AsyncSession = Depends(get_db_session),
) -> RefactoringTargetsResponse:
"""Ranked refactoring plans for the repo, filterable by type, confidence,
@@ -201,9 +128,6 @@ async def get_refactoring_targets(
honor *min_confidence* — so the summary and the plan list stay consistent
under a confidence filter.
"""
- centrality = await _centrality_map(session, repo_id)
- nloc = await _nloc_map(session, repo_id)
-
# Summary is computed over the unfiltered-by-type set so the chips can show
# every type's count even while one type is selected.
all_rows = await crud.get_refactoring_suggestions(
@@ -227,11 +151,10 @@ async def get_refactoring_targets(
)
if file_path is not None:
rows = [r for r in rows if r.file_path == file_path]
- suggestions = [_row_to_suggestion(r) for r in rows]
- ranked = rank_suggestions(suggestions, centrality=centrality)
+ recommendations = await hydrate_recommendations(session, repo_id, rows, view=view)
return RefactoringTargetsResponse(
summary=summary,
- plans=[_to_response(s, centrality, nloc) for s in ranked],
+ plans=[_to_response(recommendation.as_dict()) for recommendation in recommendations],
)
@@ -346,30 +269,8 @@ async def get_refactoring_plan(
row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)
if row is None:
raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")
- sug = _row_to_suggestion(row)
- # Only this plan's file and its blast files affect its score / caller rollup,
- # so fetch in-degree for just those rather than the whole graph_metrics table.
- files = {sug.file_path, *(f for f in blast_files(sug) if isinstance(f, str))}
- centrality: dict[str, float] = {}
- for path in files:
- degrees = await crud.get_node_degree_counts(session, repo_id, path)
- centrality[path] = float(degrees.get("in_degree") or 0)
- # The list endpoint reads in-degree from the materialized `graph_metrics`
- # snapshot; the loop above counts live edges. The two can disagree, and a
- # plan whose `dependents` changed between the row you clicked and the panel
- # that opened is the bug this field exists to end. The snapshot wins for the
- # plan's own file; edge counts still serve the blast-file caller rollup,
- # which is a different question.
- metrics = await crud.get_graph_metrics(session, repo_id)
- snapshot = metrics.get(sug.file_path)
- if snapshot is not None and snapshot.get("in_degree") is not None:
- centrality[sug.file_path] = float(snapshot["in_degree"])
- # Enrich the blast radius the same way the ranking does, so the detail view
- # carries the caller rollup the list ranked on.
- rank_suggestions([sug], centrality=centrality)
- metrics = await crud.get_health_metrics(session, repo_id, file_paths=[sug.file_path])
- nloc = {m.file_path: int(m.nloc or 0) for m in metrics}
- return _to_response(sug, centrality, nloc)
+ recommendation = (await hydrate_recommendations(session, repo_id, [row]))[0]
+ return _to_response(recommendation.as_dict())
# ---------------------------------------------------------------------------
@@ -445,7 +346,8 @@ async def generate_refactoring_code(
row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)
if row is None:
raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")
- sug = _row_to_suggestion(row)
+ recommendation = (await hydrate_recommendations(session, repo_id, [row]))[0]
+ sug = recommendation.suggestion
body = body or GenerateCodeRequest()
try:
diff --git a/packages/types/__tests__/refactoring.test.ts b/packages/types/__tests__/refactoring.test.ts
new file mode 100644
index 000000000..073f3393f
--- /dev/null
+++ b/packages/types/__tests__/refactoring.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+import type { RefactoringPlan } from "../src/refactoring";
+
+const legacyServerPlan: RefactoringPlan = {
+ id: "legacy",
+ refactoring_type: "extract_method",
+ file_path: "src/a.py",
+ target_symbol: "run",
+ line_start: 1,
+ line_end: 20,
+ plan: {},
+ evidence: {},
+ impact_delta: 1,
+ effort_bucket: "M",
+ blast_radius: {},
+ confidence: "medium",
+ source_biomarker: "complex_method",
+ rank_score: 1.25,
+};
+
+describe("refactoring recommendation contract", () => {
+ it("accepts an older server payload with the newer fields missing", () => {
+ expect(legacyServerPlan.benefit).toBeUndefined();
+ expect(legacyServerPlan.validation).toBeUndefined();
+ });
+
+ it("types the canonical validation and priority components", () => {
+ const current: RefactoringPlan = {
+ ...legacyServerPlan,
+ benefit: 2,
+ leverage: 1.5,
+ cost: 2.25,
+ risk: 0.75,
+ validation: {
+ basis: "measured",
+ via: "coverage",
+ total: 1,
+ tests: ["tests/test_a.py::test_run"],
+ truncated: false,
+ affected_files: ["src/a.py"],
+ affected_symbols: ["run"],
+ commands: ["pytest tests/test_a.py::test_run"],
+ targets: [
+ {
+ file_path: "src/a.py",
+ basis: "measured",
+ via: "coverage",
+ total: 1,
+ tests: ["tests/test_a.py::test_run"],
+ truncated: false,
+ },
+ ],
+ },
+ };
+ expect(current.validation?.basis).toBe("measured");
+ expect(current.risk).toBe(0.75);
+ });
+});
diff --git a/packages/types/package.json b/packages/types/package.json
index 470cd8fd5..5c7923230 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -30,7 +30,8 @@
"./external-systems": "./src/external-systems.ts",
"./health": "./src/health.ts",
"./coupling": "./src/coupling.ts",
- "./stats": "./src/stats.ts"
+ "./stats": "./src/stats.ts",
+ "./refactoring": "./src/refactoring.ts"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com",
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index dfb1472d4..f9fa6244f 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -631,10 +631,10 @@ export interface HealthCoverageResponse {
}
/* ------------------------------------------------------------------ *
- * Refactoring targets
+ * Health work queue (legacy route: /health/refactoring-targets)
* ------------------------------------------------------------------ */
-export interface RefactoringTarget {
+export interface HealthWorkItem {
file_path: string;
score: number;
nloc: number;
@@ -670,12 +670,12 @@ export interface RefactoringTarget {
}>;
}
-export interface RefactoringTargetsResponse {
- targets: RefactoringTarget[];
+export interface HealthWorkQueueResponse {
+ targets: HealthWorkItem[];
total: number;
}
-export interface RefactoringQuery {
+export interface HealthWorkQueueQuery {
limit?: number;
module?: string;
biomarker?: string;
@@ -684,6 +684,13 @@ export interface RefactoringQuery {
sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";
}
+/** @deprecated Use HealthWorkItem; this is a file triage row, not a plan. */
+export type RefactoringTarget = HealthWorkItem;
+/** @deprecated Use HealthWorkQueueResponse. */
+export type RefactoringTargetsResponse = HealthWorkQueueResponse;
+/** @deprecated Use HealthWorkQueueQuery. */
+export type RefactoringQuery = HealthWorkQueueQuery;
+
/* ------------------------------------------------------------------ *
* Churn x complexity quadrant (the "hotspot anatomy" view)
* ------------------------------------------------------------------ */
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 82b979e5d..a2b9669bf 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -31,3 +31,4 @@ export * from "./external-systems.js";
export * from "./health.js";
export * from "./coupling.js";
export * from "./stats.js";
+export * from "./refactoring.js";
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
new file mode 100644
index 000000000..2d19a9881
--- /dev/null
+++ b/packages/types/src/refactoring.ts
@@ -0,0 +1,100 @@
+/** Canonical wire contract for structured refactoring recommendations. */
+
+export type RefactoringType =
+ | "extract_class"
+ | "extract_helper"
+ | "extract_method"
+ | "move_method"
+ | "break_cycle"
+ | "split_file"
+ | "performance_fix";
+
+export type EffortBucket = "S" | "M" | "L" | "XL";
+export type Confidence = "low" | "medium" | "high";
+export type ValidationBasis = "measured" | "inferred" | "mixed" | "unknown";
+export type ValidationVia = "coverage" | "call-graph" | "import-graph" | "mixed";
+
+export interface RecommendationValidationTarget {
+ file_path: string;
+ basis: ValidationBasis;
+ via: ValidationVia | null;
+ total: number;
+ tests: string[];
+ truncated: boolean;
+}
+
+export interface RecommendationValidation {
+ basis: ValidationBasis;
+ via: ValidationVia | null;
+ total: number;
+ tests: string[];
+ truncated: boolean;
+ affected_files: string[];
+ affected_symbols: string[];
+ commands: string[];
+ targets: RecommendationValidationTarget[];
+}
+
+export interface RefactoringPlan {
+ id: string;
+ refactoring_type: RefactoringType | string;
+ file_path: string;
+ target_symbol: string;
+ line_start: number | null;
+ line_end: number | null;
+ plan: Record<string, unknown>;
+ evidence: Record<string, unknown>;
+ impact_delta: number;
+ effort_bucket: EffortBucket | string;
+ blast_radius: Record<string, unknown>;
+ confidence: Confidence | string;
+ source_biomarker: string;
+ /** Compatibility priority. Older servers already provide this field. */
+ rank_score: number;
+ /** Optional so a newer client can read a payload from a server that predates them. */
+ benefit?: number;
+ leverage?: number;
+ cost?: number;
+ risk?: number;
+ dependents?: number;
+ file_nloc?: number;
+ file_weighted_deficit?: number;
+ validation?: RecommendationValidation;
+}
+
+export interface RefactoringTypeCount {
+ type: string;
+ count: number;
+}
+
+export interface RefactoringSummary {
+ total: number;
+ by_type: RefactoringTypeCount[];
+}
+
+export interface RefactoringTargets {
+ summary: RefactoringSummary;
+ plans: RefactoringPlan[];
+}
+
+export interface GeneratedSpan {
+ file: string;
+ line_start: number;
+ line_end: number;
+}
+
+export interface GeneratedCode {
+ suggestion_id: string | null;
+ refactoring_type: string;
+ file_path: string;
+ target_symbol: string;
+ content: string;
+ diff: string;
+ provider: string;
+ model: string;
+ cached: boolean;
+ input_tokens: number;
+ output_tokens: number;
+ validation: Record<string, unknown>;
+ spans: GeneratedSpan[];
+}
diff --git a/packages/ui/__tests__/health/refactoring-target-list.test.tsx b/packages/ui/__tests__/health/refactoring-target-list.test.tsx
index 0e59eac56..04c78fa21 100644
--- a/packages/ui/__tests__/health/refactoring-target-list.test.tsx
+++ b/packages/ui/__tests__/health/refactoring-target-list.test.tsx
@@ -27,8 +27,8 @@ function targets(n: number): RefactoringTarget[] {
}
function renderedPaths(): string[] {
- return Array.from(document.querySelectorAll("[data-refactoring-card]")).map(
- (el) => el.getAttribute("data-refactoring-card") ?? "",
+ return Array.from(document.querySelectorAll("[data-health-work-item]")).map(
+ (el) => el.getAttribute("data-health-work-item") ?? "",
);
}
diff --git a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
index 2e8758d66..6dd06fa49 100644
--- a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
+++ b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
@@ -96,4 +96,26 @@ describe("extract_method suggested_name reaches the rendered prompt", () => {
expect(prompt).toContain("a clearly named helper");
expect(extractMethodPlan(methodPlan(null)).suggested_name).toBeNull();
});
+
+ it("includes the canonical validation plan in copy-to-agent handoff", () => {
+ const plan: RefactoringPlan = {
+ ...methodPlan("compute_average"),
+ validation: {
+ basis: "measured",
+ via: "coverage",
+ total: 1,
+ tests: ["tests/test_pipeline.py::test_average"],
+ truncated: false,
+ affected_files: ["pkg/pipeline.py"],
+ affected_symbols: ["run_pipeline"],
+ commands: ["pytest tests/test_pipeline.py::test_average"],
+ targets: [],
+ },
+ };
+ const prompt = buildRefactoringPlanPrompt({ plan });
+ expect(prompt).toContain("## Validation plan");
+ expect(prompt).toContain("guarding test via coverage");
+ expect(prompt).toContain("tests/test_pipeline.py::test_average");
+ expect(prompt).toContain("pytest tests/test_pipeline.py::test_average");
+ });
});
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index f5de05b94..9fd66fc5a 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -13,9 +13,10 @@
*/
import { deadCodeRiskFactorLabel } from "@repowise-dev/types/dead-code";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
-import type { RefactoringTarget } from "./refactoring-card";
+import type { HealthWorkItem } from "./refactoring-card";
import {
blastFiles,
cutEdges,
@@ -25,7 +26,6 @@ import {
extractMethodPlan,
helperSite,
moveTarget,
- type RefactoringPlan,
} from "../refactoring/types";
import { typeMeta } from "../refactoring/meta";
@@ -169,7 +169,7 @@ function biomarkerExtraContext(
return null;
}
-function effortHint(effort: RefactoringTarget["effort_bucket"]): string {
+function effortHint(effort: HealthWorkItem["effort_bucket"]): string {
switch (effort) {
case "S":
return "Small (≤40 NLOC) — should be doable in one focused pass.";
@@ -187,7 +187,7 @@ function effortHint(effort: RefactoringTarget["effort_bucket"]): string {
// ─────────────────────────────────────────────────────────────────────
export interface BuildPromptOptions {
- target: RefactoringTarget;
+ target: HealthWorkItem;
flavor?: AiPromptFlavor;
repoName?: string;
}
@@ -1315,6 +1315,40 @@ function planSourceLink(path: string, start: number | null, end: number | null):
return `\`${path}\``;
}
+function recommendationValidation(plan: RefactoringPlan): string {
+ const validation = plan.validation;
+ if (!validation) return "";
+ const evidence =
+ validation.basis === "unknown"
+ ? "No measured or inferred guarding test was found; treat this as a validation gap."
+ : `${validation.total} guarding test${validation.total === 1 ? "" : "s"} via ${
+ validation.via ?? validation.basis
+ }${validation.truncated ? ` (showing ${validation.tests.length})` : ""}.`;
+ return [
+ "## Validation plan",
+ "",
+ bulletList([
+ evidence,
+ validation.tests.length
+ ? `Tests: ${validation.tests.map((test) => `\`${test}\``).join(", ")}.`
+ : null,
+ validation.affected_files.length
+ ? `Affected files: ${validation.affected_files
+ .map((file) => `\`${file}\``)
+ .join(", ")}.`
+ : null,
+ validation.affected_symbols.length
+ ? `Affected symbols: ${validation.affected_symbols
+ .map((symbol) => `\`${symbol}\``)
+ .join(", ")}.`
+ : null,
+ validation.commands.length
+ ? `Run: ${validation.commands.map((command) => `\`${command}\``).join("; ")}.`
+ : null,
+ ]),
+ ].join("\n");
+}
+
/** Render the concrete, type-specific steps the agent should carry out. The
* detection is already done deterministically; this is the executable plan. */
function refactoringPlanSteps(plan: RefactoringPlan): string {
@@ -1413,6 +1447,7 @@ export function buildRefactoringPlanPrompt({
const repoLine = repoName ? ` (\`${repoName}\`)` : "";
const meta = typeMeta(plan.refactoring_type);
const files = blastFiles(plan).filter((f) => f !== plan.file_path);
+ const validation = recommendationValidation(plan);
const constraintList = [
"Preserve behavior exactly — this is a refactoring, not a feature change. No public API or observable behavior should shift.",
@@ -1451,6 +1486,8 @@ export function buildRefactoringPlanPrompt({
"",
refactoringPlanSteps(plan),
"",
+ validation,
+ "",
"## Hard constraints",
"",
bulletList(constraintList),
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index 94fc02f6f..17de1e561 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -5,8 +5,8 @@ import type {
HealthFilesResponse,
HealthFinding,
HealthOverviewResponse,
- RefactoringQuery,
- RefactoringTargetsResponse,
+ HealthWorkQueueQuery,
+ HealthWorkQueueResponse,
TestsReachingFile,
} from "@repowise-dev/types/health";
@@ -48,9 +48,13 @@ export interface CodeHealthAdapter {
getOverview(limit: number): Promise<HealthOverviewResponse>;
listFindings(opts?: CodeHealthFindingsQuery): Promise<HealthFinding[]>;
listFiles(opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
- getRefactoringTargets(
- opts?: RefactoringQuery,
- ): Promise<RefactoringTargetsResponse>;
+ getHealthWorkQueue?(
+ opts?: HealthWorkQueueQuery,
+ ): Promise<HealthWorkQueueResponse>;
+ /** @deprecated Legacy adapter name; FindingsView accepts it during migration. */
+ getRefactoringTargets?(
+ opts?: HealthWorkQueueQuery,
+ ): Promise<HealthWorkQueueResponse>;
updateFindingStatus(
findingId: string,
status: FindingStatusValue,
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index f1627be0e..d130fcefe 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -2,7 +2,7 @@
/**
* Findings view — the engineer's workbench. The ranked fix-next queue
- * (refactoring targets + file inventory), the cross-function performance-risk
+ * (health work items + file inventory), the cross-function performance-risk
* panel, and the function-level / hidden-coupling panels.
*
* Split out of {@link TriageView} so the landing surface stays an airy
@@ -18,8 +18,8 @@ import type {
HealthFinding,
HealthFilesResponse,
HealthOverviewResponse,
- RefactoringQuery,
- RefactoringTargetsResponse,
+ HealthWorkQueueQuery,
+ HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
import { Skeleton } from "../ui/skeleton";
@@ -33,11 +33,11 @@ import { BiomarkerList } from "./biomarker-list";
import { HotFunctionsPanel } from "./hot-functions-panel";
import { HiddenCouplingList } from "./hidden-coupling-list";
import {
- RefactoringTargetList,
+ HealthWorkQueueList,
type FindingStatus,
- type RefactoringTarget,
+ type HealthWorkItem,
} from "./refactoring-target-list";
-import type { RefactoringTargetFinding } from "./refactoring-card";
+import type { HealthWorkItemFinding } from "./refactoring-card";
import { FilterSelect, FilterChip, ViewToggle } from "./code-health-controls";
import { ImpactEffortQuadrant } from "./impact-effort-quadrant";
import { biomarkerLabel } from "./biomarker-glossary";
@@ -113,12 +113,12 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
const [biomarker, setBiomarker] = useState<string>("all");
const [maxEffort, setMaxEffort] = useState<string>("all");
- const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
+ const [sort, setSort] = useState<HealthWorkQueueQuery["sort"]>("impact_per_effort");
const [groupBy, setGroupBy] = useState<GroupBy>("none");
const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);
const [view, setView] = useState<QueueView>("queue");
const [selectedFile, setSelectedFile] = useState<string | null>(null);
- const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
+ const [promptTarget, setPromptTarget] = useState<HealthWorkItem | null>(null);
// The targets list no longer ships `all_findings` — it cost 1.8 MB per
// request to serve two click-gated consumers. Both fetch here instead.
@@ -128,11 +128,11 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
(await adapter.listFindings({
file_path: filePath,
limit: 1000,
- })) as RefactoringTargetFinding[];
+ })) as HealthWorkItemFinding[];
// The prompt promises the agent "every marker", so hydrate before opening
// rather than letting the builder fall back to the primary finding alone.
- const openPrompt = async (t: RefactoringTarget) => {
+ const openPrompt = async (t: HealthWorkItem) => {
setPromptTarget(t);
try {
setPromptTarget({ ...t, all_findings: await loadFindings(t.file_path) });
@@ -147,14 +147,18 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),
[cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],
);
+ const loadHealthWorkQueue = (opts: HealthWorkQueueQuery) => {
+ const load = adapter.getHealthWorkQueue ?? adapter.getRefactoringTargets;
+ return load ? load(opts) : Promise.resolve({ targets: [], total: 0 });
+ };
const {
data: queue,
isLoading: queueLoading,
mutate: mutateQueue,
- } = useSWR<RefactoringTargetsResponse>(
+ } = useSWR<HealthWorkQueueResponse>(
overview ? `code-health-queue:${queueKey}` : null,
() =>
- adapter.getRefactoringTargets({
+ loadHealthWorkQueue({
limit: queueLimit,
...(biomarker !== "all" && { biomarker }),
...(minSeverity !== "all" && { min_severity: minSeverity }),
@@ -334,7 +338,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
<FilterSelect
label="Sort"
value={sort ?? "impact_per_effort"}
- onChange={(v) => setSort(v as RefactoringQuery["sort"])}
+ onChange={(v) => setSort(v as HealthWorkQueueQuery["sort"])}
options={[
{ value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
{ value: "total_impact", label: "Total impact" },
@@ -391,7 +395,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
</span>
</h3>
) : null}
- <RefactoringTargetList
+ <HealthWorkQueueList
targets={g.targets}
onSelect={(t) => setSelectedFile(t.file_path)}
onStatusChange={handleStatus}
diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsx
index aa72e2a12..36be1a55a 100644
--- a/packages/ui/src/health/impact-effort-quadrant.tsx
+++ b/packages/ui/src/health/impact-effort-quadrant.tsx
@@ -30,7 +30,7 @@ export function ImpactEffortQuadrant({
if (data.length === 0) {
return (
<div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)]">
- No refactoring targets to plot yet.
+ No health work items to plot yet.
</div>
);
}
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index d5c6c508b..cbe7e10c9 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -10,7 +10,7 @@ import { SeverityMark } from "./severity-mark";
export type EffortBucket = "S" | "M" | "L" | "XL";
-export interface RefactoringTargetFinding {
+export interface HealthWorkItemFinding {
id: string;
biomarker_type: string;
severity: Severity;
@@ -23,7 +23,7 @@ export interface RefactoringTargetFinding {
details?: BiomarkerDetailsRecord | null;
}
-export interface RefactoringTarget {
+export interface HealthWorkItem {
file_path: string;
score: number;
nloc: number;
@@ -41,16 +41,16 @@ export interface RefactoringTarget {
biomarkers: string[];
effort_bucket: EffortBucket;
impact_per_effort: number;
- all_findings?: RefactoringTargetFinding[];
+ all_findings?: HealthWorkItemFinding[];
}
export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";
-export interface RefactoringCardProps {
- target: RefactoringTarget;
- onSelect?: ((target: RefactoringTarget) => void) | undefined;
+export interface HealthWorkItemCardProps {
+ target: HealthWorkItem;
+ onSelect?: ((target: HealthWorkItem) => void) | undefined;
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
- onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
+ onGeneratePrompt?: ((target: HealthWorkItem) => void) | undefined;
/**
* Fetch this file's findings, called on first expand. The list response
* deliberately omits them — serializing every file's findings to render a
@@ -59,7 +59,7 @@ export interface RefactoringCardProps {
* an older payload still expands.
*/
onLoadFindings?:
- | ((filePath: string) => Promise<RefactoringTargetFinding[]>)
+ | ((filePath: string) => Promise<HealthWorkItemFinding[]>)
| undefined;
expandable?: boolean;
/** Flash-highlight the card (e.g. after a quadrant dot click scrolled to it). */
@@ -80,7 +80,7 @@ const effortColor: Record<EffortBucket, string> = {
XL: "bg-[var(--color-error)]/15 text-[var(--color-error)]",
};
-export function RefactoringCard({
+export function HealthWorkItemCard({
target,
onSelect,
onStatusChange,
@@ -88,9 +88,9 @@ export function RefactoringCard({
onLoadFindings,
expandable = true,
highlighted = false,
-}: RefactoringCardProps) {
+}: HealthWorkItemCardProps) {
const [expanded, setExpanded] = useState(false);
- const [loaded, setLoaded] = useState<RefactoringTargetFinding[] | null>(null);
+ const [loaded, setLoaded] = useState<HealthWorkItemFinding[] | null>(null);
const [loadFailed, setLoadFailed] = useState(false);
// `finding_count` is on every target, so the expander's presence and its
@@ -112,7 +112,7 @@ export function RefactoringCard({
};
return (
<div
- data-refactoring-card={target.file_path}
+ data-health-work-item={target.file_path}
className={`rounded-lg border bg-[var(--color-bg-surface)] overflow-hidden transition-colors ${
highlighted
? "border-[var(--color-accent-primary)] ring-1 ring-[var(--color-accent-primary)]/40"
@@ -246,6 +246,12 @@ export function RefactoringCard({
);
}
+/** @deprecated Health queue compatibility names; these are not structured plans. */
+export type RefactoringTarget = HealthWorkItem;
+export type RefactoringTargetFinding = HealthWorkItemFinding;
+export type RefactoringCardProps = HealthWorkItemCardProps;
+export const RefactoringCard = HealthWorkItemCard;
+
function StatusButton({
current,
value,
diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsx
index 252f2df60..b37e2ab8b 100644
--- a/packages/ui/src/health/refactoring-target-list.tsx
+++ b/packages/ui/src/health/refactoring-target-list.tsx
@@ -2,9 +2,9 @@
import { useEffect, useMemo, useState } from "react";
import {
- RefactoringCard,
- type RefactoringTarget,
- type RefactoringTargetFinding,
+ HealthWorkItemCard,
+ type HealthWorkItem,
+ type HealthWorkItemFinding,
type FindingStatus,
} from "./refactoring-card";
@@ -19,29 +19,29 @@ import {
*/
const CARD_PAGE = 50;
-export interface RefactoringTargetListProps {
- targets: RefactoringTarget[];
- onSelect?: ((target: RefactoringTarget) => void) | undefined;
+export interface HealthWorkQueueListProps {
+ targets: HealthWorkItem[];
+ onSelect?: ((target: HealthWorkItem) => void) | undefined;
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
- onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
+ onGeneratePrompt?: ((target: HealthWorkItem) => void) | undefined;
/** Per-card lazy fetch of a file's findings; see `RefactoringCardProps`. */
onLoadFindings?:
- | ((filePath: string) => Promise<RefactoringTargetFinding[]>)
+ | ((filePath: string) => Promise<HealthWorkItemFinding[]>)
| undefined;
emptyMessage?: string;
/** File path of the card to flash-highlight (quadrant click). */
highlightedPath?: string | null | undefined;
}
-export function RefactoringTargetList({
+export function HealthWorkQueueList({
targets,
onSelect,
onStatusChange,
onGeneratePrompt,
onLoadFindings,
- emptyMessage = "No refactoring targets match the current filters.",
+ emptyMessage = "No health work items match the current filters.",
highlightedPath,
-}: RefactoringTargetListProps) {
+}: HealthWorkQueueListProps) {
const [visible, setVisible] = useState(CARD_PAGE);
// A new list is a new question — re-filtering or re-sorting must not leave
@@ -76,7 +76,7 @@ export function RefactoringTargetList({
<>
<div className="grid gap-3">
{targets.slice(0, shown).map((t) => (
- <RefactoringCard
+ <HealthWorkItemCard
key={t.file_path}
target={t}
onSelect={onSelect}
@@ -100,4 +100,9 @@ export function RefactoringTargetList({
);
}
-export type { RefactoringTarget, FindingStatus } from "./refactoring-card";
+export type { FindingStatus, HealthWorkItem } from "./refactoring-card";
+
+/** @deprecated Use HealthWorkQueueList; this is a health triage queue. */
+export type RefactoringTargetListProps = HealthWorkQueueListProps;
+export const RefactoringTargetList = HealthWorkQueueList;
+export type { RefactoringTarget } from "./refactoring-card";
diff --git a/packages/ui/src/refactoring/generate-code-panel.tsx b/packages/ui/src/refactoring/generate-code-panel.tsx
index aa0751113..cb1dcfb74 100644
--- a/packages/ui/src/refactoring/generate-code-panel.tsx
+++ b/packages/ui/src/refactoring/generate-code-panel.tsx
@@ -5,10 +5,9 @@ import { Check, Copy, Loader2, RotateCw, Sparkles, TriangleAlert, Wand2 } from "
import { DiffView } from "./diff-view";
import {
generatedVerdict,
- type GeneratedCode,
- type RefactoringPlan,
type VerdictTone,
} from "./types";
+import type { GeneratedCode, RefactoringPlan } from "@repowise-dev/types/refactoring";
import { toFriendlyMessage } from "../lib/errors";
/**
diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsx
index 5487a88dd..59dc9d2e4 100644
--- a/packages/ui/src/refactoring/meta.tsx
+++ b/packages/ui/src/refactoring/meta.tsx
@@ -2,7 +2,7 @@
import * as React from "react";
import { ArrowRightLeft, CopyMinus, FileStack, Scissors, Split, Unlink } from "lucide-react";
-import type { Confidence, EffortBucket, RefactoringType } from "./types";
+import type { Confidence, EffortBucket, RefactoringType } from "@repowise-dev/types/refactoring";
export interface RefactoringTypeMeta {
label: string;
diff --git a/packages/ui/src/refactoring/plan-before.tsx b/packages/ui/src/refactoring/plan-before.tsx
index 9261e2889..80b0d48a9 100644
--- a/packages/ui/src/refactoring/plan-before.tsx
+++ b/packages/ui/src/refactoring/plan-before.tsx
@@ -8,8 +8,8 @@ import {
moveTarget,
splitGroups,
splitResidual,
- type RefactoringPlan,
} from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface PlanBeforeProps {
plan: RefactoringPlan;
diff --git a/packages/ui/src/refactoring/plan-comparison.tsx b/packages/ui/src/refactoring/plan-comparison.tsx
index 0b035b594..a3eeaca37 100644
--- a/packages/ui/src/refactoring/plan-comparison.tsx
+++ b/packages/ui/src/refactoring/plan-comparison.tsx
@@ -3,7 +3,7 @@
import { ArrowDown, ArrowRight } from "lucide-react";
import { PlanBefore } from "./plan-before";
import { PlanDetail } from "./plan-detail";
-import type { RefactoringPlan } from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface PlanComparisonProps {
plan: RefactoringPlan;
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index c470ef218..559719e23 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -15,8 +15,8 @@ import {
splitGroups,
splitResidual,
splitShimRequired,
- type RefactoringPlan,
} from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface PlanDetailProps {
plan: RefactoringPlan;
diff --git a/packages/ui/src/refactoring/plan-rows.tsx b/packages/ui/src/refactoring/plan-rows.tsx
index 0fdf4500a..72733f5b8 100644
--- a/packages/ui/src/refactoring/plan-rows.tsx
+++ b/packages/ui/src/refactoring/plan-rows.tsx
@@ -21,7 +21,8 @@ import * as React from "react";
import { formatNumber } from "../lib/format";
import { typeMeta } from "./meta";
-import { blastCount, planSynopsis, type RefactoringPlan } from "./types";
+import { blastCount, planSynopsis } from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface PlanRowsProps {
plans: RefactoringPlan[];
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index 585cd4a53..a03e38d34 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -27,10 +27,12 @@ import { CONFIDENCE_LABEL } from "./meta";
import {
blastCount,
isStructural,
- type Confidence,
- type EffortBucket,
- type RefactoringPlan,
} from "./types";
+import type {
+ Confidence,
+ EffortBucket,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
const PAGE_SIZE = 60;
diff --git a/packages/ui/src/refactoring/refactoring-drawer.tsx b/packages/ui/src/refactoring/refactoring-drawer.tsx
index 4bfbd20ce..a590c840b 100644
--- a/packages/ui/src/refactoring/refactoring-drawer.tsx
+++ b/packages/ui/src/refactoring/refactoring-drawer.tsx
@@ -31,11 +31,13 @@ import {
blastFiles,
evidenceRows,
planWins,
- type Confidence,
- type EffortBucket,
- type GeneratedCode,
- type RefactoringPlan,
} from "./types";
+import type {
+ Confidence,
+ EffortBucket,
+ GeneratedCode,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
export interface RefactoringDrawerProps {
plan: RefactoringPlan | null;
diff --git a/packages/ui/src/refactoring/refactoring-lede.tsx b/packages/ui/src/refactoring/refactoring-lede.tsx
index 74d89e588..d34268e87 100644
--- a/packages/ui/src/refactoring/refactoring-lede.tsx
+++ b/packages/ui/src/refactoring/refactoring-lede.tsx
@@ -18,7 +18,8 @@ import { PageLede } from "../shared/page-lede";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { formatNumber } from "../lib/format";
import { typeMeta } from "./meta";
-import { isStructural, planPoint, type RefactoringPlan } from "./types";
+import { isStructural, planPoint } from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface RefactoringLedeProps {
plans: RefactoringPlan[];
diff --git a/packages/ui/src/refactoring/refactoring-plan-card.tsx b/packages/ui/src/refactoring/refactoring-plan-card.tsx
index e88505014..c337e5b6e 100644
--- a/packages/ui/src/refactoring/refactoring-plan-card.tsx
+++ b/packages/ui/src/refactoring/refactoring-plan-card.tsx
@@ -5,10 +5,12 @@ import { CONFIDENCE_DOT, CONFIDENCE_LABEL, EFFORT_LABEL, typeAccent, typeMeta }
import {
blastCount,
planSynopsis,
- type Confidence,
- type EffortBucket,
- type RefactoringPlan,
} from "./types";
+import type {
+ Confidence,
+ EffortBucket,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
export interface RefactoringPlanCardProps {
plan: RefactoringPlan;
diff --git a/packages/ui/src/refactoring/start-here.tsx b/packages/ui/src/refactoring/start-here.tsx
index 4fbc4a0e2..f02e15575 100644
--- a/packages/ui/src/refactoring/start-here.tsx
+++ b/packages/ui/src/refactoring/start-here.tsx
@@ -31,8 +31,8 @@ import {
planPoint,
planReason,
planSynopsis,
- type RefactoringPlan,
} from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface StartHereProps {
/** Structural plans, already in rank order. */
diff --git a/packages/ui/src/refactoring/structural-map.tsx b/packages/ui/src/refactoring/structural-map.tsx
index 837b383ba..88855bce0 100644
--- a/packages/ui/src/refactoring/structural-map.tsx
+++ b/packages/ui/src/refactoring/structural-map.tsx
@@ -29,7 +29,8 @@ import * as React from "react";
import { formatNumber } from "../lib/format";
import { typeMeta } from "./meta";
-import { planPoint, type RefactoringPlan } from "./types";
+import { planPoint } from "./types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface StructuralMapProps {
/** Structural plans. Those without both figures are dropped and counted. */
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 44dd0260a..63374f6b9 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -7,60 +7,27 @@
* type's shape so the plan renderer can read them without `any`.
*/
-export type RefactoringType =
- | "extract_class"
- | "extract_helper"
- | "extract_method"
- | "move_method"
- | "break_cycle"
- | "split_file";
-
-export type EffortBucket = "S" | "M" | "L" | "XL";
-export type Confidence = "low" | "medium" | "high";
-
-export interface RefactoringPlan {
- id: string;
- refactoring_type: RefactoringType | string;
- file_path: string;
- target_symbol: string;
- line_start: number | null;
- line_end: number | null;
- plan: Record<string, unknown>;
- evidence: Record<string, unknown>;
- impact_delta: number;
- effort_bucket: EffortBucket | string;
- blast_radius: Record<string, unknown>;
- confidence: Confidence | string;
- source_biomarker: string;
- rank_score: number;
- /**
- * Files that import this plan's file, and the file's line count. Served
- * rather than derived: `blast_radius` carries a count under three different
- * keys depending on the detector, so reading it here produced two different
- * numbers for the same file.
- *
- * Optional so a frontend ahead of its backend degrades — an older server
- * simply omits them and the structural map renders nothing rather than
- * plotting every plan at the origin.
- */
- dependents?: number;
- file_nloc?: number;
-}
-
-export interface RefactoringTypeCount {
- type: string;
- count: number;
-}
-
-export interface RefactoringSummary {
- total: number;
- by_type: RefactoringTypeCount[];
-}
-
-export interface RefactoringTargets {
- summary: RefactoringSummary;
- plans: RefactoringPlan[];
-}
+import type {
+ GeneratedCode,
+ RefactoringPlan,
+ RefactoringType,
+} from "@repowise-dev/types/refactoring";
+
+export type {
+ Confidence,
+ EffortBucket,
+ GeneratedCode,
+ GeneratedSpan,
+ RecommendationValidation,
+ RecommendationValidationTarget,
+ RefactoringPlan,
+ RefactoringSummary,
+ RefactoringTargets,
+ RefactoringType,
+ RefactoringTypeCount,
+ ValidationBasis,
+ ValidationVia,
+} from "@repowise-dev/types/refactoring";
// ── Per-type plan shapes (the open `plan` dict, read defensively) ──────────
@@ -360,34 +327,6 @@ export interface PlanWin {
// ── Generated code (the opt-in LLM enrichment result) ─────────────────────
-export interface GeneratedSpan {
- file: string;
- line_start: number;
- line_end: number;
-}
-
-/**
- * The result of the "Generate code" action — mirrors the backend
- * `GenerateCodeResponse` (POST `…/refactoring/{id}/generate-code`). `diff` is a
- * unified diff; `validation` is the per-type self-check (open dict, read
- * defensively via {@link generatedVerdict}).
- */
-export interface GeneratedCode {
- suggestion_id: string | null;
- refactoring_type: string;
- file_path: string;
- target_symbol: string;
- content: string;
- diff: string;
- provider: string;
- model: string;
- cached: boolean;
- input_tokens: number;
- output_tokens: number;
- validation: Record<string, unknown>;
- spans: GeneratedSpan[];
-}
-
export type VerdictTone = "pass" | "fail" | "neutral";
export interface GeneratedVerdict {
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index 141570d30..7ee86cf9f 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -42,6 +42,10 @@ export default defineConfig({
"../types/src/external-systems.ts",
),
"@repowise-dev/types/health": path.resolve(__dirname, "../types/src/health.ts"),
+ "@repowise-dev/types/refactoring": path.resolve(
+ __dirname,
+ "../types/src/refactoring.ts",
+ ),
"@repowise-dev/types/coupling": path.resolve(__dirname, "../types/src/coupling.ts"),
"@repowise-dev/types/stats": path.resolve(__dirname, "../types/src/stats.ts"),
"@repowise-dev/types": path.resolve(__dirname, "../types/src/index.ts"),
diff --git a/packages/vscode/src/core/plans.ts b/packages/vscode/src/core/plans.ts
index 0d22c4ec1..c028d47b6 100644
--- a/packages/vscode/src/core/plans.ts
+++ b/packages/vscode/src/core/plans.ts
@@ -1,5 +1,5 @@
import { getRefactoringTargets } from "@repowise-dev/api-client/refactoring";
-import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import type { RepowiseContext } from "./context";
/**
diff --git a/packages/vscode/src/features/agentHandoff.ts b/packages/vscode/src/features/agentHandoff.ts
index 9e981b772..435dbf0bc 100644
--- a/packages/vscode/src/features/agentHandoff.ts
+++ b/packages/vscode/src/features/agentHandoff.ts
@@ -3,7 +3,7 @@ import * as path from "node:path";
import * as vscode from "vscode";
import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
import { typeMeta } from "@repowise-dev/ui/refactoring/meta";
-import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import { CONFIG_SECTION, InternalCommands } from "../constants";
import type { RepowiseContext } from "../core/context";
import { repoRelativePath } from "../core/fileSignals";
diff --git a/packages/vscode/src/features/refactoringLens.ts b/packages/vscode/src/features/refactoringLens.ts
index a90e58d5d..8d9b58c99 100644
--- a/packages/vscode/src/features/refactoringLens.ts
+++ b/packages/vscode/src/features/refactoringLens.ts
@@ -1,7 +1,7 @@
import * as vscode from "vscode";
import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
import { typeMeta } from "@repowise-dev/ui/refactoring/meta";
-import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import { CONFIG_SECTION, InternalCommands } from "../constants";
import type { RepowiseContext } from "../core/context";
import { repoRelativePath } from "../core/fileSignals";
diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.ts
index 73a9808cb..eea4917f3 100644
--- a/packages/vscode/src/shared/webviewMessages.ts
+++ b/packages/vscode/src/shared/webviewMessages.ts
@@ -35,7 +35,7 @@ import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";
import type { ReviewerSuggestion } from "@repowise-dev/api-client/types";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
import type { ArchitectureView } from "@repowise-dev/ui/c4";
-import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring/types";
+import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/types/refactoring";
import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
/** Every editor-tab webview panel the extension can open. */
diff --git a/packages/vscode/webview/src/views/refactoring/App.test.tsx b/packages/vscode/webview/src/views/refactoring/App.test.tsx
index 8fef72231..64c799bf5 100644
--- a/packages/vscode/webview/src/views/refactoring/App.test.tsx
+++ b/packages/vscode/webview/src/views/refactoring/App.test.tsx
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen, fireEvent, waitFor } from "@testing-library/react";
afterEach(cleanup);
-import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import { App } from "./App";
import type { WebviewHost } from "../../runtime/rpc";
diff --git a/packages/vscode/webview/src/views/refactoring/App.tsx b/packages/vscode/webview/src/views/refactoring/App.tsx
index 9d859614c..95ec44dec 100644
--- a/packages/vscode/webview/src/views/refactoring/App.tsx
+++ b/packages/vscode/webview/src/views/refactoring/App.tsx
@@ -14,11 +14,13 @@ import {
blastFiles,
evidenceRows,
planWins,
- type Confidence,
- type EffortBucket,
- type RefactoringPlan,
- type RefactoringTargets,
} from "@repowise-dev/ui/refactoring/types";
+import type {
+ Confidence,
+ EffortBucket,
+ RefactoringPlan,
+ RefactoringTargets,
+} from "@repowise-dev/types/refactoring";
import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
import type { ViewProps } from "../../runtime/mount";
import type { WebviewHost } from "../../runtime/rpc";
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index 4d82ad536..10aef46ec 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -26,7 +26,7 @@ import {
TYPE_ORDER,
typeMeta,
} from "@repowise-dev/ui/refactoring";
-import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/types/refactoring";
import { AiPromptModal, buildRefactoringPlanPrompt } from "@repowise-dev/ui/health";
import {
generateRefactoringCode,
diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsx
index 122e1cba7..fdcbe2a99 100644
--- a/packages/web/src/components/code-health/coverage-tab.tsx
+++ b/packages/web/src/components/code-health/coverage-tab.tsx
@@ -13,7 +13,7 @@ import {
getHealthCoverage,
getTestsReaching,
getHealthOverview,
- getRefactoringTargets,
+ getHealthWorkQueue,
listHealthFiles,
listHealthFindings,
updateFindingStatus,
@@ -28,7 +28,7 @@ export function CoverageTab({ repoId: id }: { repoId: string }) {
getOverview: (limit) => getHealthOverview(id, limit),
listFindings: (opts) => listHealthFindings(id, opts),
listFiles: (opts) => listHealthFiles(id, opts),
- getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),
+ getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
updateFindingStatus: (findingId, status) =>
updateFindingStatus(id, findingId, status),
getCoverage: (opts) => getHealthCoverage(id, opts),
diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsx
index a1113fb78..5ccb957e9 100644
--- a/packages/web/src/components/code-health/findings-tab.tsx
+++ b/packages/web/src/components/code-health/findings-tab.tsx
@@ -16,7 +16,7 @@ import {
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getHealthOverview,
- getRefactoringTargets,
+ getHealthWorkQueue,
listHealthFiles,
listHealthFindings,
getHealthCoverage,
@@ -33,7 +33,7 @@ export function FindingsTab({ repoId: id }: { repoId: string }) {
getOverview: (limit) => getHealthOverview(id, limit),
listFindings: (opts) => listHealthFindings(id, opts),
listFiles: (opts) => listHealthFiles(id, opts),
- getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),
+ getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
updateFindingStatus: (findingId, status) =>
updateFindingStatus(id, findingId, status),
getCoverage: (opts) => getHealthCoverage(id, opts),
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index 6e127f65b..03abe8cf5 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -19,7 +19,7 @@ import {
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getHealthOverview,
- getRefactoringTargets,
+ getHealthWorkQueue,
listHealthFiles,
listHealthFindings,
getHealthCoverage,
@@ -85,7 +85,7 @@ export function TriageTab({
getOverview: (limit) => getHealthOverview(id, limit),
listFindings: (opts) => listHealthFindings(id, opts),
listFiles: (opts) => listHealthFiles(id, opts),
- getRefactoringTargets: (opts) => getRefactoringTargets(id, opts),
+ getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
updateFindingStatus: (findingId, status) =>
updateFindingStatus(id, findingId, status),
getCoverage: (opts) => getHealthCoverage(id, opts),
diff --git a/tests/fixtures/recommendation_contract.json b/tests/fixtures/recommendation_contract.json
new file mode 100644
index 000000000..b647dfd09
--- /dev/null
+++ b/tests/fixtures/recommendation_contract.json
@@ -0,0 +1,27 @@
+{
+ "canonical_order": ["Alpha.run", "Beta.run"],
+ "fields": [
+ "id",
+ "refactoring_type",
+ "file_path",
+ "target_symbol",
+ "line_start",
+ "line_end",
+ "plan",
+ "evidence",
+ "impact_delta",
+ "effort_bucket",
+ "blast_radius",
+ "confidence",
+ "source_biomarker",
+ "benefit",
+ "leverage",
+ "cost",
+ "risk",
+ "rank_score",
+ "dependents",
+ "file_nloc",
+ "file_weighted_deficit",
+ "validation"
+ ]
+}
diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.py
index 1a5a6ba8e..304dfbcd5 100644
--- a/tests/unit/cli/test_refactoring_targets_render.py
+++ b/tests/unit/cli/test_refactoring_targets_render.py
@@ -52,10 +52,10 @@ def test_json_includes_move_and_break_plans(capsys):
out = json.loads(capsys.readouterr().out)
types = {p["refactoring_type"] for p in out["refactoring_plans"]}
assert {"move_method", "break_cycle"} <= types
- # Order is preserved from the (already unified-ranked) input.
+ # Raw detector rows are normalized into the canonical recommendation rank.
assert [p["refactoring_type"] for p in out["refactoring_plans"]] == [
- "move_method",
"break_cycle",
+ "move_method",
]
diff --git a/tests/unit/health/test_recommendation_surface_parity.py b/tests/unit/health/test_recommendation_surface_parity.py
new file mode 100644
index 000000000..3531cc158
--- /dev/null
+++ b/tests/unit/health/test_recommendation_surface_parity.py
@@ -0,0 +1,46 @@
+"""Golden REST/MCP/CLI recommendation contract parity."""
+
+from __future__ import annotations
+
+import json
+
+from repowise.cli.commands.health_cmd.refactoring_targets import _render_refactoring_targets
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.recommendations import build_recommendations
+from repowise.server.mcp_server.tool_health import _serialize_refactoring
+from repowise.server.routers.refactoring import _to_response
+
+
+def _plan(target: str, file_path: str) -> RefactoringSuggestion:
+ suggestion = RefactoringSuggestion(
+ refactoring_type="extract_method",
+ file_path=file_path,
+ target_symbol=target,
+ line_start=10,
+ line_end=20,
+ plan={"span": {"start": 12, "end": 18}},
+ evidence={"slice_nloc": 7, "ccn_removed": 2},
+ impact_delta=2.0,
+ effort_bucket="M",
+ blast_radius={"scope": "local"},
+ confidence="high",
+ source_biomarker="complex_method",
+ )
+ suggestion.id = f"plan-{target.lower().replace('.', '-')}"
+ return suggestion
+
+
+def test_golden_surface_fields_and_order_are_identical(fixtures_dir, capsys) -> None:
+ golden = json.loads((fixtures_dir / "recommendation_contract.json").read_text())
+ recommendations = build_recommendations(
+ [_plan("Beta.run", "src/beta.py"), _plan("Alpha.run", "src/alpha.py")]
+ )
+
+ rest = [_to_response(item.as_dict()).model_dump() for item in recommendations]
+ mcp = [_serialize_refactoring(item) for item in recommendations]
+ _render_refactoring_targets([], [], mcp, fmt="json")
+ cli = json.loads(capsys.readouterr().out)["refactoring_plans"]
+
+ assert rest == mcp == cli
+ assert [row["target_symbol"] for row in rest] == golden["canonical_order"]
+ assert list(rest[0]) == golden["fields"]
diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.py
new file mode 100644
index 000000000..ccda6c748
--- /dev/null
+++ b/tests/unit/health/test_recommendations.py
@@ -0,0 +1,343 @@
+"""Recommendation rank and validation contract fixtures."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sqlalchemy import event
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.analysis.health.coverage import TestCoverage
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.recommendations import (
+ apply_view,
+ build_recommendations,
+ build_validation_plan,
+ hydrate_recommendations,
+ rehydrate_suggestion,
+)
+from repowise.core.analysis.test_reachability import ReachedBy
+from repowise.core.persistence.crud import save_test_coverage
+from repowise.core.persistence.database import init_db
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _plan(
+ target: str,
+ *,
+ rtype: str = "extract_class",
+ file_path: str = "src/core.py",
+ impact: float = 2.0,
+ blast: int = 0,
+ evidence: dict | None = None,
+) -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type=rtype,
+ file_path=file_path,
+ target_symbol=target,
+ line_start=10,
+ line_end=20,
+ plan={},
+ evidence=evidence or {},
+ impact_delta=impact,
+ effort_bucket="M",
+ blast_radius={"file_count": blast},
+ confidence="high",
+ source_biomarker="long_function",
+ )
+
+
+def test_larger_blast_radius_increases_risk_not_benefit() -> None:
+ narrow, wide = build_recommendations([_plan("narrow", blast=1), _plan("wide", blast=30)])
+ by_target = {item.suggestion.target_symbol: item for item in (narrow, wide)}
+ assert by_target["wide"].risk > by_target["narrow"].risk
+ assert by_target["wide"].benefit == by_target["narrow"].benefit
+ assert by_target["wide"].rank_score < by_target["narrow"].rank_score
+
+
+def test_performance_fix_uses_detector_native_benefit_at_zero_health_impact() -> None:
+ plan = _plan(
+ "sink",
+ rtype="performance_fix",
+ impact=0.0,
+ evidence={"rank_score": 24, "provenance": "call-site"},
+ )
+ recommendation = build_recommendations([plan])[0]
+ assert recommendation.benefit > 0
+ assert recommendation.rank_score > 0
+
+
+def test_performance_benefit_excludes_call_site_blast_factor() -> None:
+ common = {"multiplier_shape": 3, "boundary_kind": 2, "provenance": 1}
+ narrow = _plan(
+ "narrow",
+ rtype="performance_fix",
+ impact=0.0,
+ blast=1,
+ evidence={"rank_factors": {**common, "affected_call_sites": 1}},
+ )
+ wide = _plan(
+ "wide",
+ rtype="performance_fix",
+ impact=0.0,
+ blast=30,
+ evidence={"rank_factors": {**common, "affected_call_sites": 8}},
+ )
+ recommendations = build_recommendations([narrow, wide])
+ by_target = {item.suggestion.target_symbol: item for item in recommendations}
+ assert by_target["wide"].benefit == by_target["narrow"].benefit
+ assert by_target["wide"].risk > by_target["narrow"].risk
+
+
+def test_zero_health_score_is_not_treated_as_healthy() -> None:
+ plan = _plan("worst")
+ recommendation = build_recommendations(
+ [plan], metric_by_path={"src/core.py": SimpleNamespace(nloc=100, score=0.0)}
+ )[0]
+ assert recommendation.file_weighted_deficit == 800
+ assert recommendation.leverage > 1.0
+
+
+def test_default_order_is_deterministic() -> None:
+ plans = [_plan("B"), _plan("A"), _plan("C", impact=1.0)]
+ forward = [item.suggestion.target_symbol for item in build_recommendations(plans)]
+ reverse = [
+ item.suggestion.target_symbol for item in build_recommendations(list(reversed(plans)))
+ ]
+ assert forward == reverse == ["A", "B", "C"]
+
+
+def test_legacy_persisted_row_rehydrates_without_phase3_fields() -> None:
+ suggestion = rehydrate_suggestion(
+ {
+ "id": "legacy",
+ "refactoring_type": "extract_method",
+ "file_path": "src/legacy.py",
+ "target_symbol": "run",
+ "plan_json": '{"span":{"start":1,"end":5}}',
+ "evidence_json": "{}",
+ "blast_radius_json": "{}",
+ "impact_delta": 1.0,
+ "effort_bucket": "M",
+ "confidence": "medium",
+ }
+ )
+ recommendation = build_recommendations([suggestion])[0]
+ assert recommendation.id == "legacy"
+ assert recommendation.validation.basis == "unknown"
+ assert recommendation.as_dict()["risk"] > 0
+
+
+def test_named_spread_view_does_not_redefine_canonical_priority() -> None:
+ plans = [
+ _plan("A1", file_path="a.py", impact=4),
+ _plan("A2", file_path="a.py", impact=3),
+ _plan("B1", file_path="b.py", impact=2),
+ ]
+ canonical = build_recommendations(plans)
+ spread = apply_view(canonical, "file_spread")
+ assert [item.suggestion.target_symbol for item in canonical] == ["A1", "A2", "B1"]
+ assert [item.suggestion.target_symbol for item in spread] == ["A1", "B1", "A2"]
+ assert {item.suggestion.target_symbol: item.rank_score for item in canonical} == {
+ item.suggestion.target_symbol: item.rank_score for item in spread
+ }
+
+
+def test_measured_coverage_suppresses_inferred_evidence_for_same_target() -> None:
+ plan = _plan("covered")
+ measured = {
+ "src/core.py": [
+ {
+ "test_id": "tests/test_core.py::test_measured",
+ "test_file": "tests/test_core.py",
+ "covered_lines": [12],
+ "source_format": "coverage.py",
+ }
+ ]
+ }
+ inferred = {"src/core.py": ReachedBy(["tests/test_inferred.py"], "call-graph", 1)}
+ validation = build_validation_plan(plan, measured, inferred)
+ assert validation.basis == "measured"
+ assert validation.via == "coverage"
+ assert validation.tests == ["tests/test_core.py::test_measured"]
+
+
+def test_call_graph_evidence_precedes_import_fallback_by_target() -> None:
+ plan = _plan("mixed", file_path="src/a.py")
+ plan.blast_radius = {"files": ["src/b.py"]}
+ inferred = {
+ "src/a.py": ReachedBy(["tests/test_a.py"], "call-graph", 1),
+ "src/b.py": ReachedBy(["tests/test_b.py"], "import-graph", 1),
+ }
+ validation = build_validation_plan(plan, {}, inferred)
+ assert [target.via for target in validation.targets] == ["call-graph", "import-graph"]
+ assert validation.basis == "inferred"
+ assert validation.via == "mixed"
+
+
+def test_capped_test_list_keeps_true_total_and_stable_order() -> None:
+ plan = _plan("capped")
+ reached = ReachedBy(["tests/z.py", "tests/a.py"], "call-graph", 9)
+ validation = build_validation_plan(plan, {}, {"src/core.py": reached}, test_limit=1)
+ assert validation.total == 9
+ assert validation.tests == ["tests/a.py"]
+ assert validation.truncated is True
+ assert validation.targets[0].total == 9
+
+
+def test_aggregate_validation_total_deduplicates_tests_across_targets() -> None:
+ plan = _plan("shared", file_path="src/a.py")
+ plan.blast_radius = {"files": ["src/b.py"]}
+ shared = "tests/test_shared.py"
+ inferred = {
+ "src/a.py": ReachedBy([shared], "call-graph", 1, (shared,)),
+ "src/b.py": ReachedBy([shared], "call-graph", 1, (shared,)),
+ }
+ validation = build_validation_plan(plan, {}, inferred)
+ assert validation.total == 1
+ assert validation.tests == [shared]
+ assert validation.truncated is False
+
+
+async def test_query_count_is_constant_as_plan_and_test_counts_grow() -> None:
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async_session = factory()
+ repo = await insert_repo(async_session)
+ records = [
+ TestCoverage(
+ test_id=f"tests/test_all.py::test_{index}",
+ file_path=f"src/f{index}.py",
+ covered_lines=[10],
+ source_format="coverage.py",
+ test_file="tests/test_all.py",
+ )
+ for index in range(12)
+ ]
+ await save_test_coverage(async_session, repo.id, records[:1], source_format="coverage.py")
+ await async_session.commit()
+
+ statements: list[str] = []
+
+ def record(_conn, _cursor, statement, _params, _context, _many) -> None:
+ statements.append(statement)
+
+ event.listen(engine.sync_engine, "before_cursor_execute", record)
+ try:
+ statements.clear()
+ await hydrate_recommendations(async_session, repo.id, [_plan("one", file_path="src/f0.py")])
+ small = len(statements)
+ await save_test_coverage(async_session, repo.id, records, source_format="coverage.py")
+ await async_session.commit()
+ statements.clear()
+ await hydrate_recommendations(
+ async_session,
+ repo.id,
+ [_plan(str(index), file_path=f"src/f{index}.py") for index in range(12)],
+ )
+ large = len(statements)
+ finally:
+ event.remove(engine.sync_engine, "before_cursor_execute", record)
+ await async_session.close()
+ await engine.dispose()
+ assert small == large
+
+
+def _multi_site_plan() -> RefactoringSuggestion:
+ """A ``performance_fix`` whose call sites all sit in one file (the N+1 shape)."""
+ return RefactoringSuggestion(
+ refactoring_type="performance_fix",
+ file_path="svc/orders.py",
+ target_symbol="load_all",
+ line_start=None,
+ line_end=None,
+ plan={
+ "affected_locations": [
+ {"file_path": "svc/orders.py", "line_start": 10, "line_end": 12},
+ {"file_path": "svc/orders.py", "line_start": 40, "line_end": 42},
+ {"file_path": "svc/orders.py", "line_start": 90, "line_end": 92},
+ ]
+ },
+ evidence={},
+ impact_delta=0.0,
+ effort_bucket="M",
+ blast_radius={},
+ confidence="high",
+ source_biomarker="",
+ )
+
+
+def test_every_call_site_in_one_file_keeps_its_lines() -> None:
+ """Locations accumulate per file; the last one must not evict the others.
+
+ A test covering only the first call site still proves the plan is exercised.
+ While locations overwrote, that coverage stopped intersecting, the plan
+ reported ``unknown`` with no tests, and its rank fell by the unknown-basis
+ risk penalty.
+ """
+ measured = {
+ "svc/orders.py": [
+ {"test_id": "tests/test_orders.py::test_first_site", "covered_lines": [10, 11, 12]}
+ ]
+ }
+ plan = build_validation_plan(_multi_site_plan(), measured, {})
+ assert plan.basis == "measured"
+ assert plan.via == "coverage"
+ assert plan.tests == ["tests/test_orders.py::test_first_site"]
+
+
+def test_a_middle_call_site_is_evidence_too() -> None:
+ """Guards the union rather than a first-wins rule that would also pass above."""
+ measured = {
+ "svc/orders.py": [
+ {"test_id": "tests/test_orders.py::test_middle_site", "covered_lines": [40, 41, 42]}
+ ]
+ }
+ assert build_validation_plan(_multi_site_plan(), measured, {}).basis == "measured"
+
+
+def test_uncovered_lines_in_a_multi_site_plan_stay_unknown() -> None:
+ """The union must not turn into 'any row on the file counts'."""
+ measured = {
+ "svc/orders.py": [
+ {"test_id": "tests/test_orders.py::test_elsewhere", "covered_lines": [500, 501]}
+ ]
+ }
+ assert build_validation_plan(_multi_site_plan(), measured, {}).basis == "unknown"
+
+
+def test_a_truncated_test_list_widens_the_command_past_the_shown_tests() -> None:
+ """A capped list must not produce a command that looks like a full run.
+
+ Enumerating only the displayed tests reads as "this validates the change"
+ while skipping most of the evidence, so the command falls back to the files
+ those tests live in — never narrower than what the plan claims.
+ """
+ reached = ReachedBy(
+ via="call-graph",
+ total=40,
+ tests=[f"tests/test_orders.py::test_{index}" for index in range(40)],
+ all_tests=[f"tests/test_orders.py::test_{index}" for index in range(40)],
+ )
+ plan = build_validation_plan(_multi_site_plan(), {}, {"svc/orders.py": reached}, test_limit=3)
+ assert plan.truncated is True
+ assert len(plan.tests) == 3
+ assert plan.commands == ["pytest tests/test_orders.py"]
+
+
+def test_an_untruncated_test_list_keeps_the_precise_command() -> None:
+ reached = ReachedBy(
+ via="call-graph",
+ total=2,
+ tests=["tests/test_orders.py::test_a", "tests/test_orders.py::test_b"],
+ all_tests=["tests/test_orders.py::test_a", "tests/test_orders.py::test_b"],
+ )
+ plan = build_validation_plan(_multi_site_plan(), {}, {"svc/orders.py": reached}, test_limit=12)
+ assert plan.truncated is False
+ assert plan.commands == ["pytest tests/test_orders.py::test_a tests/test_orders.py::test_b"]
diff --git a/tests/unit/health/test_refactoring_rank.py b/tests/unit/health/test_refactoring_rank.py
index 4dd06d237..cbc4e32e2 100644
--- a/tests/unit/health/test_refactoring_rank.py
+++ b/tests/unit/health/test_refactoring_rank.py
@@ -1,8 +1,8 @@
"""Tests for the unified cross-detector ranking (rank.py).
One ranking is imposed over every refactoring type so the surfaces show the
-most valuable suggestion first regardless of kind. The key blends recovered
-impact, target centrality, and blast radius, weighted by confidence.
+most valuable suggestion first regardless of kind. Benefit and leverage raise
+priority; effort, blast-radius risk, weak evidence, and validation gaps lower it.
"""
from __future__ import annotations
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 8d38c92a9..b1b03913b 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -149,7 +149,8 @@ async def test_directive_admits_when_the_file_has_no_plans_at_all(setup_mcp, hea
# The seeded worst file leads with complex_method and carries no plans.
assert directive["fix_first"] == "src/auth/service.py"
assert directive["plan_addresses_reason"] is False
- assert "no plans at all" in directive["plan_note"]
+ assert "has no plans" in directive["plan_note"]
+ assert directive["next_action"] == "investigate complex_method"
@pytest.mark.asyncio
@@ -162,7 +163,13 @@ async def test_directive_admits_when_plans_target_a_different_biomarker(
await _seed_plans(
session,
health_data,
- [{"file_path": "src/auth/service.py", "source_biomarker": "dry_violation", "impact_delta": 1.0}],
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "source_biomarker": "dry_violation",
+ "impact_delta": 1.0,
+ }
+ ],
)
directive = (await get_health(only=["directive"]))["directive"]
@@ -173,9 +180,7 @@ async def test_directive_admits_when_plans_target_a_different_biomarker(
@pytest.mark.asyncio
-async def test_directive_confirms_when_a_plan_addresses_the_reason(
- setup_mcp, health_data, session
-):
+async def test_directive_confirms_when_a_plan_addresses_the_reason(setup_mcp, health_data, session):
"""The true branch has to be reachable, or the flag is decoration."""
from repowise.server.mcp_server import get_health
@@ -194,6 +199,34 @@ async def test_directive_confirms_when_a_plan_addresses_the_reason(
directive = (await get_health(only=["directive"]))["directive"]
assert directive["plan_addresses_reason"] is True
assert "plan_note" not in directive
+ assert directive["next_action"] == "inspect matching plan via plan_via"
+
+
+async def test_combined_recommendation_lede_is_compact_and_self_directing(
+ setup_mcp, health_data, session
+):
+ from repowise.server.mcp_server import get_health
+
+ await _seed_plans(
+ session,
+ health_data,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "source_biomarker": "complex_method",
+ "impact_delta": 1.0,
+ }
+ ],
+ )
+ result = await get_health(include=["performance", "refactoring"], only=["recommendation_lede"])
+ lede = result["recommendation_lede"]
+ assert set(result) <= {"mode", "recommendation_lede", "_meta"}
+ assert lede["performance_opportunities_total"] == 1
+ assert lede["refactoring_plans_total"] == 1
+ assert lede["performance_lead"]["boundary_kind"] == "db"
+ assert {"benefit", "leverage", "cost", "risk", "validation"} <= set(lede["recommendation_lead"])
+ assert "only=['performance_opportunities','refactoring_plans']" in lede["next_call"]
@pytest.mark.asyncio
@@ -223,7 +256,7 @@ async def test_directive_does_not_claim_a_file_is_planless_over_an_unattributed_
directive = (await get_health(only=["directive"]))["directive"]
assert directive["plan_addresses_reason"] is False
- assert "no plans at all" not in directive["plan_note"]
+ assert "has no plans" not in directive["plan_note"]
assert "record no source biomarker" in directive["plan_note"]
@@ -377,9 +410,7 @@ async def test_get_health_dashboard_leads_with_a_directive(setup_mcp, health_dat
@pytest.mark.asyncio
-async def test_directive_share_bounded_when_gross_exceeds_net_gap(
- session, setup_mcp
-):
+async def test_directive_share_bounded_when_gross_exceeds_net_gap(session, setup_mcp):
"""Regression guard for #1437: the share uses the gross deficit of all
below-target files as its denominator, so it is bounded by 100% and sums to
100% by construction — the net gap (which healthy files cushion) would let
@@ -436,9 +467,7 @@ async def test_directive_share_bounded_when_gross_exceeds_net_gap(
@pytest.mark.asyncio
-async def test_directive_absent_when_no_file_below_target(
- session, setup_mcp
-):
+async def test_directive_absent_when_no_file_below_target(session, setup_mcp):
"""When no file is below the Healthy floor there is no gross gap, nothing to
recommend, and no share to report — the directive is absent entirely."""
from repowise.core.persistence.crud import save_health_metrics
@@ -472,9 +501,7 @@ async def test_directive_absent_when_no_file_below_target(
@pytest.mark.asyncio
-async def test_high_leverage_rows_sum_to_100_with_negative_net_gap(
- session, setup_mcp
-):
+async def test_high_leverage_rows_sum_to_100_with_negative_net_gap(session, setup_mcp):
"""The microdot scenario from #1437: several files below target against a
negative net gap. The gross gap is the denominator, so rows are distinct,
each bounded by 100%, and they sum to 100% by construction — whereas the
@@ -822,9 +849,7 @@ async def test_worst_files_order_survives_every_dimension_filter(setup_mcp, floo
@pytest.mark.asyncio
-async def test_one_response_agrees_with_itself_about_the_worst_file(
- setup_mcp, floored_health_data
-):
+async def test_one_response_agrees_with_itself_about_the_worst_file(setup_mcp, floored_health_data):
"""``kpis`` and ``worst_files`` must name the same file.
Regression: ``_compute_kpis`` reduces with ``min()``, which returns the
@@ -1115,9 +1140,7 @@ async def test_test_findings_get_their_own_bucket(setup_mcp, health_data_with_te
@pytest.mark.asyncio
-async def test_each_bucket_is_capped_against_its_own_population(
- setup_mcp, health_data_with_tests
-):
+async def test_each_bucket_is_capped_against_its_own_population(setup_mcp, health_data_with_tests):
"""The split happens before the cap, not after.
Capping first and partitioning after would hand the smaller bucket
@@ -1134,9 +1157,7 @@ async def test_each_bucket_is_capped_against_its_own_population(
@pytest.mark.asyncio
-async def test_metric_rows_say_whether_a_file_is_test_material(
- setup_mcp, health_data_with_tests
-):
+async def test_metric_rows_say_whether_a_file_is_test_material(setup_mcp, health_data_with_tests):
"""``is_test`` is a fact on the row, distinct from ``has_test_file``.
The two answer opposite questions — "is this file a test" vs "is this file
@@ -1299,7 +1320,7 @@ async def test_coverage_payload_shape_is_unchanged(setup_mcp, health_data):
@pytest.mark.asyncio
async def test_refactoring_plans_spread_across_files(setup_mcp, health_data, session):
- """The cap is spread over files instead of being spent on the worst one.
+ """The explicit file_spread view spreads the cap without changing rank.
``deficit_by_path`` is a *file* property, so a pure deficit sort puts every
plan on the worst file ahead of every plan on the second worst. Measured on
@@ -1334,7 +1355,9 @@ async def test_refactoring_plans_spread_across_files(setup_mcp, health_data, ses
],
)
- plans = (await get_health(include=["refactoring"], limit=4))["refactoring_plans"]
+ plans = (await get_health(include=["refactoring"], limit=4, refactoring_view="file_spread"))[
+ "refactoring_plans"
+ ]
assert len(plans) == 4
# Both files are represented rather than the worst file owning the list.
assert len({p["file_path"] for p in plans}) == 2
@@ -1665,9 +1688,7 @@ async def test_a_response_that_fits_is_not_trimmed(setup_mcp, health_data):
@pytest.mark.asyncio
-async def test_trimming_never_eats_the_directive_or_the_totals(
- setup_mcp, health_data, monkeypatch
-):
+async def test_trimming_never_eats_the_directive_or_the_totals(setup_mcp, health_data, monkeypatch):
"""The blocks that let a caller recover must survive the cut that caused it."""
from repowise.server.mcp_server import get_health