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(ui): connect performance opportunities to refactoring plans (#1816)

Raghav Chamadiya3ab320a1f7d5
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4b9ba1015..06c889e4c 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Code Health performance opportunities now lead into the existing
+ Refactoring workflow.** A dedicated Performance tab groups raw findings into
+ bounded causal opportunities with production/tooling versus test context,
+ affected-call-site totals, confidence, provenance paths, and raw-evidence
+ paging. Exact stable opportunity ids open matching `performance_fix` plans;
+ opportunities without a safe plan say so instead of selecting a nearby one.
+ The Refactoring page adds a Performance filter and shared priority,
+ validation, path, and pagination renderers. Its new server-owned page endpoint
+ bounds initial payloads while preserving the legacy unpaged route. VS Code
+ consumes the same contracts and renders priority and validation without web
+ dependencies; older missing optional fields remain supported.
+
- **A test-to-code map that needs no coverage report.** The per-test map only
ever existed if you ingested a coverage report with contexts, so on most
repositories `tests_to_run` was empty, `impacted_tests` said "run the full
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index bbf061938..82cc3c74f 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -409,6 +409,22 @@ goes.
Methodology and raw data:
[perf-detection](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).
+### Product flow
+
+The web Code Health page has a dedicated **Performance** tab. It leads with a
+bounded list of causal opportunities rather than a flat wall of observations:
+the boundary and execution context, shared intervention, affected call-site and
+file totals, confidence, and resolution provenance. Production/tooling and test
+contexts are separate views. Expanding an opportunity shows caller-to-sink
+paths; raw findings remain canonical and load as a separately paged evidence
+drill-down.
+
+When the deterministic service can describe a safe intervention, the
+opportunity links by its exact stable `opportunity_id` to the matching
+`performance_fix` plan on the existing **Refactoring** page. It never guesses a
+nearby plan. When no safe plan exists, Code Health says so and keeps the raw
+evidence available.
+
## Refactoring targets
```bash
@@ -418,7 +434,7 @@ repowise health --refactoring-targets
A score tells you a file is in trouble; a refactoring target names the fix.
Repowise emits structured suggestions computed deterministically during the
health pass from data it already has — the call graph, the cohesion model, the
-clone pairs, git co-change. No re-parse, no LLM, inside the same budget. Six
+clone pairs, git co-change. No re-parse, no LLM, inside the same budget. Seven
detectors ship:
| Type | What it names |
@@ -429,12 +445,15 @@ detectors ship:
| **Move Method** | A feature-envy method and the class it actually belongs to |
| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle |
| **Split File** | The cohesive files an oversized module should decompose into, plus the import edits in every dependent |
+| **Performance Fix** | A proven shared intervention for a causal performance opportunity, with affected call sites and caller-to-sink paths |
Each suggestion is structured data, not a string: a `plan`, the `evidence` that
justifies it, the `impact_delta` it recovers, an `effort_bucket`, and a
`blast_radius` of callers and co-changing files that must move with it. Ranking
-is graph-aware — `impact × centrality × blast_radius`, so a plan on a central hub
-outranks the same plan on a leaf.
+is graph-aware. The canonical recommendation service separates benefit and
+leverage from cost and risk; a larger blast radius raises cost and risk and is
+never presented as benefit. Performance plans retain detector-native benefit
+even though they intentionally recover zero defect-health points.
```python
get_health(include=["refactoring"]) # ranked structured plans
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index e5bbe2d40..d3f577b65 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -23,7 +23,7 @@ LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in
<img src="../../.github/assets/health-loop.svg" alt="repowise code-health loop: markers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" />
</div>
-## The six detectors
+## The seven detectors
Each detector is a self-contained module registered into a registry (adding a
refactoring type is a new file + a registry entry, like the marker registry).
@@ -38,6 +38,7 @@ one**, and produces stable-sorted, deterministic output.
| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. |
| **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |
| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify; IN/OUT comes from liveness over the def/use facts, so the suggested helper is behavior-preserving by construction. |
+| **Performance Fix** | A safe shared intervention, affected call sites, and caller-to-sink paths for one causal performance opportunity. | The call-graph opportunity service groups raw findings by stable cause, boundary and context, then emits only supported strategies. Findings with no coherent safe intervention remain visible in Code Health without a plan. |
The algorithms are derived from public academic literature (Fokaefs-Tsantalis
HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking,
@@ -58,11 +59,11 @@ web).
| Field | Meaning |
|-------|---------|
-| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` \| `extract_method` |
+| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` \| `extract_method` \| `performance_fix` |
| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |
| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. |
| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. |
-| `impact_delta` | The health score the refactoring would recover (the deduction of the marker it answers); `0` for the graph-native types that answer no marker. |
+| `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. |
| `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. |
| `blast_radius` | What else must move: the callers, co-change partners, and importing files. Extract Method carries `{"scope": "local"}` instead — extraction adds a private helper and changes no signature, so nothing outside the file moves and there is no count to make. |
| `confidence` | `low` \| `medium` \| `high` (drives the `min_confidence` surface gate). |
@@ -74,22 +75,19 @@ The per-type `plan` / `evidence` / `blast_radius` shapes are documented in full
## Ranking: graph-aware, not churn-only
Each detector sorts its own output, but the surfaces show one mixed list, so the
-**global** order is what matters. A single unified rank blends three orthogonal
-signals as a product of `(1 + signal)` factors (so a zero in any one dimension
-shapes the order without annihilating the plan):
+**global** order is what matters. The shared recommendation service owns four
+named components and one canonical score:
```
-score = (1 + impact_delta)
- × (1 + log1p(target centrality)) # importer count / in-degree
- × (1 + log1p(blast radius)) # how much else moves, a mild amplifier
- × confidence_weight # high 1.25 · medium 1.0 · low 0.75
+score = (1 + benefit) * (1 + leverage) / (1 + cost + risk)
```
-A plan on a **central hub file outranks the same plan on a leaf**. Because the
-impact-free graph-native types (Move Method, Break Cycle, Split File) still rank
-via centrality and blast radius, they interleave fairly with the impact-bearing
-types rather than sinking below them. Ties break on type → file → target, so the
-order is fully deterministic.
+`benefit` is recoverable health or detector-native structural/performance gain;
+`leverage` is weighted health deficit, dependents, and reliable entry reach;
+`cost` includes effort and change surface; `risk` includes blast radius,
+confidence, provenance, and validation quality. Larger blast radius therefore
+cannot improve rank by masquerading as benefit. Performance plans keep their
+detector-native benefit even with zero health impact. Ties break deterministically.
> **The wedge.** The leading commercial code-health tool ranks refactoring
> targets by **churn alone**, generates code **within-function only**, and ignores
@@ -113,16 +111,19 @@ get_health(targets=["module:src.api"]) # one module
```text
# REST: what the web tab reads
GET /api/repos/{repo_id}/refactoring/targets?refactoring_type=extract_class&min_confidence=high
+GET /api/repos/{repo_id}/refactoring/targets/page?limit=60&offset=0&refactoring_type=performance_fix
GET /api/repos/{repo_id}/refactoring/{suggestion_id} # one plan + blast-radius detail
```
-The web **Refactoring** tab renders each plan as a card (the split groups as a
-small tree, the move arrow, the clone occurrences with line links, the file-split
-groups tree with its residual core and import-rewrite list) over an impact/effort
-quadrant, with per-type filter chips (URL-synced) and a distinct accent color per
-type carried consistently across the quadrant dots, card rails, and chips. Each
-card has a **copy-to-agent** button that exports the structured plan + source
-spans + blast radius as a prompt a coding agent can execute.
+The web **Refactoring** page uses one shared plan board and drawer for every
+type, including a Performance filter. Its initial data path is bounded and
+server-owned: search, type, confidence, effort, canonical sorting, true totals,
+and deterministic offset cursors. The older unpaged endpoint remains available
+during migration. The drawer explains benefit, leverage, cost, risk and rank;
+shows validation basis and provenance, true test totals, capped tests and
+commands; and makes affected paths and intervention points navigable. Each card
+can still export the structured plan for an agent. It never runs tests, creates
+edits, or applies a refactoring automatically.
## Optional code generation
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index bcaad4873..260df27e4 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -14,9 +14,11 @@ import type {
HealthFileBreakdownResponse,
HealthOverviewResponse,
HealthTrendResponse,
+ PerformanceOpportunityPage,
HealthWorkQueueQuery,
HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
+import type { Paginated } from "@repowise-dev/types";
import { apiGet, apiPatch } from "./client";
export type {
@@ -71,6 +73,33 @@ export async function listHealthFindings(
return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);
}
+export interface PerformanceOpportunityPageParams {
+ context?: "production_tooling" | "test" | "all";
+ limit?: number;
+ offset?: number;
+}
+
+export async function getPerformanceOpportunities(
+ repoId: string,
+ opts: PerformanceOpportunityPageParams = {},
+): Promise<PerformanceOpportunityPage> {
+ return apiGet<PerformanceOpportunityPage>(
+ `/api/repos/${repoId}/health/performance-opportunities`,
+ { context: opts.context, limit: opts.limit, offset: opts.offset },
+ );
+}
+
+export async function getPerformanceOpportunityFindings(
+ repoId: string,
+ opportunityId: string,
+ opts: { limit?: number; offset?: number } = {},
+): Promise<Paginated<HealthFinding>> {
+ return apiGet(
+ `/api/repos/${repoId}/health/performance-opportunities/${encodeURIComponent(opportunityId)}/findings`,
+ { limit: opts.limit, offset: opts.offset },
+ );
+}
+
export async function listHealthFiles(
repoId: string,
opts?: HealthFilesQuery,
diff --git a/packages/api-client/src/hosted.test.ts b/packages/api-client/src/hosted.test.ts
index 927243933..6aecd4967 100644
--- a/packages/api-client/src/hosted.test.ts
+++ b/packages/api-client/src/hosted.test.ts
@@ -318,6 +318,50 @@ describe("request wiring", () => {
// No route registered for health/overview: stub returns a 404 body.
await expect(p.getHealthOverview("repo-1")).rejects.toBeInstanceOf(ApiClientError);
});
+
+ it("passes bounded performance and refactoring paging through snapshot routes", async () => {
+ const envelope = { items: [], total: 0, has_more: false, next_offset: null };
+ const { p, calls } = provider([
+ REPOS_ROUTE,
+ ["/refactoring/plan-1", { id: "plan-1", refactoring_type: "performance_fix" }],
+ [
+ "/refactoring/targets/page",
+ { ...envelope, summary: { total: 0, by_type: [] }, structural_leads: [] },
+ ],
+ ["/health/performance-opportunities/opp-1/findings", envelope],
+ [
+ "/health/performance-opportunities",
+ {
+ ...envelope,
+ summary: {
+ total: 0,
+ production_total: 0,
+ tooling_total: 0,
+ test_total: 0,
+ with_plan_total: 0,
+ without_plan_total: 0,
+ },
+ },
+ ],
+ ]);
+
+ await p.getRefactoringPlansPage("repo-1", {
+ refactoringType: "performance_fix",
+ confidence: "high,medium",
+ sort: "canonical",
+ limit: 20,
+ offset: 40,
+ });
+ await p.getRefactoringPlan("repo-1", "plan-1");
+ await p.getPerformanceOpportunities("repo-1", { context: "test", limit: 20 });
+ await p.getPerformanceOpportunityFindings("repo-1", "opp-1", { limit: 50 });
+
+ expect(calls.at(-4)!.url).toContain("refactoring_type=performance_fix");
+ expect(calls.at(-4)!.url).toContain("offset=40");
+ expect(calls.at(-3)!.url).toContain("refactoring/plan-1");
+ expect(calls.at(-2)!.url).toContain("context=test");
+ expect(calls.at(-1)!.url).toContain("performance-opportunities/opp-1/findings");
+ });
});
// ---------------------------------------------------------------------------
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index 6874d1068..15b9ba8db 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -31,12 +31,17 @@ import type {
HealthWorkQueueResponse,
} from "@repowise-dev/types/health";
import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
-import type { RefactoringTargets } from "@repowise-dev/types/refactoring";
+import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";
+import type {
+ RefactoringPlan,
+ RefactoringPlanPage,
+ 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 { RefactoringPageParams, RefactoringTargetsParams } from "./refactoring";
import type {
ArchitectureGraphResponse,
CommunitySliceResponse,
@@ -362,6 +367,7 @@ export interface HostedProvider {
file_path?: string;
min_severity?: string;
dimension?: string;
+ limit?: number;
},
): Promise<HealthFinding[]>;
listHealthFiles(repoId: string, opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
@@ -384,6 +390,24 @@ export interface HostedProvider {
repoId: string,
opts?: RefactoringTargetsParams,
): Promise<RefactoringTargets>;
+ getRefactoringPlansPage(
+ repoId: string,
+ opts?: RefactoringPageParams,
+ ): Promise<RefactoringPlanPage>;
+ getRefactoringPlan(repoId: string, planId: string): Promise<RefactoringPlan>;
+ getPerformanceOpportunities(
+ repoId: string,
+ opts?: {
+ context?: "production_tooling" | "test" | "all";
+ limit?: number;
+ offset?: number;
+ },
+ ): Promise<PerformanceOpportunityPage>;
+ getPerformanceOpportunityFindings(
+ repoId: string,
+ opportunityId: string,
+ opts?: { limit?: number; offset?: number },
+ ): Promise<import("@repowise-dev/types").Paginated<HealthFinding>>;
getChurnComplexity(repoId: string, opts?: { limit?: number }): Promise<ChurnComplexityResponse>;
// Modules
@@ -668,7 +692,7 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
biomarker: opts?.biomarker_type,
file_path: opts?.file_path,
dimension: opts?.dimension,
- limit: 500,
+ limit: opts?.limit ?? 500,
});
let items = res.items ?? [];
if (opts?.min_severity !== undefined && opts.min_severity in SEVERITY_ORDER) {
@@ -761,6 +785,29 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
file_path: opts.filePath,
view: opts.view,
}),
+ getRefactoringPlansPage: (repoId, opts = {}) =>
+ snapGet(repoId, "/refactoring/targets/page", {
+ refactoring_type: opts.refactoringType,
+ min_confidence: opts.minConfidence,
+ file_path: opts.filePath,
+ view: opts.view,
+ search: opts.search,
+ confidence: opts.confidence,
+ effort: opts.effort,
+ sort: opts.sort,
+ limit: opts.limit,
+ offset: opts.offset,
+ }),
+ getRefactoringPlan: (repoId, planId) =>
+ snapGet(repoId, `/refactoring/${encodeURIComponent(planId)}`),
+ getPerformanceOpportunities: (repoId, opts = {}) =>
+ snapGet(repoId, "/health/performance-opportunities", opts),
+ getPerformanceOpportunityFindings: (repoId, opportunityId, opts = {}) =>
+ snapGet(
+ repoId,
+ `/health/performance-opportunities/${encodeURIComponent(opportunityId)}/findings`,
+ opts,
+ ),
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 3cd511ab0..5ccb30035 100644
--- a/packages/api-client/src/refactoring.ts
+++ b/packages/api-client/src/refactoring.ts
@@ -6,6 +6,7 @@
import { apiGet, apiPost, apiPut } from "./client";
import type {
GeneratedCode,
+ RefactoringPlanPage,
RefactoringPlan,
RefactoringTargets,
} from "@repowise-dev/types/refactoring";
@@ -29,6 +30,17 @@ export interface RefactoringTargetsParams {
view?: "canonical" | "file_spread";
}
+export type RefactoringSort = "canonical" | "health" | "effort" | "blast" | "file";
+
+export interface RefactoringPageParams extends RefactoringTargetsParams {
+ search?: string;
+ confidence?: string;
+ effort?: string;
+ sort?: RefactoringSort;
+ limit?: number;
+ offset?: number;
+}
+
export async function getRefactoringTargets(
repoId: string,
params: RefactoringTargetsParams = {},
@@ -41,6 +53,25 @@ export async function getRefactoringTargets(
});
}
+/** Bounded server-filtered list for product surfaces. */
+export async function getRefactoringPlansPage(
+ repoId: string,
+ params: RefactoringPageParams = {},
+): Promise<RefactoringPlanPage> {
+ return apiGet<RefactoringPlanPage>(`/api/repos/${repoId}/refactoring/targets/page`, {
+ refactoring_type: params.refactoringType,
+ min_confidence: params.minConfidence,
+ file_path: params.filePath,
+ view: params.view,
+ search: params.search,
+ confidence: params.confidence,
+ effort: params.effort,
+ sort: params.sort,
+ limit: params.limit,
+ offset: params.offset,
+ });
+}
+
export async function getRefactoringPlan(
repoId: string,
suggestionId: string,
diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
index 046f1586c..ffdbb36d7 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
@@ -20,6 +20,7 @@ from repowise.core.test_paths import is_test_related_path
ExecutionContext = Literal["production", "tooling", "test"]
FixSafety = Literal["proven", "advisory"]
+OpportunityConfidence = Literal["high", "medium", "low"]
FixStrategy = Literal[
"parallelize_independent_awaits",
"replace_membership_collection",
@@ -75,6 +76,7 @@ class PerformanceOpportunity:
evidence_truncated: bool
reliable_entry_reachability: bool | None
provenance: str
+ confidence: OpportunityConfidence
rank_score: int
rank_factors: dict[str, int]
fix: PerformanceFix | None
@@ -96,6 +98,7 @@ class PerformanceOpportunity:
"evidence_truncated": self.evidence_truncated,
"reliable_entry_reachability": self.reliable_entry_reachability,
"provenance": self.provenance,
+ "confidence": self.confidence,
"rank_score": self.rank_score,
"rank_factors": dict(self.rank_factors),
"fix": self.fix.as_dict() if self.fix else None,
@@ -191,15 +194,27 @@ def _shared_suffix(paths: list[tuple[str, ...]]) -> tuple[str, ...]:
def _evidence(row: Any, details: dict[str, Any]) -> dict[str, Any]:
return {
+ "finding_id": str(_attr(row, "id", "") or ""),
"file_path": str(_attr(row, "file_path", "")),
+ "biomarker_type": str(_attr(row, "biomarker_type", "") or ""),
"function_name": _attr(row, "function_name", None),
"line_start": _attr(row, "line_start", None),
"line_end": _attr(row, "line_end", None),
+ "reason": str(_attr(row, "reason", "") or ""),
"path": list(details.get("path", ())),
"provenance": details.get("resolution_basis", "direct"),
}
+def provenance_confidence(provenance: str) -> OpportunityConfidence:
+ """Product confidence label owned beside the provenance ranking policy."""
+ if provenance in {"call-site", "direct"}:
+ return "high"
+ if provenance == "reliable-edge":
+ return "medium"
+ return "low"
+
+
def _fix_for(
marker: str,
markers: tuple[str, ...],
@@ -339,6 +354,7 @@ def build_performance_opportunities(
evidence_truncated=len(rows) > cap,
reliable_entry_reachability=reachable,
provenance=provenance,
+ confidence=provenance_confidence(provenance),
rank_score=sum(factors.values()),
rank_factors=factors,
fix=_fix_for(
@@ -370,4 +386,5 @@ __all__ = [
"execution_context",
"link_performance_findings",
"opportunity_id_for_finding",
+ "provenance_confidence",
]
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index afc1b1bbc..cc8f8e80b 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -970,11 +970,24 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Non
file_paths=changed_paths,
)
if performance_paths:
+ performance_suggestions = [
+ suggestion
+ for suggestion in list(getattr(report, "refactoring_suggestions", None) or [])
+ if suggestion.refactoring_type == "performance_fix"
+ ]
+ # A causal plan is stored at its shared intervention, which can sit
+ # downstream of every caller file in the performance invalidation
+ # closure. Include those targets in the scoped replacement or the
+ # findings refresh while their matching plans are silently discarded.
+ performance_plan_paths = sorted(
+ set(performance_paths)
+ | {suggestion.file_path for suggestion in performance_suggestions}
+ )
await upsert_refactoring_suggestions(
session,
repo_id,
- list(getattr(report, "refactoring_suggestions", None) or []),
- file_paths=performance_paths,
+ performance_suggestions,
+ file_paths=performance_plan_paths,
refactoring_type="performance_fix",
)
# Per-function blame rollup for the changed files (keeps git_function_blame
diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
index 4b9ba1015..06c889e4c 100644
--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
@@ -13,6 +13,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Code Health performance opportunities now lead into the existing
+ Refactoring workflow.** A dedicated Performance tab groups raw findings into
+ bounded causal opportunities with production/tooling versus test context,
+ affected-call-site totals, confidence, provenance paths, and raw-evidence
+ paging. Exact stable opportunity ids open matching `performance_fix` plans;
+ opportunities without a safe plan say so instead of selecting a nearby one.
+ The Refactoring page adds a Performance filter and shared priority,
+ validation, path, and pagination renderers. Its new server-owned page endpoint
+ bounds initial payloads while preserving the legacy unpaged route. VS Code
+ consumes the same contracts and renders priority and validation without web
+ dependencies; older missing optional fields remain supported.
+
- **A test-to-code map that needs no coverage report.** The per-test map only
ever existed if you ingested a coverage report with contexts, so on most
repositories `tests_to_run` was empty, `impacted_tests` said "run the full
diff --git a/packages/server/src/repowise/server/routers/code_health/__init__.py b/packages/server/src/repowise/server/routers/code_health/__init__.py
index ade1f8145..299a7d94f 100644
--- a/packages/server/src/repowise/server/routers/code_health/__init__.py
+++ b/packages/server/src/repowise/server/routers/code_health/__init__.py
@@ -21,6 +21,7 @@ from . import (
files_routes, # noqa: F401
findings_routes, # noqa: F401
overview_routes, # noqa: F401
+ performance_routes, # noqa: F401
refactoring_routes, # noqa: F401
trends_routes, # noqa: F401
)
diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
new file mode 100644
index 000000000..2823b3a9c
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
@@ -0,0 +1,156 @@
+"""Bounded causal performance opportunities and raw-evidence drill-down."""
+
+from __future__ import annotations
+
+import json
+from typing import Any, Literal
+
+from fastapi import Depends, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.health.perf.opportunities import (
+ build_performance_opportunities,
+ opportunity_id_for_finding,
+)
+from repowise.core.persistence import crud
+from repowise.server.deps import get_db_session
+
+from ._router import router
+from .loaders import _attach_symbol_ids
+from .serializers import _finding_to_dict
+
+
+def _json_dict(raw: str | None) -> dict[str, Any]:
+ if not raw:
+ return {}
+ try:
+ value = json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _plan_ids(rows: list[Any]) -> dict[str, str]:
+ matches: dict[str, str] = {}
+ for row in rows:
+ opportunity_id = _json_dict(row.plan_json).get("opportunity_id")
+ if isinstance(opportunity_id, str) and opportunity_id:
+ plan_id = str(row.id)
+ matches[opportunity_id] = min(matches.get(opportunity_id, plan_id), plan_id)
+ return matches
+
+
+def _finding_opportunity_id(row: Any) -> str:
+ persisted = _json_dict(getattr(row, "details_json", None)).get("opportunity_id")
+ return (
+ persisted if isinstance(persisted, str) and persisted else opportunity_id_for_finding(row)
+ )
+
+
+def _plan_link(opportunity: Any, plan_id: str | None) -> dict[str, str | None]:
+ if plan_id:
+ return {
+ "plan_id": plan_id,
+ "plan_status": "available",
+ "plan_reason": "A stored performance plan addresses this exact opportunity.",
+ }
+ if opportunity.fix is None:
+ return {
+ "plan_id": None,
+ "plan_status": "no_safe_plan",
+ "plan_reason": (
+ "The analysis found the shared cause but could not prove one coherent "
+ "intervention without guessing."
+ ),
+ }
+ return {
+ "plan_id": None,
+ "plan_status": "not_persisted",
+ "plan_reason": (
+ "A supported strategy exists, but this index does not contain its matching "
+ "stored plan. Reindex to refresh recommendations."
+ ),
+ }
+
+
[email protected]("/api/repos/{repo_id}/health/performance-opportunities")
+async def list_performance_opportunities(
+ repo_id: str,
+ context: Literal["production_tooling", "test", "all"] = Query("production_tooling"),
+ limit: int = Query(20, ge=1, le=100),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """One bounded page over the canonical causal read model.
+
+ Findings and performance-plan rows are each read once. Exact
+ ``opportunity_id`` equality is the only accepted plan match.
+ """
+ findings = await crud.get_health_findings(session, repo_id, dimension="performance")
+ plan_rows = await crud.get_refactoring_suggestions(
+ session, repo_id, refactoring_type="performance_fix"
+ )
+ opportunities = build_performance_opportunities(findings, evidence_limit=8)
+ matches = _plan_ids(plan_rows)
+ contexts = {
+ "production_tooling": {"production", "tooling"},
+ "test": {"test"},
+ "all": {"production", "tooling", "test"},
+ }[context]
+ filtered = [item for item in opportunities if item.execution_context in contexts]
+ total = len(filtered)
+ page = filtered[offset : offset + limit]
+ next_offset = offset + len(page) if offset + len(page) < total else None
+ return {
+ "items": [
+ {
+ **item.as_dict(),
+ **_plan_link(item, matches.get(item.opportunity_id)),
+ }
+ for item in page
+ ],
+ "total": total,
+ "has_more": next_offset is not None,
+ "next_offset": next_offset,
+ "summary": {
+ "total": len(opportunities),
+ "production_total": sum(
+ item.execution_context == "production" for item in opportunities
+ ),
+ "tooling_total": sum(item.execution_context == "tooling" for item in opportunities),
+ "test_total": sum(item.execution_context == "test" for item in opportunities),
+ "with_plan_total": sum(item.opportunity_id in matches for item in opportunities),
+ "without_plan_total": sum(item.opportunity_id not in matches for item in opportunities),
+ },
+ }
+
+
[email protected]("/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}/findings")
+async def list_performance_opportunity_findings(
+ repo_id: str,
+ opportunity_id: str,
+ limit: int = Query(50, ge=1, le=200),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """Click-gated raw canonical observations for one stable opportunity id."""
+ findings = await crud.get_health_findings(session, repo_id, dimension="performance")
+ matched = [
+ finding for finding in findings if _finding_opportunity_id(finding) == opportunity_id
+ ]
+ matched.sort(key=lambda row: (row.file_path, row.line_start or 0, row.id))
+ total = len(matched)
+ page = matched[offset : offset + limit]
+ items = await _attach_symbol_ids(
+ session, repo_id, [_finding_to_dict(finding) for finding in page]
+ )
+ next_offset = offset + len(page) if offset + len(page) < total else None
+ return {
+ "items": items,
+ "total": total,
+ "has_more": next_offset is not None,
+ "next_offset": next_offset,
+ }
+
+
+__all__ = ["list_performance_opportunities", "list_performance_opportunity_findings"]
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 116ceae13..ebb4e5ce6 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -19,7 +19,11 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.health.refactoring.recommendations import hydrate_recommendations
+from repowise.core.analysis.health.refactoring.recommendations import (
+ apply_view,
+ blast_size,
+ hydrate_recommendations,
+)
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
@@ -84,6 +88,13 @@ class RefactoringTypeCount(BaseModel):
class RefactoringSummary(BaseModel):
total: int
by_type: list[RefactoringTypeCount]
+ files_total: int | None = None
+ structural_total: int | None = None
+ performance_total: int | None = None
+ small_effort_total: int | None = None
+ health_recovery_total: int | None = None
+ negligible_health_total: int | None = None
+ best_health_gain: float | None = None
class RefactoringTargetsResponse(BaseModel):
@@ -91,6 +102,17 @@ class RefactoringTargetsResponse(BaseModel):
plans: list[RefactoringPlanResponse]
+class RefactoringPlanPageResponse(BaseModel):
+ """Bounded product page; the legacy targets response remains unpaged."""
+
+ items: list[RefactoringPlanResponse]
+ total: int
+ has_more: bool
+ next_offset: int | None
+ summary: RefactoringSummary
+ structural_leads: list[RefactoringPlanResponse]
+
+
# ---------------------------------------------------------------------------
# Row → dataclass → response adapters
# ---------------------------------------------------------------------------
@@ -100,6 +122,88 @@ def _to_response(data: dict[str, Any]) -> RefactoringPlanResponse:
return RefactoringPlanResponse(**data)
+_STRUCTURAL_TYPES = {"split_file", "break_cycle", "extract_class", "move_method"}
+_EFFORT_ORDER = {"S": 0, "M": 1, "L": 2, "XL": 3}
+
+
+def _summary(recommendations: list[Any]) -> RefactoringSummary:
+ by_type: dict[str, int] = {}
+ for recommendation in recommendations:
+ suggestion = recommendation.suggestion
+ by_type[suggestion.refactoring_type] = by_type.get(suggestion.refactoring_type, 0) + 1
+ return RefactoringSummary(
+ total=len(recommendations),
+ by_type=[
+ RefactoringTypeCount(type=kind, count=count)
+ for kind, count in sorted(by_type.items(), key=lambda item: (-item[1], item[0]))
+ ],
+ files_total=len({item.suggestion.file_path for item in recommendations}),
+ structural_total=sum(
+ item.suggestion.refactoring_type in _STRUCTURAL_TYPES for item in recommendations
+ ),
+ performance_total=by_type.get("performance_fix", 0),
+ small_effort_total=sum(item.suggestion.effort_bucket == "S" for item in recommendations),
+ health_recovery_total=sum(item.suggestion.impact_delta >= 0.1 for item in recommendations),
+ negligible_health_total=sum(item.suggestion.impact_delta < 0.5 for item in recommendations),
+ best_health_gain=round(
+ max((float(item.suggestion.impact_delta) for item in recommendations), default=0.0),
+ 3,
+ ),
+ )
+
+
+def _csv_values(value: str | None) -> set[str]:
+ return {part.strip() for part in (value or "").split(",") if part.strip()}
+
+
+def _matches_search(recommendation: Any, query: str) -> bool:
+ suggestion = recommendation.suggestion
+ plan = suggestion.plan or {}
+ haystack = " ".join(
+ (
+ suggestion.file_path,
+ suggestion.target_symbol,
+ suggestion.refactoring_type,
+ suggestion.source_biomarker,
+ str(plan.get("strategy") or ""),
+ str(plan.get("intervention_symbol") or ""),
+ )
+ ).lower()
+ return query in haystack
+
+
+def _sort_recommendations(recommendations: list[Any], sort: str) -> list[Any]:
+ canonical_position = {item.id: index for index, item in enumerate(recommendations)}
+ if sort == "canonical":
+ return recommendations
+ if sort == "health":
+ return sorted(
+ recommendations,
+ key=lambda item: (-item.suggestion.impact_delta, canonical_position[item.id]),
+ )
+ if sort == "effort":
+ return sorted(
+ recommendations,
+ key=lambda item: (
+ _EFFORT_ORDER.get(item.suggestion.effort_bucket, 2),
+ canonical_position[item.id],
+ ),
+ )
+ if sort == "blast":
+ return sorted(
+ recommendations,
+ key=lambda item: (-blast_size(item.suggestion), canonical_position[item.id]),
+ )
+ return sorted(
+ recommendations,
+ key=lambda item: (
+ item.suggestion.file_path,
+ item.suggestion.target_symbol,
+ item.id,
+ ),
+ )
+
+
# ---------------------------------------------------------------------------
# Endpoints — declare the static `targets` path before the dynamic id path so
# FastAPI matches it first.
@@ -158,6 +262,67 @@ async def get_refactoring_targets(
)
[email protected]("/{repo_id}/refactoring/targets/page", response_model=RefactoringPlanPageResponse)
+async def get_refactoring_plan_page(
+ repo_id: str,
+ refactoring_type: str | None = Query(None),
+ min_confidence: str | None = Query(None, description="Compatibility confidence floor"),
+ confidence: str | None = Query(None, description="Comma-separated exact confidence values"),
+ effort: str | None = Query(None, description="Comma-separated effort buckets"),
+ file_path: str | None = Query(None),
+ search: str | None = Query(None, max_length=200),
+ sort: Literal["canonical", "health", "effort", "blast", "file"] = Query("canonical"),
+ view: Literal["canonical", "file_spread"] = Query("canonical"),
+ limit: int = Query(60, ge=1, le=100),
+ offset: int = Query(0, ge=0),
+ session: AsyncSession = Depends(get_db_session),
+) -> RefactoringPlanPageResponse:
+ """Bounded list with server-owned filters and deterministic ordering.
+
+ Hydration remains one batched pass over the repository plans so validation
+ and priority have exactly the Phase 3 semantics and a constant SQL shape.
+ Only the requested page crosses the wire.
+ """
+ rows = await crud.get_refactoring_suggestions(session, repo_id, min_confidence=min_confidence)
+ canonical = await hydrate_recommendations(session, repo_id, rows, view="canonical")
+ summary = _summary(canonical)
+ structural_leads = [
+ item for item in canonical if item.suggestion.refactoring_type in _STRUCTURAL_TYPES
+ ][:12]
+
+ ordered = apply_view(canonical, view)
+ if refactoring_type == "structural":
+ ordered = [
+ item for item in ordered if item.suggestion.refactoring_type in _STRUCTURAL_TYPES
+ ]
+ elif refactoring_type:
+ ordered = [item for item in ordered if item.suggestion.refactoring_type == refactoring_type]
+ if file_path is not None:
+ ordered = [item for item in ordered if item.suggestion.file_path == file_path]
+ confidences = _csv_values(confidence)
+ if confidences:
+ ordered = [item for item in ordered if item.suggestion.confidence in confidences]
+ efforts = _csv_values(effort)
+ if efforts:
+ ordered = [item for item in ordered if item.suggestion.effort_bucket in efforts]
+ normalized_search = (search or "").strip().lower()
+ if normalized_search:
+ ordered = [item for item in ordered if _matches_search(item, normalized_search)]
+ ordered = _sort_recommendations(ordered, sort)
+
+ total = len(ordered)
+ page = ordered[offset : offset + limit]
+ next_offset = offset + len(page) if offset + len(page) < total else None
+ return RefactoringPlanPageResponse(
+ items=[_to_response(item.as_dict()) for item in page],
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ summary=summary,
+ structural_leads=[_to_response(item.as_dict()) for item in structural_leads],
+ )
+
+
# ---------------------------------------------------------------------------
# Code-gen settings — read/write the refactoring.llm config block. Declared
# before the dynamic /{suggestion_id} GET so the static `settings` path wins.
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index f9fa6244f..575b0a755 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -16,6 +16,7 @@
*/
import type { C4IoKind } from "./external-systems.js";
+import type { Paginated } from "./pagination.js";
/** Finding severity used across the health surface. */
export type HealthSeverity = "low" | "medium" | "high" | "critical";
@@ -231,6 +232,66 @@ export interface HealthFinding {
dimension?: HealthDimension;
}
+export type PerformanceExecutionContext = "production" | "tooling" | "test";
+export type PerformanceOpportunityConfidence = "high" | "medium" | "low";
+
+export interface PerformanceOpportunityFix {
+ strategy: string;
+ safety: "proven" | "advisory";
+ rationale: string;
+}
+
+export interface PerformanceOpportunityEvidence {
+ finding_id: string;
+ file_path: string;
+ biomarker_type: string;
+ function_name: string | null;
+ line_start: number | null;
+ line_end: number | null;
+ reason: string;
+ path: string[];
+ provenance: string;
+}
+
+export interface PerformanceOpportunity {
+ opportunity_id: string;
+ biomarker_type: string;
+ biomarker_types: string[];
+ boundary_kind: C4IoKind | null;
+ execution_context: PerformanceExecutionContext;
+ terminal_sink: string | null;
+ shared_path_suffix: string[];
+ intervention_symbol: string | null;
+ affected_call_sites_total: number;
+ affected_files_total: number;
+ observations_total: number;
+ evidence: PerformanceOpportunityEvidence[];
+ evidence_truncated: boolean;
+ reliable_entry_reachability: boolean | null;
+ provenance: string;
+ confidence: PerformanceOpportunityConfidence;
+ rank_score: number;
+ rank_factors: Record<string, number>;
+ fix: PerformanceOpportunityFix | null;
+ /** Exact stored match. Never inferred from file, marker, or rank. */
+ plan_id: string | null;
+ plan_status: "available" | "no_safe_plan" | "not_persisted";
+ plan_reason: string;
+}
+
+export interface PerformanceOpportunitySummary {
+ total: number;
+ production_total: number;
+ tooling_total: number;
+ test_total: number;
+ with_plan_total: number;
+ without_plan_total: number;
+}
+
+export interface PerformanceOpportunityPage extends Paginated<PerformanceOpportunity> {
+ summary: PerformanceOpportunitySummary;
+}
+
export interface HealthModuleRow {
module: string;
file_count: number;
@@ -260,7 +321,12 @@ export interface HealthOverviewSummary {
worst_performer_path: string | null;
worst_performer_score: number | null;
open_findings: number;
- severity_breakdown?: { critical: number; high: number; medium: number; low: number };
+ severity_breakdown?: {
+ critical: number;
+ high: number;
+ medium: number;
+ low: number;
+ };
/** Repo-level band derived from `average_health` (added in the band/distribution layer). */
band?: HealthBand;
/**
@@ -488,7 +554,12 @@ export interface HealthTrendResponse {
message: string;
}>;
/** Largest movements first, in either direction, capped server-side. */
- file_deltas: Array<{ file_path: string; before: number; after: number; delta: number }>;
+ file_deltas: Array<{
+ file_path: string;
+ before: number;
+ after: number;
+ delta: number;
+ }>;
/**
* How many files moved in total, before the cap. Optional: the hosted
* backend does not send it, so consumers fall back to `file_deltas.length`.
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 2d19a9881..c877e423c 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -1,5 +1,7 @@
/** Canonical wire contract for structured refactoring recommendations. */
+import type { Paginated } from "./pagination.js";
+
export type RefactoringType =
| "extract_class"
| "extract_helper"
@@ -70,6 +72,14 @@ export interface RefactoringTypeCount {
export interface RefactoringSummary {
total: number;
by_type: RefactoringTypeCount[];
+ /** Additive Phase 4 aggregates; absent on older servers. */
+ files_total?: number;
+ structural_total?: number;
+ performance_total?: number;
+ small_effort_total?: number;
+ health_recovery_total?: number;
+ negligible_health_total?: number;
+ best_health_gain?: number;
}
export interface RefactoringTargets {
@@ -77,6 +87,13 @@ export interface RefactoringTargets {
plans: RefactoringPlan[];
}
+/** Bounded product list. The legacy unpaged RefactoringTargets path remains. */
+export interface RefactoringPlanPage extends Paginated<RefactoringPlan> {
+ summary: RefactoringSummary;
+ /** Bounded canonical structural head used by the existing Start here section. */
+ structural_leads: RefactoringPlan[];
+}
+
export interface GeneratedSpan {
file: string;
line_start: number;
diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsx
new file mode 100644
index 000000000..1caff9191
--- /dev/null
+++ b/packages/ui/__tests__/health/performance-view.test.tsx
@@ -0,0 +1,237 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+import { PerformanceView, type PerformanceViewAdapter } from "../../src/health/performance-view";
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+});
+
+function page(planId: string | null = "plan-1"): PerformanceOpportunityPage {
+ return {
+ items: [
+ {
+ opportunity_id: "opp-1",
+ biomarker_type: "io_in_loop",
+ biomarker_types: ["io_in_loop"],
+ boundary_kind: "db",
+ execution_context: "production",
+ terminal_sink: "src/db.py::fetch",
+ shared_path_suffix: ["src/shared.py::load", "src/db.py::fetch"],
+ intervention_symbol: "src/shared.py::load",
+ affected_call_sites_total: 2,
+ affected_files_total: 2,
+ observations_total: 6,
+ evidence: [
+ {
+ finding_id: "finding-1",
+ file_path: "src/a.py",
+ biomarker_type: "io_in_loop",
+ function_name: "run",
+ line_start: 10,
+ line_end: 10,
+ reason: "Database work repeats.",
+ path: ["src/a.py::run", "src/shared.py::load", "src/db.py::fetch"],
+ provenance: "reliable-edge",
+ },
+ {
+ finding_id: "finding-2",
+ file_path: "src/b.py",
+ biomarker_type: "io_in_loop",
+ function_name: "run",
+ line_start: 20,
+ line_end: 20,
+ reason: "Database work repeats.",
+ path: ["src/b.py::run", "src/shared.py::load", "src/db.py::fetch"],
+ provenance: "reliable-edge",
+ },
+ ],
+ evidence_truncated: true,
+ reliable_entry_reachability: true,
+ provenance: "reliable-edge",
+ confidence: "medium",
+ rank_score: 12.5,
+ rank_factors: {},
+ fix: {
+ strategy: "batch_or_prefetch_io",
+ safety: "advisory",
+ rationale: "Validate result equivalence.",
+ },
+ plan_id: planId,
+ plan_status: planId ? "available" : "no_safe_plan",
+ plan_reason: planId ? "Exact match." : "No coherent intervention was proven.",
+ },
+ ],
+ total: 1,
+ has_more: false,
+ next_offset: null,
+ summary: {
+ total: 2,
+ production_total: 1,
+ tooling_total: 0,
+ test_total: 1,
+ with_plan_total: planId ? 1 : 0,
+ without_plan_total: planId ? 1 : 2,
+ },
+ };
+}
+
+function adapter(load = vi.fn(async () => page())): PerformanceViewAdapter {
+ return {
+ cacheKey: `repo-${Math.random()}`,
+ listFindings: vi.fn(async () => []),
+ getPerformanceOpportunities: load,
+ getPerformanceOpportunityFindings: vi.fn(),
+ refactoringPlanHref: (planId) => `/refactoring?plan=${planId}`,
+ fileHref: (path) => `/files/${path}`,
+ symbolHref: (symbol) => `/symbols/${symbol}`,
+ navigate: vi.fn(),
+ };
+}
+
+describe("PerformanceView", () => {
+ it("renders causal totals, context, provenance paths, truncation, and an exact plan handoff", async () => {
+ render(<PerformanceView adapter={adapter()} />);
+ const row = await screen.findByRole("button", { name: /2 call sites/i });
+ expect(screen.getByRole("tab", { name: /Production & tooling 1/i })).toBeTruthy();
+ expect(screen.getByRole("tab", { name: /Test suite 1/i })).toBeTruthy();
+
+ fireEvent.click(row);
+ expect(await screen.findAllByText("Reliable resolved edge")).toHaveLength(2);
+ expect(screen.getByText("2 paths shown of 6 recorded observations.")).toBeTruthy();
+ expect(screen.getByText(/Database · Production · Medium confidence/)).toBeTruthy();
+ expect(screen.getByRole("link", { name: "Open on Refactoring page" }).getAttribute("href")).toBe(
+ "/refactoring?plan=plan-1",
+ );
+ });
+
+ it("switches server-owned context and explains the no-safe-plan state", async () => {
+ const load = vi.fn(async () => page(null));
+ render(<PerformanceView adapter={adapter(load)} />);
+ fireEvent.click(await screen.findByRole("tab", { name: /Test suite 1/i }));
+ await waitFor(() =>
+ expect(load).toHaveBeenLastCalledWith({
+ context: "test",
+ offset: 0,
+ limit: 20,
+ }),
+ );
+ expect(load).toHaveBeenCalledTimes(2);
+
+ fireEvent.click(screen.getByRole("button", { name: /2 call sites/i }));
+ expect(await screen.findByText(/No safe structured plan/)).toBeTruthy();
+ expect(screen.queryByRole("link", { name: "Open on Refactoring page" })).toBeNull();
+ });
+
+ it("distinguishes a safe plan that needs reindexing from no safe plan", async () => {
+ const result = page(null);
+ result.items[0] = {
+ ...result.items[0]!,
+ plan_status: "not_persisted",
+ plan_reason: "A matching recommendation can be materialized by reindexing.",
+ };
+ render(<PerformanceView adapter={adapter(vi.fn(async () => result))} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: /2 call sites/i }));
+ expect(await screen.findByText("Refresh the index to materialize the plan")).toBeTruthy();
+ expect(screen.queryByText("No safe structured plan")).toBeNull();
+ });
+
+ it("opens the canonical refactoring drawer and agent handoff for an exact plan", async () => {
+ const exactPlan: RefactoringPlan = {
+ id: "plan-1",
+ refactoring_type: "performance_fix",
+ file_path: "src/shared.py",
+ target_symbol: "src/shared.py::load",
+ line_start: 8,
+ line_end: 12,
+ plan: {
+ opportunity_id: "opp-1",
+ strategy: "batch_or_prefetch_io",
+ safety: "advisory",
+ intervention_symbol: "src/shared.py::load",
+ affected_locations: [],
+ affected_locations_total: 2,
+ paths: [["src/a.py::run", "src/shared.py::load"]],
+ paths_total: 1,
+ evidence_truncated: false,
+ },
+ evidence: {},
+ impact_delta: 0,
+ effort_bucket: "M",
+ blast_radius: { file_count: 2, files: ["src/a.py", "src/b.py"] },
+ confidence: "medium",
+ source_biomarker: "io_in_loop",
+ rank_score: 12.5,
+ benefit: 4,
+ leverage: 3,
+ cost: 2,
+ risk: 1,
+ };
+ const exact = adapter();
+ exact.getRefactoringPlan = vi.fn(async () => exactPlan);
+ render(<PerformanceView adapter={exact} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: /Inspect 2 call sites/i }));
+ expect(await screen.findByText("The change")).toBeTruthy();
+ expect(screen.getByText("Causal context")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Review raw findings/ })).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for an agent" }));
+ expect(await screen.findByText("AI performance plan")).toBeTruthy();
+ expect(exact.getRefactoringPlan).toHaveBeenCalledWith("plan-1");
+ });
+
+ it("rejects a fetched plan whose stable opportunity identity does not match", async () => {
+ const unrelated: RefactoringPlan = {
+ id: "plan-1",
+ refactoring_type: "performance_fix",
+ file_path: "src/other.py",
+ target_symbol: "src/other.py::work",
+ line_start: null,
+ line_end: null,
+ plan: { opportunity_id: "different-opportunity" },
+ evidence: {},
+ impact_delta: 0,
+ effort_bucket: "M",
+ blast_radius: {},
+ confidence: "medium",
+ source_biomarker: "io_in_loop",
+ rank_score: 1,
+ };
+ const exact = adapter();
+ exact.getRefactoringPlan = vi.fn(async () => unrelated);
+ render(<PerformanceView adapter={exact} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: /Inspect 2 call sites/i }));
+ expect(await screen.findByText(/returned plan no longer matches this opportunity/)).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Copy prompt for an agent" })).toBeNull();
+ });
+
+ it("falls back to bounded raw findings when an older server lacks grouping", async () => {
+ const unavailable = Object.assign(new Error("Not found"), { status: 404 });
+ const legacy = adapter(vi.fn(async () => Promise.reject(unavailable)));
+ legacy.listFindings = vi.fn(async () => [
+ {
+ id: "finding-legacy",
+ dimension: "performance" as const,
+ biomarker_type: "io_in_loop",
+ severity: "medium" as const,
+ health_impact: 0.4,
+ file_path: "src/legacy.py",
+ function_name: null,
+ line_start: 4,
+ line_end: 4,
+ reason: "Repeated file read.",
+ details: {},
+ status: "open",
+ },
+ ]);
+ render(<PerformanceView adapter={legacy} />);
+
+ expect(await screen.findByText("Raw performance findings")).toBeTruthy();
+ expect(legacy.listFindings).toHaveBeenCalledWith({ dimension: "performance", limit: 100 });
+ expect(screen.queryByText("No safe structured plan")).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx b/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx
new file mode 100644
index 000000000..8341e2a2e
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx
@@ -0,0 +1,111 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+import { PriorityExplanation } from "../../src/refactoring/priority-explanation";
+import { PlanDetail } from "../../src/refactoring/plan-detail";
+import { ValidationSummary } from "../../src/refactoring/validation-summary";
+import { RefactoringBoard } from "../../src/refactoring/refactoring-board";
+
+const base = {
+ id: "plan-1",
+ refactoring_type: "performance_fix",
+ file_path: "src/shared.py",
+ target_symbol: "src/shared.py::load",
+ line_start: null,
+ line_end: null,
+ plan: {},
+ evidence: {},
+ impact_delta: 0,
+ effort_bucket: "M",
+ blast_radius: {},
+ confidence: "medium",
+ source_biomarker: "io_in_loop",
+ rank_score: 8.25,
+} satisfies RefactoringPlan;
+
+describe("Phase 4 structured plan contract", () => {
+ it("explains canonical priority components without treating blast as benefit", () => {
+ render(<PriorityExplanation plan={{ ...base, benefit: 4, leverage: 3, cost: 2, risk: 5 }} />);
+ expect(screen.getByText("8.2500")).toBeTruthy();
+ expect(screen.getByText("Blast radius, evidence strength, and validation gaps.")).toBeTruthy();
+ expect(screen.getByText("Health recovered or detector-native gain.")).toBeTruthy();
+ });
+
+ it("keeps true validation totals and labels capped lists", () => {
+ render(
+ <ValidationSummary
+ validation={{
+ basis: "inferred",
+ via: "call-graph",
+ total: 9,
+ tests: ["tests/a.py", "tests/b.py"],
+ truncated: true,
+ affected_files: ["src/shared.py"],
+ affected_symbols: ["src/shared.py::load"],
+ commands: ["pytest tests"],
+ targets: [],
+ }}
+ />,
+ );
+ expect(screen.getByText(/9 guarding tests; 2 shown/)).toBeTruthy();
+ expect(screen.getByText(/capped display rows/)).toBeTruthy();
+ });
+
+ it("degrades honestly when optional fields are missing from an older server", () => {
+ const { rerender } = render(<PriorityExplanation plan={base} />);
+ expect(screen.getByText(/server predates the detailed priority components/)).toBeTruthy();
+ rerender(<ValidationSummary />);
+ expect(screen.getByText(/unavailable from this older server/)).toBeTruthy();
+ });
+
+ it("renders a server-filtered performance plan without re-ranking it locally", () => {
+ render(
+ <RefactoringBoard
+ plans={[base]}
+ showLede={false}
+ serverState={{
+ query: "",
+ sort: "canonical",
+ efforts: [],
+ confidences: [],
+ total: 1,
+ offset: 0,
+ nextOffset: null,
+ }}
+ onServerStateChange={() => {}}
+ />,
+ );
+ expect(screen.getByText("Performance")).toBeTruthy();
+ expect(screen.getByText("1 plan")).toBeTruthy();
+ expect(screen.getByText("src/shared.py::load")).toBeTruthy();
+ });
+
+ it("links the shared intervention and does not mislabel observations as paths", () => {
+ render(
+ <PlanDetail
+ plan={{
+ ...base,
+ line_start: 12,
+ plan: {
+ strategy: "batch_or_prefetch_io",
+ safety: "advisory",
+ intervention_symbol: "src/shared.py::load",
+ paths: [["src/a.py::run", "src/shared.py::load"]],
+ paths_total: 6,
+ evidence_truncated: true,
+ affected_locations: [],
+ affected_locations_total: 0,
+ },
+ }}
+ fileHref={(path, line) => `/files/${path}${line ? `?line=${line}` : ""}`}
+ />,
+ );
+
+ expect(screen.getByRole("link", { name: /src\/shared.py::load/ }).getAttribute("href")).toBe(
+ "/files/src/shared.py?line=12",
+ );
+ expect(screen.getByText(/1 resolved path shown; additional observations remain/)).toBeTruthy();
+ expect(screen.queryByText(/of 6 paths/)).toBeNull();
+ });
+});
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 9fd66fc5a..b63f12695 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -13,6 +13,7 @@
*/
import { deadCodeRiskFactorLabel } from "@repowise-dev/types/dead-code";
+import type { PerformanceOpportunity } from "@repowise-dev/types/health";
import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
@@ -1303,6 +1304,54 @@ export function buildCommitAiPrompt({
// Refactoring plan prompt — hand a deterministic plan to a coding agent
// ─────────────────────────────────────────────────────────────────────
+export interface BuildPerformanceOpportunityPromptOptions {
+ opportunity: PerformanceOpportunity;
+ flavor?: AiPromptFlavor;
+}
+
+/** An evidence-first handoff used only when no exact persisted plan is available. */
+export function buildPerformanceOpportunityPrompt({
+ opportunity,
+ flavor = "generic",
+}: BuildPerformanceOpportunityPromptOptions): string {
+ const evidence = opportunity.evidence.map((item) => {
+ const location = `${item.file_path}${item.line_start ? `:${item.line_start}` : ""}`;
+ const path = item.path.length ? `; path: ${item.path.join(" -> ")}` : "";
+ return `- \`${location}\`: ${item.reason} (${item.provenance}${path})`;
+ });
+ const intervention = opportunity.intervention_symbol
+ ? `Candidate shared intervention: \`${opportunity.intervention_symbol}\`.`
+ : "No shared intervention was proven.";
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ "## Causal performance opportunity",
+ "",
+ `- Stable opportunity ID: \`${opportunity.opportunity_id}\`.`,
+ `- Detector: \`${opportunity.biomarker_type}\`.`,
+ `- Execution context: ${opportunity.execution_context}.`,
+ `- Boundary: ${opportunity.boundary_kind ?? "unknown"}.`,
+ `- Confidence: ${opportunity.confidence}; provenance: ${opportunity.provenance}.`,
+ `- Scope: ${opportunity.affected_call_sites_total} affected call sites across ${opportunity.affected_files_total} files.`,
+ `- ${intervention}`,
+ `- Product status: ${opportunity.plan_reason}`,
+ "",
+ "## Evidence sampled by the analyzer",
+ "",
+ evidence.length ? evidence.join("\n") : "No resolved evidence paths were included in this page.",
+ "",
+ "## What to do",
+ "",
+ "1. Verify the repeated cost and caller-to-sink paths against the real code.",
+ "2. Determine whether one behavior-preserving intervention safely addresses the shared cause.",
+ "3. Identify the tests and commands that prove result equivalence and performance improvement.",
+ "4. If the evidence is insufficient or the intervention is unsafe, stop and explain the blocker instead of editing.",
+ "",
+ "Do not run commands or change files until the evidence and proposed validation have been reviewed.",
+ ].join("\n");
+}
+
export interface BuildRefactoringPlanPromptOptions {
plan: RefactoringPlan;
flavor?: AiPromptFlavor;
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index 17de1e561..81e6c8a69 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -7,8 +7,11 @@ import type {
HealthOverviewResponse,
HealthWorkQueueQuery,
HealthWorkQueueResponse,
+ PerformanceOpportunityPage,
TestsReachingFile,
} from "@repowise-dev/types/health";
+import type { Paginated } from "@repowise-dev/types";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
/** Subset of the findings list query the shared views need. */
export interface CodeHealthFindingsQuery {
@@ -47,6 +50,17 @@ export interface CodeHealthAdapter {
getOverview(limit: number): Promise<HealthOverviewResponse>;
listFindings(opts?: CodeHealthFindingsQuery): Promise<HealthFinding[]>;
+ getPerformanceOpportunities?(opts?: {
+ context?: "production_tooling" | "test" | "all";
+ limit?: number;
+ offset?: number;
+ }): Promise<PerformanceOpportunityPage>;
+ getPerformanceOpportunityFindings?(
+ opportunityId: string,
+ opts?: { limit?: number; offset?: number },
+ ): Promise<Paginated<HealthFinding>>;
+ /** Fetch one exact canonical plan for the performance drawer. */
+ getRefactoringPlan?(planId: string): Promise<RefactoringPlan>;
listFiles(opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
getHealthWorkQueue?(
opts?: HealthWorkQueueQuery,
@@ -79,6 +93,8 @@ export interface CodeHealthAdapter {
fileHref(path: string): string;
/** Build an href to a symbol detail page, or `undefined` if not linkable. */
symbolHref?(symbolId: string): string | undefined;
+ /** Exact stable-id handoff into the existing structured-plan page. */
+ refactoringPlanHref?(planId: string, opportunityId: string): string;
/** Navigate to an href (host wires this to its router). */
navigate(href: string): void;
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index d130fcefe..178a20101 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -2,8 +2,8 @@
/**
* Findings view — the engineer's workbench. The ranked fix-next queue
- * (health work items + file inventory), the cross-function performance-risk
- * panel, and the function-level / hidden-coupling panels.
+ * (health work items + file inventory) and the function-level /
+ * hidden-coupling panels. Performance has its own causal-opportunity view.
*
* Split out of {@link TriageView} so the landing surface stays an airy
* proof + map overview and the dense drill-down lives behind its own tab.
@@ -13,7 +13,7 @@
import { useMemo, useState } from "react";
import useSWR from "swr";
-import { Gauge, Search } from "lucide-react";
+import { Search } from "lucide-react";
import type {
HealthFinding,
HealthFilesResponse,
@@ -25,11 +25,9 @@ import type {
import { Skeleton } from "../ui/skeleton";
import { Button } from "../ui/button";
import { EmptyState } from "../shared/empty-state";
-import { CollapsibleSection } from "../shared/collapsible-section";
import { AiPromptModal } from "./ai-prompt-modal";
import { HealthFileTable, type FileSortField } from "./file-table";
-import { BiomarkerList } from "./biomarker-list";
import { HotFunctionsPanel } from "./hot-functions-panel";
import { HiddenCouplingList } from "./hidden-coupling-list";
import {
@@ -98,17 +96,6 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
[panelFindings],
);
- // Every open performance-pillar finding (the cross-function N+1 / I/O-in-loop
- // moat), for the dedicated Performance risks panel.
- const { data: perfFindings } = useSWR<HealthFinding[]>(
- `code-health-perf-findings:${cacheKey}`,
- () =>
- adapter
- .listFindings({ dimension: "performance", limit: 200 })
- .catch(() => [] as HealthFinding[]),
- { revalidateOnFocus: false },
- );
-
// ---- Queue filters ----
const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
const [biomarker, setBiomarker] = useState<string>("all");
@@ -144,7 +131,14 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
const queueKey = useMemo(
() =>
- JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),
+ JSON.stringify({
+ cacheKey,
+ biomarker,
+ minSeverity,
+ maxEffort,
+ sort,
+ queueLimit,
+ }),
[cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],
);
const loadHealthWorkQueue = (opts: HealthWorkQueueQuery) => {
@@ -250,35 +244,6 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
return (
<div className="space-y-6">
- {/* Performance risks — the cross-function N+1 / I/O-in-loop moat, given a
- dedicated home. Only rendered when risks actually exist (high
- precision, low recall), so a clean repo stays uncluttered. */}
- {perfFindings && perfFindings.length > 0 ? (
- <CollapsibleSection
- title={
- <span className="inline-flex items-center gap-2">
- <Gauge className="h-4 w-4 text-[var(--color-info)]" />
- Performance risks
- </span>
- }
- hint={`${perfFindings.length} ${perfFindings.length === 1 ? "risk" : "risks"}`}
- defaultOpen
- >
- <div className="space-y-3">
- <p className="text-xs text-[var(--color-text-secondary)]">
- Static performance risk: a DB, network, filesystem, or subprocess call
- per loop iteration, detected across function boundaries via the call
- graph. High precision, low recall, never blended into the defect score.
- </p>
- <BiomarkerList
- findings={perfFindings}
- grouped
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- </div>
- </CollapsibleSection>
- ) : null}
-
{/* The full ranked queue + file inventory. */}
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
@@ -309,7 +274,10 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
onChange={setBiomarker}
options={[
{ value: "all", label: "All markers" },
- ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
+ ...biomarkerOptions.map((b) => ({
+ value: b,
+ label: biomarkerLabel(b),
+ })),
]}
/>
<FilterSelect
@@ -340,7 +308,10 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
value={sort ?? "impact_per_effort"}
onChange={(v) => setSort(v as HealthWorkQueueQuery["sort"])}
options={[
- { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
+ {
+ value: "impact_per_effort",
+ label: "Leverage (impact ÷ effort)",
+ },
{ value: "total_impact", label: "Total impact" },
{ value: "score", label: "Worst score" },
{ value: "finding_count", label: "Finding count" },
@@ -499,9 +470,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
findings={hotFunctionFindings}
collapsible
onSelect={(f) => setSelectedFile(f.file_path)}
- symbolHrefFor={(f) =>
- f.symbol_id ? adapter.symbolHref?.(f.symbol_id) : undefined
- }
+ symbolHrefFor={(f) => (f.symbol_id ? adapter.symbolHref?.(f.symbol_id) : undefined)}
/>
) : null}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index d666db655..f095ff7ea 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -41,6 +41,7 @@ export * from "./severity-mark";
export * from "./code-health-adapter";
export * from "./triage-view";
export * from "./findings-view";
+export * from "./performance-view";
export * from "./coverage-view";
export * from "./inferred-tests-view";
export * from "./tests-reaching-list";
diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsx
new file mode 100644
index 000000000..8d83b2b68
--- /dev/null
+++ b/packages/ui/src/health/performance-view.tsx
@@ -0,0 +1,599 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { Gauge, ChevronRight, Sparkles } from "lucide-react";
+import type {
+ HealthFinding,
+ PerformanceOpportunity,
+ PerformanceOpportunityEvidence,
+ PerformanceOpportunityPage,
+} from "@repowise-dev/types/health";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+import { EmptyState } from "../shared/empty-state";
+import { PageLede } from "../shared/page-lede";
+import { PaginationControls } from "../shared/pagination-controls";
+import { ProvenancePathList } from "../shared/provenance-path-list";
+import { ViewTabs } from "../shared/view-tabs";
+import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
+import { StatRibbon } from "../stats/stat-ribbon";
+import { RefactoringDrawer } from "../refactoring/refactoring-drawer";
+import { performancePlanDetail } from "../refactoring/types";
+import { PERF_BOUNDARY_LABEL } from "@repowise-dev/types/health";
+import { biomarkerLabel } from "./biomarker-glossary";
+import { BiomarkerList } from "./biomarker-list";
+import type { CodeHealthAdapter } from "./code-health-adapter";
+import { AiPromptModal } from "./ai-prompt-modal";
+import {
+ buildPerformanceOpportunityPrompt,
+ buildRefactoringPlanPrompt,
+} from "./ai-prompt-builder";
+
+export type PerformanceViewAdapter = Pick<
+ CodeHealthAdapter,
+ | "cacheKey"
+ | "listFindings"
+ | "getPerformanceOpportunities"
+ | "getPerformanceOpportunityFindings"
+ | "getRefactoringPlan"
+ | "refactoringPlanHref"
+ | "fileHref"
+ | "symbolHref"
+ | "navigate"
+>;
+
+const PAGE_SIZE = 20;
+const RAW_PAGE_SIZE = 50;
+type ContextView = "production_tooling" | "test";
+
+function contextLabel(context: PerformanceOpportunity["execution_context"]): string {
+ return context === "test" ? "Test suite" : context === "tooling" ? "Tooling" : "Production";
+}
+
+function opportunityTitle(opportunity: PerformanceOpportunity): string {
+ const boundary = opportunity.boundary_kind
+ ? PERF_BOUNDARY_LABEL[opportunity.boundary_kind].toLowerCase()
+ : "repeated";
+ if (opportunity.terminal_sink) {
+ return `${biomarkerLabel(opportunity.biomarker_type)} reaches ${opportunity.terminal_sink}`;
+ }
+ return `${biomarkerLabel(opportunity.biomarker_type)} in ${boundary} work`;
+}
+
+export function PerformanceView({ adapter }: { adapter: PerformanceViewAdapter }) {
+ const [context, setContext] = useState<ContextView>("production_tooling");
+ const [offset, setOffset] = useState(0);
+ const [selected, setSelected] = useState<PerformanceOpportunity | null>(null);
+ const [promptPlan, setPromptPlan] = useState<RefactoringPlan | null>(null);
+ const [promptOpportunity, setPromptOpportunity] = useState<PerformanceOpportunity | null>(null);
+
+ const load = adapter.getPerformanceOpportunities;
+ const { data, error, isLoading } = useSWR<PerformanceOpportunityPage>(
+ load ? `performance-opportunities:${adapter.cacheKey}:${context}:${offset}` : null,
+ () => load!({ context, offset, limit: PAGE_SIZE }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+ const selectedPlanId = selected?.plan_id ?? null;
+ const {
+ data: selectedPlan,
+ error: selectedPlanError,
+ isLoading: selectedPlanLoading,
+ } = useSWR<RefactoringPlan>(
+ selectedPlanId && adapter.getRefactoringPlan
+ ? `performance-plan:${adapter.cacheKey}:${selectedPlanId}`
+ : null,
+ () => adapter.getRefactoringPlan!(selectedPlanId!),
+ { revalidateOnFocus: false },
+ );
+ const selectedPlanMatches = Boolean(
+ selectedPlan &&
+ selected &&
+ selectedPlan.id === selected.plan_id &&
+ selectedPlan.refactoring_type === "performance_fix" &&
+ performancePlanDetail(selectedPlan).opportunityId === selected.opportunity_id,
+ );
+
+ if (!load) {
+ return <LegacyPerformanceFindings adapter={adapter} />;
+ }
+ if (error && [404, 405].includes(Number((error as { status?: number }).status))) {
+ return <LegacyPerformanceFindings adapter={adapter} />;
+ }
+ if (error) {
+ return (
+ <EmptyState
+ icon={<Gauge className="h-6 w-6" />}
+ title="Couldn’t load performance opportunities"
+ description="The repository may need indexing, or the server may be temporarily unavailable."
+ />
+ );
+ }
+ if (isLoading && !data) {
+ return (
+ <div className="space-y-8">
+ <div className="h-32 animate-pulse bg-[var(--color-bg-surface)]" />
+ <div className="h-12 animate-pulse bg-[var(--color-bg-surface)]" />
+ <div className="h-72 animate-pulse bg-[var(--color-bg-surface)]" />
+ </div>
+ );
+ }
+ if (!data) return null;
+
+ const { summary } = data;
+ const productionToolingTotal = summary.production_total + summary.tooling_total;
+ const stats = [
+ {
+ label: "Production",
+ value: summary.production_total.toLocaleString(),
+ sub: "runtime paths",
+ },
+ {
+ label: "Tooling",
+ value: summary.tooling_total.toLocaleString(),
+ sub: "build and developer paths",
+ },
+ {
+ label: "Test suite",
+ value: summary.test_total.toLocaleString(),
+ sub: "test execution cost",
+ },
+ {
+ label: "Structured plan",
+ value: summary.with_plan_total.toLocaleString(),
+ sub: `of ${summary.total.toLocaleString()} causes`,
+ },
+ ];
+
+ return (
+ <div className="space-y-8">
+ <div className="space-y-6">
+ <PageLede
+ label="Causal opportunities"
+ value={summary.total.toLocaleString()}
+ unit="ranked root causes, not duplicated observations"
+ layout="beside"
+ figureFooter={
+ <p className="text-caption text-[var(--color-text-tertiary)]">
+ Static, high-precision signals. They are not measured latency.
+ </p>
+ }
+ >
+ <p>
+ Repeated caller paths are folded into one cause so the first row answers what should
+ change once, while every raw line finding stays available as evidence.
+ </p>
+ <p>
+ Production and tooling stay separate from test-suite cost. A structured plan appears
+ only when the analysis can name an intervention without guessing.
+ </p>
+ </PageLede>
+ <StatRibbon stats={stats} />
+ </div>
+
+ <section className="space-y-4 border-t border-[var(--color-border-default)] pt-8">
+ <div>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Opportunity queue
+ </h2>
+ <p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">
+ Ordered by the canonical causal score: multiplier shape, boundary, execution context,
+ entry reachability, affected call sites, and resolution provenance.
+ </p>
+ </div>
+ <ViewTabs
+ tabs={[
+ {
+ id: "production_tooling",
+ label: "Production & tooling",
+ badge: productionToolingTotal,
+ },
+ { id: "test", label: "Test suite", badge: summary.test_total },
+ ]}
+ value={context}
+ onValueChange={(value) => {
+ setOffset(0);
+ setContext(value as ContextView);
+ }}
+ />
+
+ {data.items.length === 0 ? (
+ <div className="border-t border-[var(--color-border-default)] py-10 text-center">
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ No causal opportunities in this context
+ </h3>
+ <p className="mx-auto mt-1.5 max-w-[60ch] text-sm text-[var(--color-text-tertiary)]">
+ A supported performance detector must find a repeated cost shape before this queue
+ fills. This does not claim the code is fast.
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {data.items.map((opportunity) => (
+ <OpportunityRow
+ key={opportunity.opportunity_id}
+ opportunity={opportunity}
+ onOpen={() => setSelected(opportunity)}
+ />
+ ))}
+ </div>
+ )}
+
+ <PaginationControls
+ offset={offset}
+ shown={data.items.length}
+ total={data.total}
+ label="opportunities"
+ onPrevious={offset > 0 ? () => setOffset(Math.max(0, offset - PAGE_SIZE)) : undefined}
+ onNext={data.next_offset != null ? () => setOffset(data.next_offset!) : undefined}
+ />
+ </section>
+
+ {selectedPlanId && adapter.getRefactoringPlan ? (
+ <RefactoringDrawer
+ plan={selectedPlanMatches ? (selectedPlan ?? null) : null}
+ loading={selectedPlanLoading}
+ error={
+ selectedPlanError
+ ? "The exact plan could not be loaded. Close this drawer and retry from the queue."
+ : selectedPlan && !selectedPlanMatches
+ ? "The returned plan no longer matches this opportunity. Reindex before handing it to an agent."
+ : undefined
+ }
+ open={selected !== null}
+ onOpenChange={(open) => {
+ if (!open) setSelected(null);
+ }}
+ onAiPrompt={(plan) => {
+ if (selectedPlanMatches) setPromptPlan(plan);
+ }}
+ contextSlot={
+ selected ? <OpportunityCausalEvidence opportunity={selected} adapter={adapter} /> : null
+ }
+ fileHref={(path, line) => {
+ const href = adapter.fileHref(path);
+ return line ? `${href}${href.includes("?") ? "&" : "?"}line=${line}` : href;
+ }}
+ />
+ ) : (
+ <PerformanceOpportunityDrawer
+ opportunity={selected}
+ adapter={adapter}
+ onClose={() => setSelected(null)}
+ onAiPrompt={setPromptOpportunity}
+ />
+ )}
+
+ <AiPromptModal
+ open={promptPlan !== null || promptOpportunity !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ setPromptPlan(null);
+ setPromptOpportunity(null);
+ }
+ }}
+ getPrompt={
+ promptPlan
+ ? (flavor) => buildRefactoringPlanPrompt({ plan: promptPlan, flavor })
+ : promptOpportunity
+ ? (flavor) =>
+ buildPerformanceOpportunityPrompt({ opportunity: promptOpportunity, flavor })
+ : null
+ }
+ filePath={promptPlan?.file_path ?? promptOpportunity?.evidence[0]?.file_path ?? null}
+ title={promptPlan ? "AI performance plan" : "AI performance investigation"}
+ description={
+ promptPlan
+ ? "A ready-to-paste structured plan with the intervention, affected targets, validation, and completion contract."
+ : "A ready-to-paste evidence handoff that asks an agent to verify the cause before proposing any edit."
+ }
+ />
+ </div>
+ );
+}
+
+function LegacyPerformanceFindings({ adapter }: { adapter: PerformanceViewAdapter }) {
+ const { data, error, isLoading } = useSWR<HealthFinding[]>(
+ `performance-findings-legacy:${adapter.cacheKey}`,
+ () => adapter.listFindings({ dimension: "performance", limit: 100 }),
+ { revalidateOnFocus: false },
+ );
+ if (isLoading) return <div className="h-72 animate-pulse bg-[var(--color-bg-surface)]" />;
+ if (error || !data?.length) {
+ return (
+ <EmptyState
+ icon={<Gauge className="h-6 w-6" />}
+ title="No performance opportunities"
+ description="This older server does not provide causal grouping. Reindex with a current server to distinguish an empty result from unsupported grouping."
+ />
+ );
+ }
+ return (
+ <div className="space-y-5">
+ <div>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Raw performance findings
+ </h2>
+ <p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">
+ This server predates causal opportunity groups. Up to 100 canonical findings are shown
+ without inventing plan links or rank semantics.
+ </p>
+ </div>
+ <BiomarkerList
+ findings={data}
+ grouped
+ onSelect={(finding) => adapter.navigate(adapter.fileHref(finding.file_path))}
+ />
+ </div>
+ );
+}
+
+function OpportunityRow({
+ opportunity,
+ onOpen,
+}: {
+ opportunity: PerformanceOpportunity;
+ onOpen: () => void;
+}) {
+ const boundary = opportunity.boundary_kind
+ ? PERF_BOUNDARY_LABEL[opportunity.boundary_kind]
+ : "Local computation";
+
+ return (
+ <article data-performance-opportunity={opportunity.opportunity_id}>
+ <button
+ type="button"
+ onClick={onOpen}
+ aria-label={`Inspect ${opportunity.affected_call_sites_total} call sites for ${opportunityTitle(opportunity)}`}
+ className="grid w-full grid-cols-[18px_minmax(0,1fr)] gap-3 px-2 py-4 text-left hover:bg-[var(--color-bg-elevated)] sm:grid-cols-[18px_minmax(0,1fr)_auto] sm:items-center"
+ >
+ <ChevronRight className="mt-1 h-4 w-4" />
+ <span className="min-w-0">
+ <span className="block break-words text-[15px] font-semibold text-[var(--color-text-primary)]">
+ {opportunityTitle(opportunity)}
+ </span>
+ <span className="mt-1 block text-xs text-[var(--color-text-secondary)]">
+ {boundary} · {contextLabel(opportunity.execution_context)} ·{" "}
+ {opportunity.confidence[0]!.toUpperCase() + opportunity.confidence.slice(1)} confidence
+ </span>
+ </span>
+ <span className="col-start-2 text-xs tabular-nums text-[var(--color-text-tertiary)] sm:col-auto sm:text-right">
+ {opportunity.affected_call_sites_total.toLocaleString()} call site
+ {opportunity.affected_call_sites_total === 1 ? "" : "s"}
+ <br />
+ {opportunity.affected_files_total.toLocaleString()} file
+ {opportunity.affected_files_total === 1 ? "" : "s"}
+ <span
+ className={`mt-1 block font-medium ${
+ opportunity.plan_id
+ ? "text-[var(--color-success)]"
+ : "text-[var(--color-text-tertiary)]"
+ }`}
+ >
+ {opportunity.plan_id
+ ? "Structured plan ready"
+ : opportunity.plan_status === "not_persisted"
+ ? "Index refresh needed"
+ : "Investigation needed"}
+ </span>
+ </span>
+ </button>
+
+ </article>
+ );
+}
+
+function OpportunityCausalEvidence({
+ opportunity,
+ adapter,
+}: {
+ opportunity: PerformanceOpportunity;
+ adapter: PerformanceViewAdapter;
+}) {
+ const paths = opportunity.evidence
+ .filter((item) => item.path.length > 0)
+ .map((item) => ({ nodes: item.path, provenance: item.provenance }));
+ return (
+ <div className="space-y-6">
+ <section>
+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Causal context
+ </h4>
+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">
+ {contextLabel(opportunity.execution_context)} · {opportunity.confidence} confidence ·{" "}
+ {opportunity.provenance.replaceAll("-", " ")} provenance.{" "}
+ {opportunity.intervention_symbol ? (
+ <>
+ Repeated work converges at{" "}
+ <span className="break-all font-mono text-xs text-[var(--color-text-primary)]">
+ {opportunity.intervention_symbol}
+ </span>
+ .
+ </>
+ ) : (
+ <>The paths share a costly sink, but no safe common intervention was proven.</>
+ )}
+ </p>
+ </section>
+ <section>
+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Caller-to-sink paths
+ </h4>
+ <ProvenancePathList
+ paths={paths}
+ total={opportunity.observations_total}
+ fileHref={adapter.fileHref}
+ symbolHref={adapter.symbolHref}
+ />
+ </section>
+ <RawEvidence opportunity={opportunity} adapter={adapter} />
+ </div>
+ );
+}
+
+function PerformanceOpportunityDrawer({
+ opportunity,
+ adapter,
+ onClose,
+ onAiPrompt,
+}: {
+ opportunity: PerformanceOpportunity | null;
+ adapter: PerformanceViewAdapter;
+ onClose: () => void;
+ onAiPrompt: (opportunity: PerformanceOpportunity) => void;
+}) {
+ const planHref = opportunity?.plan_id
+ ? adapter.refactoringPlanHref?.(opportunity.plan_id, opportunity.opportunity_id)
+ : undefined;
+
+ return (
+ <Sheet open={opportunity !== null} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent
+ side="right"
+ closeLabel="Close opportunity"
+ className="w-full max-w-[680px] sm:w-[92vw]"
+ >
+ {opportunity ? (
+ <>
+ <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">
+ <div className="text-[11px] text-[var(--color-text-secondary)]">
+ Causal performance opportunity
+ </div>
+ <SheetTitle className="mt-0.5 break-words text-[15px] font-semibold text-[var(--color-text-primary)]">
+ {opportunityTitle(opportunity)}
+ </SheetTitle>
+ <p className="mt-1 text-[11.5px] text-[var(--color-text-tertiary)]">
+ {contextLabel(opportunity.execution_context)} · {opportunity.confidence} confidence ·{" "}
+ {opportunity.affected_call_sites_total} call sites
+ </p>
+ </div>
+
+ <div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">
+ <OpportunityCausalEvidence opportunity={opportunity} adapter={adapter} />
+
+ <section>
+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Recommended next step
+ </h4>
+ <p className="text-sm font-medium text-[var(--color-text-primary)]">
+ {opportunity.plan_status === "not_persisted"
+ ? "Refresh the index to materialize the plan"
+ : opportunity.plan_id
+ ? "Review the matching structured plan"
+ : "No safe structured plan — investigate before changing code"}
+ </p>
+ <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">
+ {opportunity.plan_reason}
+ </p>
+ {planHref ? (
+ <a
+ href={planHref}
+ className="mt-2 inline-block text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline"
+ >
+ Open on Refactoring page
+ </a>
+ ) : null}
+ </section>
+ </div>
+
+ <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">
+ <button
+ type="button"
+ onClick={() => onAiPrompt(opportunity)}
+ className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-accent-fill)] px-3.5 py-2 text-sm font-semibold text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90"
+ >
+ <Sparkles className="h-4 w-4" />
+ Copy investigation for an agent
+ </button>
+ </div>
+ </>
+ ) : (
+ <SheetTitle className="sr-only">Performance opportunity</SheetTitle>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function RawEvidence({
+ opportunity,
+ adapter,
+}: {
+ opportunity: PerformanceOpportunity;
+ adapter: PerformanceViewAdapter;
+}) {
+ const [open, setOpen] = useState(false);
+ const [offset, setOffset] = useState(0);
+ const load = adapter.getPerformanceOpportunityFindings;
+ const { data, isLoading } = useSWR(
+ open && load
+ ? `performance-raw:${adapter.cacheKey}:${opportunity.opportunity_id}:${offset}`
+ : null,
+ () => load!(opportunity.opportunity_id, { offset, limit: RAW_PAGE_SIZE }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+ const fallback = opportunity.evidence;
+ const items: Array<HealthFinding | PerformanceOpportunityEvidence> = data?.items ?? fallback;
+ const total = data?.total ?? opportunity.observations_total;
+
+ return (
+ <section>
+ <button
+ type="button"
+ onClick={() => setOpen((value) => !value)}
+ aria-expanded={open}
+ className="text-sm font-medium text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline"
+ >
+ {open ? "Hide" : "Review"} raw findings · {total.toLocaleString()} observation
+ {total === 1 ? "" : "s"}
+ </button>
+ {open ? (
+ <div className="mt-3">
+ {isLoading && !data ? (
+ <div className="h-24 animate-pulse bg-[var(--color-bg-surface)]" />
+ ) : (
+ <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {items.map((finding, index) => {
+ const href = adapter.fileHref(finding.file_path);
+ return (
+ <div
+ key={("id" in finding ? finding.id : finding.finding_id) || index}
+ className="py-3"
+ >
+ <a
+ href={href}
+ className="break-all font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {finding.file_path}
+ {finding.line_start ? `:${finding.line_start}` : ""}
+ </a>
+ <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
+ {finding.reason}
+ </p>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {data ? (
+ <PaginationControls
+ offset={offset}
+ shown={data.items.length}
+ total={data.total}
+ label="raw findings"
+ onPrevious={
+ offset > 0 ? () => setOffset(Math.max(0, offset - RAW_PAGE_SIZE)) : undefined
+ }
+ onNext={data.next_offset != null ? () => setOffset(data.next_offset!) : undefined}
+ />
+ ) : opportunity.evidence_truncated ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ {fallback.length.toLocaleString()} shown of {total.toLocaleString()}; connect the
+ paged evidence endpoint to load the rest.
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </section>
+ );
+}
diff --git a/packages/ui/src/refactoring/index.ts b/packages/ui/src/refactoring/index.ts
index 52e5e43ef..5887326ae 100644
--- a/packages/ui/src/refactoring/index.ts
+++ b/packages/ui/src/refactoring/index.ts
@@ -15,3 +15,7 @@ export * from "./refactoring-lede";
export * from "./refactoring-drawer";
export * from "./refactoring-settings-card";
export * from "./refactoring-board";
+export * from "./priority-explanation";
+export * from "./validation-summary";
+export * from "../shared/provenance-path-list";
+export * from "../shared/pagination-controls";
diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsx
index 59dc9d2e4..8a1f189f9 100644
--- a/packages/ui/src/refactoring/meta.tsx
+++ b/packages/ui/src/refactoring/meta.tsx
@@ -1,19 +1,29 @@
"use client";
import * as React from "react";
-import { ArrowRightLeft, CopyMinus, FileStack, Scissors, Split, Unlink } from "lucide-react";
+import { ArrowRightLeft, CopyMinus, FileStack, Gauge, Scissors, Split, Unlink } from "lucide-react";
import type { Confidence, EffortBucket, RefactoringType } from "@repowise-dev/types/refactoring";
export interface RefactoringTypeMeta {
label: string;
/** One-line description of what the refactoring does. */
blurb: string;
- Icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>;
+ Icon: React.ComponentType<{
+ className?: string;
+ style?: React.CSSProperties;
+ }>;
/** A CSS var name used for the type's accent (text + tinted backgrounds). */
accentVar: string;
}
export const TYPE_META: Record<string, RefactoringTypeMeta> = {
+ performance_fix: {
+ label: "Performance",
+ blurb:
+ "Change one proven intervention to remove repeated runtime, tooling, or test-suite work.",
+ Icon: Gauge,
+ accentVar: "--color-accent-primary",
+ },
extract_class: {
label: "Extract Class",
blurb: "Split a low-cohesion class into focused, single-responsibility classes.",
@@ -88,6 +98,7 @@ export const CONFIDENCE_DOT: Record<Confidence, string> = {
/** Order types deterministically for legends and tab rows. */
export const TYPE_ORDER: RefactoringType[] = [
+ "performance_fix",
"extract_class",
"extract_helper",
"extract_method",
diff --git a/packages/ui/src/refactoring/plan-before.tsx b/packages/ui/src/refactoring/plan-before.tsx
index 80b0d48a9..ecdecf7ea 100644
--- a/packages/ui/src/refactoring/plan-before.tsx
+++ b/packages/ui/src/refactoring/plan-before.tsx
@@ -6,6 +6,7 @@ import {
extractClassGroups,
extractHelperOccurrences,
moveTarget,
+ performancePlanDetail,
splitGroups,
splitResidual,
} from "./types";
@@ -45,6 +46,35 @@ const ACCENT = "var(--color-accent-fill)";
export function PlanBefore({ plan }: PlanBeforeProps) {
const accent = ACCENT;
+ if (plan.refactoring_type === "performance_fix") {
+ const detail = performancePlanDetail(plan);
+ const shown = detail.affectedLocations.slice(0, 4);
+ return (
+ <div className="space-y-2">
+ <p className="text-2xs text-[var(--color-text-tertiary)]">
+ The same expensive operation is reached from {detail.affectedLocationsTotal} call site
+ {detail.affectedLocationsTotal === 1 ? "" : "s"} before the shared intervention.
+ </p>
+ {shown.map((location, index) => (
+ <div
+ key={`${location.file_path}:${location.line_start ?? index}`}
+ className="border-t border-[var(--color-border-default)] py-2"
+ >
+ <code className="break-all text-2xs text-[var(--color-text-secondary)]">
+ {location.file_path}
+ {location.line_start ? `:${location.line_start}` : ""}
+ </code>
+ </div>
+ ))}
+ {detail.affectedLocationsTotal > shown.length ? (
+ <p className="text-2xs text-[var(--color-text-tertiary)]">
+ {shown.length} shown of {detail.affectedLocationsTotal} affected call sites.
+ </p>
+ ) : null}
+ </div>
+ );
+ }
+
if (plan.refactoring_type === "extract_class") {
const groups = extractClassGroups(plan);
const methods = groups.flatMap((g) => g.methods);
@@ -146,8 +176,7 @@ export function PlanBefore({ plan }: PlanBeforeProps) {
</div>
</div>
<p className="mt-2.5 text-2xs leading-relaxed text-[var(--color-text-tertiary)]">
- It reaches into{" "}
- <code className="text-[var(--color-text-secondary)]">{mv.to_class}</code>
+ It reaches into <code className="text-[var(--color-text-secondary)]">{mv.to_class}</code>
{foreign || own ? (
<>
{" "}
@@ -237,10 +266,7 @@ function CycleGraph({ plan, accent }: { plan: RefactoringPlan; accent: string })
y: cy + r * sin,
lx: cx + (r + 11) * cos,
ly: cy + (r + 11) * sin,
- anchor: (cos > 0.15 ? "start" : cos < -0.15 ? "end" : "middle") as
- | "start"
- | "end"
- | "middle",
+ anchor: (cos > 0.15 ? "start" : cos < -0.15 ? "end" : "middle") as "start" | "end" | "middle",
file: members[i] ?? "",
};
});
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index 559719e23..fe22f6954 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -1,6 +1,7 @@
"use client";
import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";
+import { ProvenancePathList } from "../shared/provenance-path-list";
import {
blastFiles,
cutEdges,
@@ -11,6 +12,7 @@ import {
extractMethodPlan,
helperSite,
moveTarget,
+ performancePlanDetail,
splitBlast,
splitGroups,
splitResidual,
@@ -36,17 +38,19 @@ function FileRef({
path,
line,
fileHref,
+ label,
className = "",
}: {
path: string;
line?: number | null;
fileHref?: PlanDetailProps["fileHref"];
+ label?: string;
/** Extra classes, e.g. `block truncate` inside a `min-w-0` flex item. */
className?: string;
}) {
const inner = (
<>
- {shortFile(path)}
+ {label ?? shortFile(path)}
{line ? <span className="text-[var(--color-text-tertiary)]">:{line}</span> : null}
</>
);
@@ -109,6 +113,73 @@ const ACCENT = "var(--color-accent-fill)";
export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProps) {
const accent = ACCENT;
+ if (plan.refactoring_type === "performance_fix") {
+ const detail = performancePlanDetail(plan);
+ const provenance =
+ typeof plan.evidence?.provenance === "string" ? plan.evidence.provenance : "unresolved";
+ return (
+ <div className="space-y-4">
+ {hideIntro ? null : (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {detail.safety === "proven" ? "Proven" : "Advisory"}{" "}
+ {detail.strategy.replaceAll("_", " ")} at the shared intervention.
+ </p>
+ )}
+ <div className="border-y border-[var(--color-border-default)] py-3">
+ <div className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Intervention point
+ </div>
+ <FileRef
+ path={plan.file_path}
+ line={plan.line_start ?? null}
+ fileHref={fileHref}
+ label={detail.interventionSymbol ?? plan.target_symbol}
+ className="mt-1 block break-all text-xs font-semibold"
+ />
+ </div>
+ <div>
+ <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Caller-to-sink paths
+ </div>
+ <ProvenancePathList
+ paths={detail.paths.map((nodes) => ({ nodes, provenance }))}
+ total={detail.paths.length}
+ fileHref={(path) => fileHref?.(path, null)}
+ />
+ {detail.truncated ? (
+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
+ {detail.paths.length} resolved {detail.paths.length === 1 ? "path" : "paths"} shown;
+ additional observations remain in Code Health evidence.
+ </p>
+ ) : null}
+ </div>
+ <div>
+ <div className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Affected targets
+ </div>
+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {detail.affectedLocations.map((location, index) => (
+ <li key={`${location.file_path}:${location.line_start ?? index}`} className="py-2">
+ <FileRef
+ path={location.file_path}
+ line={location.line_start ?? null}
+ fileHref={fileHref}
+ className="break-all"
+ />
+ </li>
+ ))}
+ </ul>
+ {detail.affectedLocations.length < detail.affectedLocationsTotal ? (
+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
+ {detail.affectedLocations.length} shown of {detail.affectedLocationsTotal} affected
+ call sites.
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+ }
+
if (plan.refactoring_type === "extract_class") {
const groups = extractClassGroups(plan).filter(
(g) => g.methods.length > 0 || g.fields.length > 0,
@@ -300,7 +371,10 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
</div>
<div
className="rounded-lg border px-3 py-2"
- style={{ borderColor: accent, backgroundColor: `color-mix(in srgb, ${accent} 8%, transparent)` }}
+ style={{
+ borderColor: accent,
+ backgroundColor: `color-mix(in srgb, ${accent} 8%, transparent)`,
+ }}
>
<div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
To
diff --git a/packages/ui/src/refactoring/plan-rows.tsx b/packages/ui/src/refactoring/plan-rows.tsx
index 72733f5b8..667e95f38 100644
--- a/packages/ui/src/refactoring/plan-rows.tsx
+++ b/packages/ui/src/refactoring/plan-rows.tsx
@@ -42,13 +42,7 @@ const EFFORT_WORD: Record<string, string> = {
XL: "Extra large",
};
-export function PlanRows({
- plans,
- onOpen,
- onAiPrompt,
- fileHref,
- highlightedId,
-}: PlanRowsProps) {
+export function PlanRows({ plans, onOpen, onAiPrompt, fileHref, highlightedId }: PlanRowsProps) {
return (
<div className="flex flex-col">
{plans.map((plan) => (
@@ -121,10 +115,12 @@ function PlanRow({
</div>
<div className="order-4 text-[12.5px] tabular-nums lg:order-none">
- {gain > 0 ? (
+ {plan.refactoring_type === "performance_fix" && (plan.benefit ?? 0) > 0 ? (
<span className="font-medium text-[var(--color-success)]">
- +{gain.toFixed(1)} health
+ {plan.benefit?.toFixed(1)} benefit
</span>
+ ) : gain > 0 ? (
+ <span className="font-medium text-[var(--color-success)]">+{gain.toFixed(1)} health</span>
) : (
<span className="text-[var(--color-text-tertiary)]">no score change</span>
)}
diff --git a/packages/ui/src/refactoring/priority-explanation.tsx b/packages/ui/src/refactoring/priority-explanation.tsx
new file mode 100644
index 000000000..81bf18084
--- /dev/null
+++ b/packages/ui/src/refactoring/priority-explanation.tsx
@@ -0,0 +1,61 @@
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+export function PriorityExplanation({ plan }: { plan: RefactoringPlan }) {
+ const components = [
+ {
+ label: "Benefit",
+ value: plan.benefit,
+ detail: "Health recovered or detector-native gain.",
+ },
+ {
+ label: "Leverage",
+ value: plan.leverage,
+ detail: "Deficit and dependency or execution centrality.",
+ },
+ {
+ label: "Cost",
+ value: plan.cost,
+ detail: "Estimated effort and change surface.",
+ },
+ {
+ label: "Risk",
+ value: plan.risk,
+ detail: "Blast radius, evidence strength, and validation gaps.",
+ },
+ ];
+ const detailed = components.every((item) => typeof item.value === "number");
+ return (
+ <div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-text-primary)]">Priority score </span>
+ <span className="font-mono tabular-nums">{plan.rank_score.toFixed(4)}</span>. Higher benefit
+ and leverage raise priority; cost and risk reduce it.
+ </p>
+ {detailed ? (
+ <dl className="mt-3 grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-4">
+ {components.map((item) => (
+ <div
+ key={item.label}
+ className="border-t border-[var(--color-border-default)] py-3 pr-4 first:border-t-0 sm:border-t-0"
+ >
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {item.label}
+ </dt>
+ <dd className="mt-1 font-mono text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {item.value!.toFixed(2)}
+ </dd>
+ <p className="mt-1 text-xs leading-relaxed text-[var(--color-text-tertiary)]">
+ {item.detail}
+ </p>
+ </div>
+ ))}
+ </dl>
+ ) : (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ This server predates the detailed priority components; the compatibility priority is still
+ shown.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index a03e38d34..b29be9058 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -20,18 +20,17 @@ import * as React from "react";
import { Search } from "lucide-react";
import { Input } from "../ui/input";
+import { PaginationControls } from "../shared/pagination-controls";
import { PlanRows } from "./plan-rows";
import { RefactoringLede } from "./refactoring-lede";
import { StartHere } from "./start-here";
import { CONFIDENCE_LABEL } from "./meta";
-import {
- blastCount,
- isStructural,
-} from "./types";
+import { blastCount, isStructural } from "./types";
import type {
Confidence,
EffortBucket,
RefactoringPlan,
+ RefactoringSummary,
} from "@repowise-dev/types/refactoring";
const PAGE_SIZE = 60;
@@ -46,13 +45,10 @@ const EFFORT_LABEL_LONG: Record<EffortBucket, string> = {
};
const CONFIDENCE_ORDER: Confidence[] = ["high", "medium", "low"];
-type SortKey = "leverage" | "health" | "effort" | "blast" | "file";
+export type RefactoringSortKey = "canonical" | "health" | "effort" | "blast" | "file";
-const SORT_OPTIONS: { value: SortKey; label: string }[] = [
- // "Leverage" names what the backend rank actually blends: recovered health,
- // how depended-upon the file is, and how much rides along. It used to be
- // labelled "Priority", which named nothing.
- { value: "leverage", label: "Leverage" },
+const SORT_OPTIONS: { value: RefactoringSortKey; label: string }[] = [
+ { value: "canonical", label: "Canonical priority" },
{ value: "health", label: "Health recovered" },
{ value: "effort", label: "Effort, small first" },
{ value: "blast", label: "Files touched" },
@@ -68,6 +64,32 @@ export interface RefactoringBoardProps {
* endpoint's summary and the plan list could disagree under a filter, and
* two sources for one number is how a tab badge starts lying. */
allPlans?: RefactoringPlan[] | undefined;
+ /** Repo-wide totals supplied by the bounded endpoint. */
+ summary?: RefactoringSummary | undefined;
+ /** Bounded canonical structural head for Start here. */
+ structuralPlans?: RefactoringPlan[] | undefined;
+ /** Controlled server-owned filtering and paging. Omit for legacy local mode. */
+ serverState?:
+ | {
+ query: string;
+ sort: RefactoringSortKey;
+ efforts: EffortBucket[];
+ confidences: Confidence[];
+ total: number;
+ offset: number;
+ nextOffset: number | null;
+ }
+ | undefined;
+ onServerStateChange?:
+ | ((
+ change: Partial<
+ Pick<
+ NonNullable<RefactoringBoardProps["serverState"]>,
+ "query" | "sort" | "efforts" | "confidences" | "offset"
+ >
+ >,
+ ) => void)
+ | undefined;
indexedFileCount?: number | undefined;
onOpen?: ((plan: RefactoringPlan) => void) | undefined;
onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
@@ -76,6 +98,7 @@ export interface RefactoringBoardProps {
onSeeStructural?: (() => void) | undefined;
/** Hide the lede and Start here — for hosts that render their own header. */
showLede?: boolean;
+ sectionTitle?: string;
emptyTitle?: string;
emptyHint?: string;
}
@@ -83,30 +106,53 @@ export interface RefactoringBoardProps {
export function RefactoringBoard({
plans,
allPlans,
+ summary,
+ structuralPlans,
+ serverState,
+ onServerStateChange,
indexedFileCount,
onOpen,
onAiPrompt,
fileHref,
onSeeStructural,
showLede = true,
+ sectionTitle = "All plans",
emptyTitle = "No refactoring plans",
emptyHint = "Plans appear here when a file is worth splitting, a cycle worth cutting, a class worth extracting, or a repeated block worth sharing.",
}: RefactoringBoardProps) {
const [query, setQuery] = React.useState("");
- const [sortKey, setSortKey] = React.useState<SortKey>("leverage");
+ const [sortKey, setSortKey] = React.useState<RefactoringSortKey>("canonical");
const [effortSel, setEffortSel] = React.useState<Set<EffortBucket>>(new Set());
const [confSel, setConfSel] = React.useState<Set<Confidence>>(new Set());
const [visibleCount, setVisibleCount] = React.useState(PAGE_SIZE);
+ const controlled = serverState !== undefined && onServerStateChange !== undefined;
+ const server = serverState ?? {
+ query: "",
+ sort: "canonical" as RefactoringSortKey,
+ efforts: [],
+ confidences: [],
+ total: plans.length,
+ offset: 0,
+ nextOffset: null,
+ };
const every = allPlans ?? plans;
- const structural = React.useMemo(() => every.filter(isStructural), [every]);
+ const structural = React.useMemo(
+ () => structuralPlans ?? every.filter(isStructural),
+ [structuralPlans, every],
+ );
+ const activeQuery = controlled ? server.query : query;
+ const activeSort = controlled ? server.sort : sortKey;
+ const activeEfforts = controlled ? new Set(server.efforts) : effortSel;
+ const activeConfidences = controlled ? new Set(server.confidences) : confSel;
// Only offer confidences that occur. A filter is worth building where there
// is something to subtract from.
const confidencesPresent = React.useMemo(() => {
+ if (controlled) return CONFIDENCE_ORDER;
const present = new Set(every.map((p) => p.confidence || "medium"));
return CONFIDENCE_ORDER.filter((c) => present.has(c));
- }, [every]);
+ }, [controlled, every]);
const toggle = React.useCallback(
<T,>(setter: React.Dispatch<React.SetStateAction<Set<T>>>, value: T) => {
@@ -121,6 +167,7 @@ export function RefactoringBoard({
);
const processed = React.useMemo(() => {
+ if (controlled) return plans;
const q = query.trim().toLowerCase();
let out = plans.filter((p) => {
if (q && !`${p.file_path} ${p.target_symbol}`.toLowerCase().includes(q)) return false;
@@ -128,8 +175,8 @@ export function RefactoringBoard({
if (confSel.size && !confSel.has((p.confidence || "medium") as Confidence)) return false;
return true;
});
- // `leverage` keeps the backend's rank order; the rest sort a copy.
- if (sortKey !== "leverage") {
+ // `canonical` keeps the shared service's rank order; the rest sort a copy.
+ if (sortKey !== "canonical") {
out = [...out].sort((a, b) => {
switch (sortKey) {
case "health":
@@ -149,13 +196,13 @@ export function RefactoringBoard({
});
}
return out;
- }, [plans, query, sortKey, effortSel, confSel]);
+ }, [controlled, plans, query, sortKey, effortSel, confSel]);
React.useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [processed]);
- if (every.length === 0) {
+ if ((summary?.total ?? every.length) === 0) {
return (
<div className="border-t border-[var(--color-border-default)] pt-10 text-center">
<h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{emptyTitle}</h3>
@@ -166,12 +213,15 @@ export function RefactoringBoard({
);
}
- const filtersActive = query.trim() !== "" || effortSel.size > 0 || confSel.size > 0;
+ const filtersActive =
+ activeQuery.trim() !== "" || activeEfforts.size > 0 || activeConfidences.size > 0;
+ const displayed = controlled ? processed : processed.slice(0, visibleCount);
+ const resultTotal = controlled ? server.total : processed.length;
return (
<div className="space-y-10">
{showLede ? (
- <RefactoringLede plans={every} indexedFileCount={indexedFileCount} />
+ <RefactoringLede plans={every} summary={summary} indexedFileCount={indexedFileCount} />
) : null}
{showLede && structural.length > 0 ? (
@@ -180,10 +230,10 @@ export function RefactoringBoard({
<section className="space-y-4 border-t border-[var(--color-border-default)] pt-8">
<div>
- <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">All plans</h2>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">{sectionTitle}</h2>
<p className="mt-1 max-w-[68ch] text-sm text-[var(--color-text-secondary)]">
- Ordered by leverage. Every plan opens the same inspector: what changes, why it was
- flagged, and what else it touches.
+ Canonical priority balances benefit and leverage against cost and risk. Every plan opens
+ the same inspector with the full explanation.
</p>
</div>
@@ -191,8 +241,12 @@ export function RefactoringBoard({
<div className="relative min-w-[220px] flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
<Input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
+ value={activeQuery}
+ onChange={(e) =>
+ controlled
+ ? onServerStateChange?.({ query: e.target.value, offset: 0 })
+ : setQuery(e.target.value)
+ }
placeholder="Search file or symbol"
className="pl-9"
aria-label="Search plans"
@@ -207,8 +261,15 @@ export function RefactoringBoard({
</label>
<select
id="refactoring-sort"
- value={sortKey}
- onChange={(e) => setSortKey(e.target.value as SortKey)}
+ value={activeSort}
+ onChange={(e) =>
+ controlled
+ ? onServerStateChange?.({
+ sort: e.target.value as RefactoringSortKey,
+ offset: 0,
+ })
+ : setSortKey(e.target.value as RefactoringSortKey)
+ }
className="h-9 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 text-sm text-[var(--color-text-primary)] transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)]"
>
{SORT_OPTIONS.map((o) => (
@@ -228,8 +289,17 @@ export function RefactoringBoard({
{EFFORTS.map((e) => (
<FilterChip
key={e}
- active={effortSel.has(e)}
- onClick={() => toggle(setEffortSel, e)}
+ active={activeEfforts.has(e)}
+ onClick={() =>
+ controlled
+ ? onServerStateChange?.({
+ efforts: activeEfforts.has(e)
+ ? server.efforts.filter((item) => item !== e)
+ : [...server.efforts, e],
+ offset: 0,
+ })
+ : toggle(setEffortSel, e)
+ }
label={EFFORT_LABEL_LONG[e]}
/>
))}
@@ -242,8 +312,17 @@ export function RefactoringBoard({
{confidencesPresent.map((c) => (
<FilterChip
key={c}
- active={confSel.has(c)}
- onClick={() => toggle(setConfSel, c)}
+ active={activeConfidences.has(c)}
+ onClick={() =>
+ controlled
+ ? onServerStateChange?.({
+ confidences: activeConfidences.has(c)
+ ? server.confidences.filter((item) => item !== c)
+ : [...server.confidences, c],
+ offset: 0,
+ })
+ : toggle(setConfSel, c)
+ }
label={CONFIDENCE_LABEL[c]}
/>
))}
@@ -253,21 +332,27 @@ export function RefactoringBoard({
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">
- {processed.length.toLocaleString()} plan{processed.length === 1 ? "" : "s"}
+ {resultTotal.toLocaleString()} plan{resultTotal === 1 ? "" : "s"}
{filtersActive ? (
- <span className="font-normal text-[var(--color-text-tertiary)]">
- {" "}
- of {plans.length.toLocaleString()}
- </span>
+ <span className="font-normal text-[var(--color-text-tertiary)]"> matching</span>
) : null}
</h3>
{filtersActive ? (
<button
type="button"
onClick={() => {
+ if (controlled)
+ onServerStateChange?.({
+ query: "",
+ efforts: [],
+ confidences: [],
+ offset: 0,
+ });
+ else {
setQuery("");
setEffortSel(new Set());
setConfSel(new Set());
+ }
}}
className="text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline"
>
@@ -283,12 +368,12 @@ export function RefactoringBoard({
) : (
<>
<PlanRows
- plans={processed.slice(0, visibleCount)}
+ plans={displayed}
onOpen={onOpen}
onAiPrompt={onAiPrompt}
fileHref={fileHref}
/>
- {processed.length > visibleCount ? (
+ {!controlled && processed.length > visibleCount ? (
<div className="flex justify-center border-t border-[var(--color-border-default)] pt-5">
<button
type="button"
@@ -302,6 +387,27 @@ export function RefactoringBoard({
</button>
</div>
) : null}
+ {controlled ? (
+ <PaginationControls
+ offset={server.offset}
+ shown={plans.length}
+ total={server.total}
+ label="plans"
+ onPrevious={
+ server.offset > 0
+ ? () =>
+ onServerStateChange?.({
+ offset: Math.max(0, server.offset - PAGE_SIZE),
+ })
+ : undefined
+ }
+ onNext={
+ server.nextOffset != null
+ ? () => onServerStateChange?.({ offset: server.nextOffset! })
+ : undefined
+ }
+ />
+ ) : null}
</>
)}
</section>
diff --git a/packages/ui/src/refactoring/refactoring-drawer.tsx b/packages/ui/src/refactoring/refactoring-drawer.tsx
index a590c840b..380b163d2 100644
--- a/packages/ui/src/refactoring/refactoring-drawer.tsx
+++ b/packages/ui/src/refactoring/refactoring-drawer.tsx
@@ -19,19 +19,17 @@
* line of prose under the title.
*/
+import type { ReactNode } from "react";
import { Layers, Sparkles, TrendingUp, Wand2 } from "lucide-react";
import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
import { formatNumber } from "../lib/format";
import { PlanComparison } from "./plan-comparison";
import { GenerateCodePanel } from "./generate-code-panel";
+import { PriorityExplanation } from "./priority-explanation";
+import { ValidationSummary } from "./validation-summary";
import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
-import {
- blastCount,
- blastFiles,
- evidenceRows,
- planWins,
-} from "./types";
+import { blastCount, blastFiles, evidenceRows, planWins } from "./types";
import type {
Confidence,
EffortBucket,
@@ -43,6 +41,10 @@ export interface RefactoringDrawerProps {
plan: RefactoringPlan | null;
open: boolean;
onOpenChange: (open: boolean) => void;
+ loading?: boolean | undefined;
+ error?: string | undefined;
+ /** Optional causal context supplied by another shared product surface. */
+ contextSlot?: ReactNode;
onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
/** Opt-in LLM code generation. Omit to hide the section entirely. */
onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
@@ -54,6 +56,9 @@ export function RefactoringDrawer({
plan,
open,
onOpenChange,
+ loading = false,
+ error,
+ contextSlot,
onAiPrompt,
onGenerateCode,
settingsHref,
@@ -76,9 +81,27 @@ export function RefactoringDrawer({
onGenerateCode={onGenerateCode}
settingsHref={settingsHref}
fileHref={fileHref}
+ contextSlot={contextSlot}
/>
+ ) : loading ? (
+ <>
+ <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">
+ Loading structured plan
+ </SheetTitle>
+ <div className="space-y-4 px-5 py-5" aria-busy="true">
+ <div className="h-16 animate-pulse bg-[var(--color-bg-surface)]" />
+ <div className="h-40 animate-pulse bg-[var(--color-bg-surface)]" />
+ </div>
+ </>
+ ) : error ? (
+ <>
+ <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">
+ Structured plan unavailable
+ </SheetTitle>
+ <p className="px-5 py-5 text-sm text-[var(--color-text-secondary)]">{error}</p>
+ </>
) : (
- <SheetTitle className="sr-only">Refactoring plan</SheetTitle>
+ <SheetTitle className="sr-only">Structured plan</SheetTitle>
)}
</SheetContent>
</Sheet>
@@ -91,12 +114,14 @@ function DrawerBody({
onGenerateCode,
settingsHref,
fileHref,
+ contextSlot,
}: {
plan: RefactoringPlan;
onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
settingsHref?: string | undefined;
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ contextSlot?: ReactNode;
}) {
const meta = typeMeta(plan.refactoring_type);
const effort = (plan.effort_bucket || "M") as EffortBucket;
@@ -143,6 +168,7 @@ function DrawerBody({
</div>
<div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">
+ {contextSlot}
<p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">{meta.blurb}</p>
<section>
@@ -152,6 +178,23 @@ function DrawerBody({
<PlanComparison plan={plan} fileHref={fileHref} />
</section>
+ <section>
+ <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Priority
+ </h4>
+ <PriorityExplanation plan={plan} />
+ </section>
+
+ <section>
+ <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Validation
+ </h4>
+ <ValidationSummary
+ validation={plan.validation}
+ fileHref={(path) => fileHref?.(path, null)}
+ />
+ </section>
+
{onGenerateCode ? (
<section>
<div className="mb-3 flex items-center justify-between gap-3">
diff --git a/packages/ui/src/refactoring/refactoring-lede.tsx b/packages/ui/src/refactoring/refactoring-lede.tsx
index d34268e87..1cc00d1e6 100644
--- a/packages/ui/src/refactoring/refactoring-lede.tsx
+++ b/packages/ui/src/refactoring/refactoring-lede.tsx
@@ -18,11 +18,13 @@ 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 } from "./types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+import { isStructural, planPoint, STRUCTURAL_TYPES } from "./types";
+import type { RefactoringPlan, RefactoringSummary } from "@repowise-dev/types/refactoring";
export interface RefactoringLedeProps {
plans: RefactoringPlan[];
+ /** True repo totals from the paged endpoint. Older hosts may omit it. */
+ summary?: RefactoringSummary | undefined;
/** Files in the repo, for the "802 of 4,952 indexed" denominator. Omit and
* the ribbon drops the comparison rather than inventing one. */
indexedFileCount?: number | undefined;
@@ -45,29 +47,53 @@ const STRUCTURAL_PHRASE: Record<string, (n: number) => string> = {
move_method: (n) => `${n} method${n === 1 ? "" : "s"} living on the wrong class`,
};
-export function RefactoringLede({ plans, indexedFileCount, action }: RefactoringLedeProps) {
- const total = plans.length;
+export function RefactoringLede({
+ plans,
+ summary,
+ indexedFileCount,
+ action,
+}: RefactoringLedeProps) {
+ const total = summary?.total ?? plans.length;
const structural = plans.filter(isStructural);
- const local = total - structural.length;
+ const structuralTotal = summary?.structural_total ?? structural.length;
+ const performanceTotal =
+ summary?.performance_total ??
+ plans.filter((p) => p.refactoring_type === "performance_fix").length;
+ const local = Math.max(0, total - structuralTotal - performanceTotal);
- const files = new Set(plans.map((p) => p.file_path)).size;
- const small = plans.filter((p) => (p.effort_bucket || "M") === "S").length;
- const recovers = plans.filter((p) => p.impact_delta >= 0.1).length;
+ const files = summary?.files_total ?? new Set(plans.map((p) => p.file_path)).size;
+ const small =
+ summary?.small_effort_total ?? plans.filter((p) => (p.effort_bucket || "M") === "S").length;
+ const recovers =
+ summary?.health_recovery_total ?? plans.filter((p) => p.impact_delta >= 0.1).length;
const plottable = structural.filter((p) => planPoint(p) !== null).length;
const byType = new Map<string, number>();
- for (const p of structural) byType.set(p.refactoring_type, (byType.get(p.refactoring_type) ?? 0) + 1);
+ if (summary) {
+ for (const item of summary.by_type) {
+ if ((STRUCTURAL_TYPES as readonly string[]).includes(item.type)) {
+ byType.set(item.type, item.count);
+ }
+ }
+ } else {
+ for (const p of structural)
+ byType.set(p.refactoring_type, (byType.get(p.refactoring_type) ?? 0) + 1);
+ }
const structuralPhrase = joinPhrases(
[...byType.entries()]
.sort((a, b) => b[1] - a[1])
- .map(([type, n]) => STRUCTURAL_PHRASE[type]?.(n) ?? `${n} ${typeMeta(type).label.toLowerCase()}`),
+ .map(
+ ([type, n]) => STRUCTURAL_PHRASE[type]?.(n) ?? `${n} ${typeMeta(type).label.toLowerCase()}`,
+ ),
);
// The largest single recovery on the page. Quoted rather than assumed,
// because the ceiling is what makes "rank by health recovered" a bad idea and
// a reader is entitled to check the claim.
- const bestGain = plans.reduce((m, p) => Math.max(m, p.impact_delta), 0);
- const negligible = plans.filter((p) => p.impact_delta < 0.5).length;
+ const bestGain =
+ summary?.best_health_gain ?? plans.reduce((m, p) => Math.max(m, p.impact_delta), 0);
+ const negligible =
+ summary?.negligible_health_total ?? plans.filter((p) => p.impact_delta < 0.5).length;
const stats: RibbonStat[] = [
{
@@ -87,8 +113,11 @@ export function RefactoringLede({ plans, indexedFileCount, action }: Refactoring
},
{
label: "Change a file's shape",
- value: formatNumber(structural.length),
- sub: plottable < structural.length ? `${formatNumber(plottable)} measured` : "the rest are local",
+ value: formatNumber(structuralTotal),
+ sub:
+ plottable < structural.length
+ ? `${formatNumber(plottable)} measured among displayed leads`
+ : `${formatNumber(structural.length)} displayed leads`,
},
];
@@ -101,10 +130,12 @@ export function RefactoringLede({ plans, indexedFileCount, action }: Refactoring
layout="beside"
action={action}
figureFooter={
- structural.length > 0 ? (
+ structuralTotal > 0 ? (
<p className="text-caption text-[var(--color-text-tertiary)]">
- {formatNumber(structural.length)} of them change a file&apos;s shape. The rest are
- local.
+ {formatNumber(structuralTotal)} change a file&apos;s shape
+ {performanceTotal
+ ? `; ${formatNumber(performanceTotal)} address a causal performance opportunity.`
+ : ". The rest are local."}
</p>
) : undefined
}
@@ -118,11 +149,20 @@ export function RefactoringLede({ plans, indexedFileCount, action }: Refactoring
small effort. They are worth doing when you are already in the file, and they are not
worth a planning meeting.
</p>
- {structural.length > 0 ? (
+ {performanceTotal > 0 ? (
<p>
<span className="font-medium text-[var(--color-text-primary)]">
- {formatNumber(structural.length)}{" "}
- {structural.length === 1 ? "is structural" : "are structural"}.
+ {formatNumber(performanceTotal)} performance plan
+ {performanceTotal === 1 ? "" : "s"}.
+ </span>{" "}
+ These preserve detector-native benefit even when defect-health recovery is zero.
+ </p>
+ ) : null}
+ {structuralTotal > 0 ? (
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {formatNumber(structuralTotal)}{" "}
+ {structuralTotal === 1 ? "is structural" : "are structural"}.
</span>{" "}
{structuralPhrase}. These change how the codebase is shaped, so they lead the page.
</p>
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 63374f6b9..7090bbeac 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -223,6 +223,51 @@ export function splitBlast(plan: RefactoringPlan): SplitBlast {
}
/** A one-line synopsis for the compact card — what the plan does, at a glance. */
+export interface PerformancePlanDetail {
+ opportunityId: string | null;
+ strategy: string;
+ safety: string;
+ interventionSymbol: string | null;
+ affectedLocations: Array<{
+ file_path: string;
+ function_name?: string | null;
+ line_start?: number | null;
+ line_end?: number | null;
+ }>;
+ affectedLocationsTotal: number;
+ paths: string[][];
+ pathsTotal: number;
+ truncated: boolean;
+}
+
+export function performancePlanDetail(plan: RefactoringPlan): PerformancePlanDetail {
+ const value = plan.plan ?? {};
+ const locations = Array.isArray(value.affected_locations) ? value.affected_locations : [];
+ const paths = Array.isArray(value.paths) ? value.paths : [];
+ return {
+ opportunityId: typeof value.opportunity_id === "string" ? value.opportunity_id : null,
+ strategy: typeof value.strategy === "string" ? value.strategy : "performance intervention",
+ safety: typeof value.safety === "string" ? value.safety : "advisory",
+ interventionSymbol:
+ typeof value.intervention_symbol === "string" ? value.intervention_symbol : null,
+ affectedLocations: locations.filter(
+ (item): item is PerformancePlanDetail["affectedLocations"][number] =>
+ Boolean(
+ item &&
+ typeof item === "object" &&
+ typeof (item as { file_path?: unknown }).file_path === "string",
+ ),
+ ),
+ affectedLocationsTotal: Number(value.affected_locations_total ?? locations.length),
+ paths: paths.filter(
+ (item): item is string[] =>
+ Array.isArray(item) && item.every((node) => typeof node === "string"),
+ ),
+ pathsTotal: Number(value.paths_total ?? paths.length),
+ truncated: value.evidence_truncated === true,
+ };
+}
+
export function planSynopsis(plan: RefactoringPlan): string {
switch (plan.refactoring_type) {
case "extract_class": {
@@ -256,6 +301,10 @@ export function planSynopsis(plan: RefactoringPlan): string {
const n = splitGroups(plan).length;
return `Split into ${n} module${n === 1 ? "" : "s"}`;
}
+ case "performance_fix": {
+ const detail = performancePlanDetail(plan);
+ return `${detail.strategy.replaceAll("_", " ")} at ${detail.interventionSymbol ?? plan.target_symbol}`;
+ }
default:
return "";
}
@@ -306,6 +355,8 @@ export const EVIDENCE_LABELS: Record<string, string> = {
cut_edges: "Cut edges",
slice_nloc: "Extracted lines",
ccn_removed: "Complexity removed",
+ observations_total: "Observations",
+ affected_files_total: "Affected files",
};
export function evidenceRows(plan: RefactoringPlan): { label: string; value: string }[] {
@@ -313,7 +364,10 @@ export function evidenceRows(plan: RefactoringPlan): { label: string; value: str
for (const [key, label] of Object.entries(EVIDENCE_LABELS)) {
const v = plan.evidence?.[key];
if (typeof v === "number" && Number.isFinite(v)) {
- rows.push({ label, value: Number.isInteger(v) ? String(v) : v.toFixed(2) });
+ rows.push({
+ label,
+ value: Number.isInteger(v) ? String(v) : v.toFixed(2),
+ });
}
}
return rows;
@@ -355,7 +409,11 @@ export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null
const status = v.status;
if (status === "skipped") {
const reason = typeof v.reason === "string" ? v.reason : null;
- return { tone: "neutral", label: "Self-check skipped", ...(reason ? { detail: reason } : {}) };
+ return {
+ tone: "neutral",
+ label: "Self-check skipped",
+ ...(reason ? { detail: reason } : {}),
+ };
}
if (status !== "checked") return null;
@@ -413,14 +471,20 @@ export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null
export function planWins(plan: RefactoringPlan): PlanWin[] {
const wins: PlanWin[] = [];
if (plan.impact_delta > 0) {
- wins.push({ hero: true, label: `+${plan.impact_delta.toFixed(1)} health recovered` });
+ wins.push({
+ hero: true,
+ label: `+${plan.impact_delta.toFixed(1)} health recovered`,
+ });
}
switch (plan.refactoring_type) {
case "extract_class": {
const n = extractClassGroups(plan).filter(
(g) => g.methods.length > 0 || g.fields.length > 0,
).length;
- if (n) wins.push({ label: `${n} focused, single-responsibility class${n === 1 ? "" : "es"}` });
+ if (n)
+ wins.push({
+ label: `${n} focused, single-responsibility class${n === 1 ? "" : "es"}`,
+ });
break;
}
case "extract_helper": {
@@ -441,9 +505,14 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
const ccn = Number(plan.evidence?.ccn_removed ?? 0);
if (em.span) {
const lines = em.span.end - em.span.start + 1;
- wins.push({ label: `${lines} line${lines === 1 ? "" : "s"} lifted into a focused helper` });
+ wins.push({
+ label: `${lines} line${lines === 1 ? "" : "s"} lifted into a focused helper`,
+ });
}
- if (ccn) wins.push({ label: `-${ccn} cyclomatic complexity on the original method` });
+ if (ccn)
+ wins.push({
+ label: `-${ccn} cyclomatic complexity on the original method`,
+ });
break;
}
case "move_method": {
@@ -455,13 +524,19 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
const members = cycleMembers(plan).length;
const edges = cutEdges(plan).length;
if (members) wins.push({ label: `${members} files untangled` });
- if (edges) wins.push({ label: `${edges} import edge${edges === 1 ? "" : "s"} cut` });
+ if (edges)
+ wins.push({
+ label: `${edges} import edge${edges === 1 ? "" : "s"} cut`,
+ });
break;
}
case "split_file": {
const n = splitGroups(plan).length;
const blast = splitBlast(plan);
- if (n) wins.push({ label: `${n} focused module${n === 1 ? "" : "s"} from one file` });
+ if (n)
+ wins.push({
+ label: `${n} focused module${n === 1 ? "" : "s"} from one file`,
+ });
if (blast.import_rewrites > 0) {
wins.push({
label: `${blast.import_rewrites} dependent file${
@@ -477,6 +552,13 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
}
break;
}
+ case "performance_fix": {
+ const detail = performancePlanDetail(plan);
+ wins.push({
+ label: `${detail.affectedLocationsTotal} repeated call site${detail.affectedLocationsTotal === 1 ? "" : "s"} addressed at one intervention`,
+ });
+ break;
+ }
}
return wins;
}
@@ -534,6 +616,11 @@ export function planReason(plan: RefactoringPlan): string {
const num = (key: string): number => Number(ev[key] ?? 0);
switch (plan.refactoring_type) {
+ case "performance_fix": {
+ const detail = performancePlanDetail(plan);
+ const rationale = typeof plan.evidence?.rationale === "string" ? plan.evidence.rationale : "";
+ return `${detail.safety === "proven" ? "Proven" : "Advisory"} ${detail.strategy.replaceAll("_", " ")} across ${detail.affectedLocationsTotal} affected call site${detail.affectedLocationsTotal === 1 ? "" : "s"}.${rationale ? ` ${rationale}` : ""}`;
+ }
case "split_file": {
const parts: string[] = [];
const nloc = num("file_nloc");
diff --git a/packages/ui/src/refactoring/validation-summary.tsx b/packages/ui/src/refactoring/validation-summary.tsx
new file mode 100644
index 000000000..cb2d4944a
--- /dev/null
+++ b/packages/ui/src/refactoring/validation-summary.tsx
@@ -0,0 +1,108 @@
+import type { RecommendationValidation, ValidationBasis } from "@repowise-dev/types/refactoring";
+
+const BASIS_LABEL: Record<ValidationBasis, string> = {
+ measured: "Measured coverage",
+ inferred: "Inferred reachability",
+ mixed: "Mixed evidence",
+ unknown: "Validation gap",
+};
+
+export interface ValidationSummaryProps {
+ validation?: RecommendationValidation | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}
+
+export function ValidationSummary({ validation, fileHref }: ValidationSummaryProps) {
+ if (!validation) {
+ return (
+ <p className="text-sm text-[var(--color-text-tertiary)]">
+ Validation detail is unavailable from this older server.
+ </p>
+ );
+ }
+ const basis = BASIS_LABEL[validation.basis] ?? validation.basis;
+ return (
+ <div className="space-y-4">
+ <div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ <span className="font-medium text-[var(--color-text-primary)]">{basis}</span>
+ {validation.via ? ` via ${validation.via.replace("-", " ")}` : ""}.{" "}
+ {validation.total.toLocaleString()} guarding test
+ {validation.total === 1 ? "" : "s"}
+ {validation.truncated ? `; ${validation.tests.length.toLocaleString()} shown.` : "."}
+ </p>
+ {validation.basis === "unknown" ? (
+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
+ No measured or inferred guarding test was found. Treat this as explicit validation work.
+ </p>
+ ) : null}
+ </div>
+
+ {validation.tests.length > 0 ? (
+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {validation.tests.map((test) => (
+ <li
+ key={test}
+ className="break-all py-2 font-mono text-xs text-[var(--color-text-secondary)]"
+ >
+ {test}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {validation.affected_files.length > 0 ? (
+ <div>
+ <h5 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Affected paths
+ </h5>
+ <ul className="mt-1.5 space-y-1">
+ {validation.affected_files.map((path) => {
+ const href = fileHref?.(path, null);
+ return (
+ <li
+ key={path}
+ className="break-all font-mono text-xs text-[var(--color-text-secondary)]"
+ >
+ {href ? (
+ <a
+ href={href}
+ className="underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {path}
+ </a>
+ ) : (
+ path
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ ) : null}
+
+ {validation.commands.length > 0 ? (
+ <div>
+ <h5 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Suggested commands
+ </h5>
+ <div className="mt-1.5 space-y-1.5">
+ {validation.commands.map((command) => (
+ <code
+ key={command}
+ className="block overflow-x-auto whitespace-nowrap bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-secondary)]"
+ >
+ {command}
+ </code>
+ ))}
+ </div>
+ {validation.truncated ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ The command is widened so capped display rows do not become a narrower validation run.
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/shared/pagination-controls.tsx b/packages/ui/src/shared/pagination-controls.tsx
new file mode 100644
index 000000000..8a1a6e9d9
--- /dev/null
+++ b/packages/ui/src/shared/pagination-controls.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+export interface PaginationControlsProps {
+ offset: number;
+ shown: number;
+ total: number;
+ onPrevious?: (() => void) | undefined;
+ onNext?: (() => void) | undefined;
+ label?: string;
+}
+
+/** Shared bounded-list footer. Totals always describe the server-side set. */
+export function PaginationControls({
+ offset,
+ shown,
+ total,
+ onPrevious,
+ onNext,
+ label = "items",
+}: PaginationControlsProps) {
+ if (total === 0) return null;
+ const first = offset + 1;
+ const last = offset + shown;
+ return (
+ <nav
+ aria-label={`${label} pagination`}
+ className="flex flex-col gap-3 border-t border-[var(--color-border-default)] pt-4 sm:flex-row sm:items-center sm:justify-between"
+ >
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Showing{" "}
+ <span className="tabular-nums">
+ {first.toLocaleString()}–{last.toLocaleString()}
+ </span>{" "}
+ of <span className="tabular-nums">{total.toLocaleString()}</span> {label}
+ </p>
+ <div className="flex gap-2">
+ <button
+ type="button"
+ onClick={onPrevious}
+ disabled={!onPrevious}
+ className="rounded-lg border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ Previous
+ </button>
+ <button
+ type="button"
+ onClick={onNext}
+ disabled={!onNext}
+ className="rounded-lg border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ Next
+ </button>
+ </div>
+ </nav>
+ );
+}
diff --git a/packages/ui/src/shared/provenance-path-list.tsx b/packages/ui/src/shared/provenance-path-list.tsx
new file mode 100644
index 000000000..507044192
--- /dev/null
+++ b/packages/ui/src/shared/provenance-path-list.tsx
@@ -0,0 +1,102 @@
+import { ArrowRight } from "lucide-react";
+
+export interface ProvenancePath {
+ nodes: string[];
+ provenance: string;
+ filePath?: string | undefined;
+ line?: number | null | undefined;
+}
+
+export interface ProvenancePathListProps {
+ paths: ProvenancePath[];
+ total?: number | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ symbolHref?: ((symbolId: string) => string | undefined) | undefined;
+}
+
+const PROVENANCE_LABEL: Record<string, string> = {
+ "call-site": "Exact call-site resolution",
+ direct: "Direct local resolution",
+ "reliable-edge": "Reliable resolved edge",
+ "name-fallback": "Compatibility name fallback",
+};
+
+function nodeHref(
+ node: string,
+ fileHref: ProvenancePathListProps["fileHref"],
+ symbolHref: ProvenancePathListProps["symbolHref"],
+): string | undefined {
+ const symbol = symbolHref?.(node);
+ if (symbol) return symbol;
+ const separator = node.indexOf("::");
+ const file = separator >= 0 ? node.slice(0, separator) : node;
+ return /[./\\]/.test(file) ? fileHref?.(file, null) : undefined;
+}
+
+/** Shared caller-to-sink rendering for Code Health and structured plans. */
+export function ProvenancePathList({
+ paths,
+ total = paths.length,
+ fileHref,
+ symbolHref,
+}: ProvenancePathListProps) {
+ if (paths.length === 0) {
+ return (
+ <p className="text-sm text-[var(--color-text-tertiary)]">No resolved path was recorded.</p>
+ );
+ }
+ return (
+ <div>
+ <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {paths.map((path, index) => (
+ <div key={`${path.nodes.join("→")}:${index}`} className="py-3">
+ <div className="flex flex-wrap items-center gap-1.5">
+ {path.nodes.map((node, nodeIndex) => {
+ const href = nodeHref(node, fileHref, symbolHref);
+ const name = node.split("::").pop() ?? node;
+ return (
+ <span
+ key={`${node}:${nodeIndex}`}
+ className="inline-flex min-w-0 items-center gap-1.5"
+ >
+ {nodeIndex > 0 ? (
+ <ArrowRight
+ className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]"
+ aria-hidden
+ />
+ ) : null}
+ {href ? (
+ <a
+ href={href}
+ title={node}
+ className="break-all font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {name}
+ </a>
+ ) : (
+ <span
+ title={node}
+ className="break-all font-mono text-xs text-[var(--color-text-secondary)]"
+ >
+ {name}
+ </span>
+ )}
+ </span>
+ );
+ })}
+ </div>
+ <p className="mt-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {PROVENANCE_LABEL[path.provenance] ?? path.provenance}
+ </p>
+ </div>
+ ))}
+ </div>
+ {total > paths.length ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ {paths.length.toLocaleString()} paths shown of {total.toLocaleString()} recorded
+ observations.
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/vscode/CHANGELOG.md b/packages/vscode/CHANGELOG.md
index 4bcdf1ad3..a39ba20a0 100644
--- a/packages/vscode/CHANGELOG.md
+++ b/packages/vscode/CHANGELOG.md
@@ -79,6 +79,12 @@ upgrade with `pip install --upgrade repowise`.
### Refactoring
+- Performance plans use the same refactoring webview, tree and CodeLens as
+ structural plans. Priority comes from the canonical shared contract, and the
+ drawer renders validation basis, provenance, true totals, capped tests and
+ commands through shared UI components. Missing fields from older servers
+ degrade cleanly; the extension does not import web code or execute a plan.
+
- An extract-helper plan names a directory as its destination. It used to
prefer a graph community label, which named a directory the duplicated code
did not live in: censused over 963 stored plans, all 905 that carried a label
diff --git a/packages/vscode/src/features/refactoringLens.ts b/packages/vscode/src/features/refactoringLens.ts
index 8d9b58c99..673ed76bc 100644
--- a/packages/vscode/src/features/refactoringLens.ts
+++ b/packages/vscode/src/features/refactoringLens.ts
@@ -1,5 +1,8 @@
import * as vscode from "vscode";
-import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
+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/types/refactoring";
import { CONFIG_SECTION, InternalCommands } from "../constants";
@@ -113,13 +116,20 @@ function createProvider(
/** "Repowise: Extract Class plan (impact 1.20)". */
function lensTitle(plan: RefactoringPlan): string {
- return `Repowise: ${typeMeta(plan.refactoring_type).label} plan (impact ${plan.impact_delta.toFixed(2)})`;
+ const score =
+ typeof plan.rank_score === "number"
+ ? `priority ${plan.rank_score.toFixed(2)}`
+ : `impact ${plan.impact_delta.toFixed(2)}`;
+ return `Repowise: ${typeMeta(plan.refactoring_type).label} plan (${score})`;
}
/** Open the designed plan panel, seeded with this plan (and its file for the list). */
function openRefactoringPlan(ctx: RepowiseContext, plan: RefactoringPlan): void {
if (!plan) return;
- openViewPanel(ctx, "refactoring", { planId: plan.id, filePath: plan.file_path });
+ openViewPanel(ctx, "refactoring", {
+ planId: plan.id,
+ filePath: plan.file_path,
+ });
}
/** Pick a prompt flavor and copy the shared agent prompt for this plan. */
diff --git a/packages/vscode/src/features/trees/refactoring.ts b/packages/vscode/src/features/trees/refactoring.ts
index d19988cd4..0afec3160 100644
--- a/packages/vscode/src/features/trees/refactoring.ts
+++ b/packages/vscode/src/features/trees/refactoring.ts
@@ -55,7 +55,10 @@ class RefactoringTreeProvider extends RepowiseTreeProvider {
const tooltip = new vscode.MarkdownString();
tooltip.appendMarkdown(`**${humanizeType(plan.refactoring_type)}**\n\n`);
tooltip.appendMarkdown(`\`${plan.file_path}\`\n\n`);
- tooltip.appendMarkdown(`- Impact: ${plan.impact_delta.toFixed(2)}\n`);
+ tooltip.appendMarkdown(`- Priority: ${plan.rank_score.toFixed(2)}\n`);
+ if (plan.impact_delta > 0) {
+ tooltip.appendMarkdown(`- Health recovery: ${plan.impact_delta.toFixed(2)}\n`);
+ }
tooltip.appendMarkdown(`- Effort: ${plan.effort_bucket}\n`);
tooltip.appendMarkdown(`- Confidence: ${plan.confidence}\n`);
const blast = blastCount(plan.blast_radius);
@@ -65,7 +68,7 @@ class RefactoringTreeProvider extends RepowiseTreeProvider {
label: `${humanizeType(plan.refactoring_type)} ${
plan.target_symbol ?? baseName(plan.file_path)
}`,
- description: `impact ${plan.impact_delta.toFixed(2)} · ${plan.effort_bucket}`,
+ description: `priority ${plan.rank_score.toFixed(2)} · ${plan.effort_bucket}`,
tooltip,
icon: new vscode.ThemeIcon("wrench"),
collapsibleState: vscode.TreeItemCollapsibleState.None,
diff --git a/packages/vscode/webview/src/views/refactoring/App.test.tsx b/packages/vscode/webview/src/views/refactoring/App.test.tsx
index 64c799bf5..dc6f21a5a 100644
--- a/packages/vscode/webview/src/views/refactoring/App.test.tsx
+++ b/packages/vscode/webview/src/views/refactoring/App.test.tsx
@@ -13,17 +13,27 @@ const PLAN: RefactoringPlan = {
target_symbol: "process_everything",
line_start: 40,
line_end: 120,
- plan: { span: { start: 60, end: 90 }, params: ["items"], returns: ["total"], suggested_name: "sum_items" },
+ plan: {
+ span: { start: 60, end: 90 },
+ params: ["items"],
+ returns: ["total"],
+ suggested_name: "sum_items",
+ },
evidence: { ccn_removed: 7 },
impact_delta: 1.4,
effort_bucket: "M",
- blast_radius: { files: ["packages/core/src/caller.py"], file_count: 1 },
+ blast_radius: { files: ["packages/core/src/caller.py"], file_count: 9 },
confidence: "high",
source_biomarker: "complexity",
rank_score: 0.9,
};
-const REPO = { id: "r1", name: "repo", headCommit: "abc", defaultBranch: "main" } as const;
+const REPO = {
+ id: "r1",
+ name: "repo",
+ headCommit: "abc",
+ defaultBranch: "main",
+} as const;
function makeHost(overrides: Partial<WebviewHost["api"]> = {}): {
host: WebviewHost;
@@ -62,11 +72,68 @@ describe("refactoring App detail page", () => {
// Clicking a flavor button builds that flavor's prompt and copies it.
fireEvent.click(screen.getByRole("button", { name: "Claude Code + Repowise MCP" }));
- await waitFor(() => expect(refactoringPrompt).toHaveBeenCalledWith("plan-1", "claude-code-mcp"));
+ await waitFor(() =>
+ expect(refactoringPrompt).toHaveBeenCalledWith("plan-1", "claude-code-mcp"),
+ );
await waitFor(() => expect(copyText).toHaveBeenCalledTimes(1));
expect(copyText).toHaveBeenCalledWith(
"GENERATED PROMPT",
"Plan prompt copied for Claude Code + Repowise MCP.",
);
});
+
+ it("renders a performance plan with shared priority and validation handoff", async () => {
+ const performance: RefactoringPlan = {
+ ...PLAN,
+ id: "perf-1",
+ refactoring_type: "performance_fix",
+ target_symbol: "packages/core/src/db.py::fetch",
+ impact_delta: 0,
+ benefit: 3.2,
+ leverage: 2.1,
+ cost: 1.4,
+ risk: 2.8,
+ plan: {
+ opportunity_id: "opp-1",
+ strategy: "batch_or_prefetch_io",
+ safety: "advisory",
+ intervention_symbol: "packages/core/src/db.py::fetch",
+ affected_locations: [
+ {
+ file_path: "packages/core/src/orders.py",
+ line_start: 44,
+ line_end: 44,
+ },
+ ],
+ affected_locations_total: 7,
+ paths: [["packages/core/src/orders.py::load", "packages/core/src/db.py::fetch"]],
+ paths_total: 7,
+ evidence_truncated: true,
+ },
+ validation: {
+ basis: "inferred",
+ via: "call-graph",
+ total: 6,
+ tests: ["tests/test_orders.py"],
+ truncated: true,
+ affected_files: ["packages/core/src/orders.py"],
+ affected_symbols: ["packages/core/src/db.py::fetch"],
+ commands: ["pytest tests/test_orders.py"],
+ targets: [],
+ },
+ };
+ const { host } = makeHost({
+ refactoringPlan: vi.fn().mockResolvedValue(performance),
+ });
+
+ render(<App host={host} repo={REPO} params={{ planId: "perf-1" }} refreshToken={0} />);
+
+ expect(await screen.findByText("Performance")).toBeTruthy();
+ expect(screen.getByText("Priority score")).toBeTruthy();
+ expect(screen.getByText(/6 guarding tests; 1 shown/)).toBeTruthy();
+ expect(screen.getByText("pytest tests/test_orders.py")).toBeTruthy();
+ expect(screen.getByText("1 shown of 7 affected call sites.")).toBeTruthy();
+ expect(screen.getByText("9 affected files recorded")).toBeTruthy();
+ expect(screen.getByText("1 shown of 9 affected files.")).toBeTruthy();
+ });
});
diff --git a/packages/vscode/webview/src/views/refactoring/App.tsx b/packages/vscode/webview/src/views/refactoring/App.tsx
index 95ec44dec..f3e2c9230 100644
--- a/packages/vscode/webview/src/views/refactoring/App.tsx
+++ b/packages/vscode/webview/src/views/refactoring/App.tsx
@@ -8,13 +8,10 @@ import {
typeMeta,
} from "@repowise-dev/ui/refactoring/meta";
import { PlanDetail } from "@repowise-dev/ui/refactoring/plan-detail";
+import { PriorityExplanation } from "@repowise-dev/ui/refactoring/priority-explanation";
+import { ValidationSummary } from "@repowise-dev/ui/refactoring/validation-summary";
import { RefactoringPlanCard } from "@repowise-dev/ui/refactoring/refactoring-plan-card";
-import {
- blastCount,
- blastFiles,
- evidenceRows,
- planWins,
-} from "@repowise-dev/ui/refactoring/types";
+import { blastCount, blastFiles, evidenceRows, planWins } from "@repowise-dev/ui/refactoring/types";
import type {
Confidence,
EffortBucket,
@@ -70,9 +67,7 @@ export function App({ host, params, refreshToken }: ViewProps<"refactoring">) {
// ── Async state helper ─────────────────────────────────────────────────────
type AsyncState<T> =
- | { status: "loading" }
- | { status: "error"; message: string }
- | { status: "ok"; data: T };
+ { status: "loading" } | { status: "error"; message: string } | { status: "ok"; data: T };
function useAsync<T>(load: () => Promise<T>, deps: unknown[]): AsyncState<T> {
const [state, setState] = useState<AsyncState<T>>({ status: "loading" });
@@ -85,7 +80,10 @@ function useAsync<T>(load: () => Promise<T>, deps: unknown[]): AsyncState<T> {
},
(err: unknown) => {
if (!cancelled) {
- setState({ status: "error", message: err instanceof Error ? err.message : String(err) });
+ setState({
+ status: "error",
+ message: err instanceof Error ? err.message : String(err),
+ });
}
},
);
@@ -196,6 +194,14 @@ function PlanDetailView({ host, planId, refreshToken, onBack }: PlanDetailViewPr
<PlanDetail plan={plan} fileHref={fileHref} />
</Section>
+ <Section title="Priority">
+ <PriorityExplanation plan={plan} />
+ </Section>
+
+ <Section title="Validation">
+ <ValidationSummary validation={plan.validation} fileHref={fileHref} />
+ </Section>
+
{evidence.length > 0 ? (
<Section title="Evidence">
<dl className="grid grid-cols-2 gap-2 sm:grid-cols-3">
@@ -220,7 +226,7 @@ function PlanDetailView({ host, planId, refreshToken, onBack }: PlanDetailViewPr
<div className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
<Layers className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
{affected.length > 0
- ? `${affected.length} other file${affected.length === 1 ? "" : "s"} to keep consistent`
+ ? `${blast} affected file${blast === 1 ? "" : "s"} recorded`
: blast > 0
? `${blast} dependent${blast === 1 ? "" : "s"} affected`
: "No dependent files recorded."}
@@ -245,6 +251,11 @@ function PlanDetailView({ host, planId, refreshToken, onBack }: PlanDetailViewPr
) : null}
</ul>
) : null}
+ {affected.length > 0 && affected.length < blast ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ {Math.min(affected.length, 25)} shown of {blast} affected files.
+ </p>
+ ) : null}
</Section>
<CopyForAgentRow host={host} planId={planId} />
@@ -264,7 +275,10 @@ function PlanHeader({ plan, onOpenFile }: { plan: RefactoringPlan; onOpenFile: (
<div className="flex flex-wrap items-center gap-3">
<span
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[15px] font-semibold"
- style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}
+ style={{
+ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`,
+ color: accent,
+ }}
>
<Icon className="h-4 w-4" />
{meta.label}
@@ -338,9 +352,7 @@ function CopyForAgentRow({ host, planId }: { host: WebviewHost; planId: string }
</button>
))}
</div>
- {copyError ? (
- <p className="mt-2 text-xs text-[var(--color-error)]">{copyError}</p>
- ) : null}
+ {copyError ? <p className="mt-2 text-xs text-[var(--color-error)]">{copyError}</p> : null}
</div>
);
}
@@ -355,10 +367,7 @@ interface PlanListViewProps {
}
function PlanListView({ host, filePath, refreshToken, onOpen }: PlanListViewProps) {
- const state = useAsync(
- () => host.api.refactoringTargets(filePath),
- [filePath, refreshToken],
- );
+ const state = useAsync(() => host.api.refactoringTargets(filePath), [filePath, refreshToken]);
if (state.status === "loading") return <CenteredNote>Loading refactoring plans…</CenteredNote>;
if (state.status === "error") {
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index 4fe5a1434..a059e415c 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -8,7 +8,9 @@
* (health / maintainability / performance / churn) so the cross-tab redundancy
* collapses.
*
- * Six tabs, down from seven. Hotspots is gone: it rendered a *second* galaxy map
+ * Performance has its own causal-opportunity tab; raw observations remain its
+ * evidence rather than competing with the ranked finding queue. Hotspots is
+ * gone: it rendered a *second* galaxy map
* on the churn lens directly under this page's, so churn became a lens here and
* what the lens cannot say — bus factor, the ranked table — became a section
* under the map. Blast radius keeps its `impact` tab id (existing file-card and
@@ -34,6 +36,7 @@ import type { DeadCodeSummary } from "@repowise-dev/types/dead-code";
import { TriageTab } from "@/components/code-health/triage-tab";
import { HotspotsSection } from "@/components/code-health/hotspots-section";
import { FindingsTab } from "@/components/code-health/findings-tab";
+import { PerformanceTab } from "@/components/code-health/performance-tab";
import { CoverageTab } from "@/components/code-health/coverage-tab";
import { TrendSection } from "@/components/code-health/trend-tab";
import { DeadCodeTab } from "@/components/risk/dead-code-tab";
@@ -53,11 +56,20 @@ import {
type HealthFilesResponse,
} from "@/lib/api/code-health";
-const TABS = ["triage", "findings", "coverage", "dead-code", "security", "impact"] as const;
+const TABS = [
+ "triage",
+ "performance",
+ "findings",
+ "coverage",
+ "dead-code",
+ "security",
+ "impact",
+] as const;
type TabId = (typeof TABS)[number];
const TAB_LABELS: Record<TabId, string> = {
triage: "Overview",
+ performance: "Performance",
findings: "Findings",
coverage: "Tests",
"dead-code": "Dead code",
@@ -137,23 +149,22 @@ export default function CodeHealthPage() {
const refresh = useCallback(async () => {
setRefreshing(true);
try {
- await mutateAll(
- (key) => typeof key === "string" && key.includes(repoId),
- undefined,
- { revalidate: true },
- );
+ await mutateAll((key) => typeof key === "string" && key.includes(repoId), undefined, {
+ revalidate: true,
+ });
} finally {
setRefreshing(false);
}
}, [mutateAll, repoId]);
// Trend fetched ONCE here, fed to the folded Trend section — no second fetch.
- const { data: trend, isLoading: trendLoading, error: trendError } =
- useSWR<HealthTrendResponse>(
- `code-health-trend:${repoId}`,
- () => getHealthTrend(repoId, 20),
- { revalidateOnFocus: false },
- );
+ const {
+ data: trend,
+ isLoading: trendLoading,
+ error: trendError,
+ } = useSWR<HealthTrendResponse>(`code-health-trend:${repoId}`, () => getHealthTrend(repoId, 20), {
+ revalidateOnFocus: false,
+ });
// Every file (NLOC-first) for the map — one big pull, shared across overlays
// so switching the lens never refetches. `fields: "summary"` because the map
@@ -309,6 +320,7 @@ export default function CodeHealthPage() {
/>
)}
{activeTab === "findings" && <FindingsTab repoId={repoId} />}
+ {activeTab === "performance" && <PerformanceTab repoId={repoId} />}
{activeTab === "coverage" && <CoverageTab repoId={repoId} />}
{activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}
{activeTab === "security" && <SecurityTab repoId={repoId} />}
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index 10aef46ec..77e202f2d 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -12,7 +12,7 @@
* a plan you can send to someone.
*/
-import { use, useCallback, useMemo, useState } from "react";
+import { use, useCallback, useDeferredValue, useMemo, useState } from "react";
import useSWR from "swr";
import { parseAsString, parseAsStringLiteral, useQueryState } from "nuqs";
import { Wrench, RotateCw } from "lucide-react";
@@ -25,18 +25,27 @@ import {
STRUCTURAL_TYPES,
TYPE_ORDER,
typeMeta,
+ type RefactoringSortKey,
} from "@repowise-dev/ui/refactoring";
-import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/types/refactoring";
+import type {
+ Confidence,
+ EffortBucket,
+ RefactoringPlan,
+ RefactoringPlanPage,
+} from "@repowise-dev/types/refactoring";
import { AiPromptModal, buildRefactoringPlanPrompt } from "@repowise-dev/ui/health";
import {
generateRefactoringCode,
getRefactoringSettings,
+ getRefactoringPlan,
+ getRefactoringPlansPage,
getRefactoringTargets,
type RefactoringSettings,
} from "@/lib/api/refactoring";
const TYPE_VALUES = ["all", "structural", ...TYPE_ORDER] as const;
type TypeFilter = (typeof TYPE_VALUES)[number];
+type RefactoringPageData = RefactoringPlanPage & { legacy?: boolean };
export default function RefactoringPage({ params }: { params: Promise<{ id: string }> }) {
const { id: repoId } = use(params);
@@ -45,24 +54,67 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
parseAsStringLiteral(TYPE_VALUES).withDefault("all"),
);
const [openPlanId, setOpenPlanId] = useQueryState("plan", parseAsString);
+ const [query, setQuery] = useState("");
+ const deferredQuery = useDeferredValue(query);
+ const [sort, setSort] = useState<RefactoringSortKey>("canonical");
+ const [efforts, setEfforts] = useState<EffortBucket[]>([]);
+ const [confidences, setConfidences] = useState<Confidence[]>([]);
+ const [offset, setOffset] = useState(0);
- const { data, error, isLoading, mutate } = useSWR<RefactoringTargets>(
- `refactoring:${repoId}`,
- () => getRefactoringTargets(repoId),
- { revalidateOnFocus: false },
+ const { data, error, isLoading, mutate } = useSWR<RefactoringPageData>(
+ [
+ "refactoring-page",
+ repoId,
+ type,
+ deferredQuery,
+ sort,
+ efforts.join(","),
+ confidences.join(","),
+ offset,
+ ],
+ async () => {
+ try {
+ return await getRefactoringPlansPage(repoId, {
+ refactoringType: type === "all" ? undefined : type,
+ search: deferredQuery || undefined,
+ sort,
+ effort: efforts.join(",") || undefined,
+ confidence: confidences.join(",") || undefined,
+ limit: 60,
+ offset,
+ });
+ } catch (caught) {
+ const status = Number((caught as { status?: number }).status);
+ if (status !== 404 && status !== 405) throw caught;
+ const legacy = await getRefactoringTargets(repoId, {
+ refactoringType:
+ type === "all" || type === "structural" ? undefined : type,
+ });
+ const items =
+ type === "structural"
+ ? legacy.plans.filter((plan) =>
+ (STRUCTURAL_TYPES as readonly string[]).includes(plan.refactoring_type),
+ )
+ : legacy.plans;
+ return {
+ items,
+ total: items.length,
+ has_more: false,
+ next_offset: null,
+ summary: legacy.summary,
+ structural_leads: legacy.plans
+ .filter((plan) =>
+ (STRUCTURAL_TYPES as readonly string[]).includes(plan.refactoring_type),
+ )
+ .slice(0, 12),
+ legacy: true,
+ };
+ }
+ },
+ { revalidateOnFocus: false, keepPreviousData: true },
);
- const allPlans = useMemo(() => data?.plans ?? [], [data?.plans]);
-
- const filtered = useMemo(() => {
- if (type === "all") return allPlans;
- if (type === "structural") {
- return allPlans.filter((p) =>
- (STRUCTURAL_TYPES as readonly string[]).includes(p.refactoring_type),
- );
- }
- return allPlans.filter((p) => p.refactoring_type === type);
- }, [allPlans, type]);
+ const plans = useMemo(() => data?.items ?? [], [data?.items]);
const prefix = `/repos/${repoId}`;
// `PlanRows` offers a second `line` argument and this deliberately ignores
@@ -73,10 +125,16 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
// The open plan comes from the URL, so a reload or a shared link lands on the
// same drawer rather than the top of the list.
- const openPlan = useMemo(
- () => allPlans.find((p) => p.id === openPlanId) ?? null,
- [allPlans, openPlanId],
+ const openPlanOnPage = useMemo(
+ () => plans.find((p) => p.id === openPlanId) ?? null,
+ [plans, openPlanId],
+ );
+ const { data: linkedPlan } = useSWR<RefactoringPlan>(
+ openPlanId && !openPlanOnPage ? ["refactoring-plan", repoId, openPlanId] : null,
+ () => getRefactoringPlan(repoId, openPlanId!),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
);
+ const openPlan = openPlanOnPage ?? linkedPlan ?? null;
const [promptPlan, setPromptPlan] = useState<RefactoringPlan | null>(null);
const onAiPrompt = useCallback((plan: RefactoringPlan) => setPromptPlan(plan), []);
@@ -105,7 +163,11 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
const tabs = [
{ id: "all" as const, label: "All", badge: data?.summary.total },
{ id: "structural" as const, label: "Structural", badge: structuralCount },
- ...TYPE_ORDER.map((t) => ({ id: t, label: typeMeta(t).label, badge: counts.get(t) ?? 0 })),
+ ...TYPE_ORDER.map((t) => ({
+ id: t,
+ label: typeMeta(t).label,
+ badge: counts.get(t) ?? 0,
+ })),
].filter((t) => t.id === "all" || (t.badge ?? 0) > 0);
return (
@@ -128,7 +190,10 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
<ViewTabs
tabs={tabs}
value={type}
- onValueChange={(id) => void setType(id as TypeFilter)}
+ onValueChange={(id) => {
+ setOffset(0);
+ void setType(id as TypeFilter);
+ }}
/>
{error ? (
@@ -145,16 +210,54 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
</div>
) : (
<RefactoringBoard
- plans={filtered}
- allPlans={allPlans}
+ plans={plans}
+ allPlans={data?.legacy ? data.items : data?.structural_leads}
+ structuralPlans={
+ data?.legacy
+ ? data.items.filter((plan) =>
+ (STRUCTURAL_TYPES as readonly string[]).includes(plan.refactoring_type),
+ )
+ : data?.structural_leads
+ }
+ summary={data?.summary}
+ serverState={
+ data?.legacy
+ ? undefined
+ : {
+ query,
+ sort,
+ efforts,
+ confidences,
+ total: data?.total ?? 0,
+ offset,
+ nextOffset: data?.next_offset ?? null,
+ }
+ }
+ onServerStateChange={(change) => {
+ if (change.query !== undefined) setQuery(change.query);
+ if (change.sort !== undefined) setSort(change.sort);
+ if (change.efforts !== undefined) setEfforts(change.efforts);
+ if (change.confidences !== undefined) setConfidences(change.confidences);
+ if (change.offset !== undefined) setOffset(change.offset);
+ }}
onOpen={(plan) => void setOpenPlanId(plan.id)}
onAiPrompt={onAiPrompt}
- onSeeStructural={() => void setType("structural")}
+ onSeeStructural={() => {
+ setOffset(0);
+ void setType("structural");
+ }}
fileHref={fileHref}
// The lede and Start here describe the whole repo, so they only
// belong on the unfiltered view — under a type filter they would
// be talking about a set the list below is not showing.
showLede={type === "all"}
+ sectionTitle={
+ type === "all"
+ ? "All plans"
+ : type === "structural"
+ ? "Structural plans"
+ : `${typeMeta(type).label} plans`
+ }
/>
)}
</div>
diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsx
index 5ccb957e9..8cb15fe32 100644
--- a/packages/web/src/components/code-health/findings-tab.tsx
+++ b/packages/web/src/components/code-health/findings-tab.tsx
@@ -2,17 +2,14 @@
/**
* Findings host — binds the shared {@link FindingsView} (the fix-next queue,
- * performance risks, and function-level panels) to web's `/api` client,
+ * and function-level panels) to web's `/api` client,
* `/repos/:id` routing, and the file-detail drawer. The composition itself
* lives in `@repowise-dev/ui/health`; this file only injects the app-specific
* pieces so web and hosted render the same view.
*/
import { useRouter } from "next/navigation";
-import {
- FindingsView,
- type CodeHealthAdapter,
-} from "@repowise-dev/ui/health";
+import { FindingsView, type CodeHealthAdapter } from "@repowise-dev/ui/health";
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getHealthOverview,
diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsx
new file mode 100644
index 000000000..492ada5b6
--- /dev/null
+++ b/packages/web/src/components/code-health/performance-tab.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { PerformanceView, type PerformanceViewAdapter } from "@repowise-dev/ui/health";
+import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
+import {
+ getPerformanceOpportunities,
+ getPerformanceOpportunityFindings,
+ listHealthFindings,
+} from "@/lib/api/code-health";
+import { getRefactoringPlan } from "@/lib/api/refactoring";
+
+export function PerformanceTab({ repoId }: { repoId: string }) {
+ const router = useRouter();
+ const prefix = `/repos/${repoId}`;
+ const adapter: PerformanceViewAdapter = {
+ cacheKey: repoId,
+ listFindings: (options) => listHealthFindings(repoId, options),
+ getPerformanceOpportunities: (options) => getPerformanceOpportunities(repoId, options),
+ getPerformanceOpportunityFindings: (opportunityId, options) =>
+ getPerformanceOpportunityFindings(repoId, opportunityId, options),
+ getRefactoringPlan: (planId) => getRefactoringPlan(repoId, planId),
+ refactoringPlanHref: (planId) =>
+ `/repos/${repoId}/refactoring?type=performance_fix&plan=${encodeURIComponent(planId)}`,
+ fileHref: (path) => fileEntityPath(prefix, path),
+ symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
+ navigate: (href) => router.push(href),
+ };
+
+ return <PerformanceView adapter={adapter} />;
+}
diff --git a/tests/unit/persistence/test_refactoring_suggestions_crud.py b/tests/unit/persistence/test_refactoring_suggestions_crud.py
index ba41b8e39..38421816d 100644
--- a/tests/unit/persistence/test_refactoring_suggestions_crud.py
+++ b/tests/unit/persistence/test_refactoring_suggestions_crud.py
@@ -194,3 +194,37 @@ async def test_performance_only_partial_scope_clears_stale_plan(async_session):
rows = await get_refactoring_suggestions(async_session, repo.id)
assert [(row.refactoring_type, row.target_symbol) for row in rows] == [("extract_class", "Foo")]
+
+
+async def test_partial_performance_scope_persists_downstream_intervention(async_session):
+ from repowise.core.pipeline.incremental import persist_partial_health
+
+ repo = await insert_repo(async_session)
+ performance = _suggestion(
+ "shared.py",
+ "shared.py::load",
+ refactoring_type="performance_fix",
+ source_biomarker="io_in_loop",
+ plan={
+ "opportunity_id": "opp-shared",
+ "strategy": "batch_or_prefetch_io",
+ "affected_locations": [{"file_path": "caller.py", "line_start": 10}],
+ },
+ )
+ report = SimpleNamespace(
+ authoritative_paths=set(),
+ performance_authoritative_paths={"caller.py"},
+ metrics=[],
+ findings=[],
+ refactoring_suggestions=[performance],
+ function_blame_rows=[],
+ )
+
+ await persist_partial_health(async_session, repo.id, report)
+ await async_session.commit()
+
+ rows = await get_refactoring_suggestions(async_session, repo.id)
+ assert [(row.refactoring_type, row.file_path, row.target_symbol) for row in rows] == [
+ ("performance_fix", "shared.py", "shared.py::load")
+ ]
diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.py
new file mode 100644
index 000000000..211ff87c1
--- /dev/null
+++ b/tests/unit/server/test_performance_opportunities.py
@@ -0,0 +1,125 @@
+"""Bounded causal performance product API and exact plan handoff."""
+
+from __future__ import annotations
+
+from httpx import AsyncClient
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.analysis.health.perf.opportunities import (
+ build_performance_opportunities,
+ link_performance_findings,
+)
+from repowise.core.analysis.health.refactoring.performance_fix import (
+ performance_fix_suggestions,
+)
+from repowise.core.persistence import crud
+from tests.unit.server.conftest import create_test_repo
+
+
+def _finding(path: str, line: int, path_nodes: list[str], *, marker: str = "io_in_loop"):
+ return HealthFindingData(
+ biomarker_type=marker,
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=line,
+ line_end=line,
+ details={
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": path_nodes,
+ "resolution_basis": "reliable-edge",
+ },
+ health_impact=0.0,
+ reason="Database work repeats for every loop iteration.",
+ dimension="performance",
+ )
+
+
+async def _seed(app, client: AsyncClient) -> tuple[str, str]:
+ repo = await create_test_repo(client)
+ findings = [
+ _finding("src/a.py", 10, ["src/a.py::run", "src/shared.py::load", "src/db.py::fetch"]),
+ _finding("src/b.py", 20, ["src/b.py::run", "src/shared.py::load", "src/db.py::fetch"]),
+ # A separate test-suite cause with no coherent shared intervention.
+ _finding(
+ "tests/test_db.py",
+ 30,
+ ["tests/test_db.py::run", "src/db.py::fetch"],
+ marker="serial_await_in_loop",
+ ),
+ ]
+ link_performance_findings(findings)
+ opportunities = build_performance_opportunities(findings)
+ production = next(item for item in opportunities if item.execution_context == "production")
+ plans = performance_fix_suggestions([production])
+ async with app.state.session_factory() as session:
+ await crud.save_health_findings(session, repo["id"], findings)
+ await crud.save_refactoring_suggestions(session, repo["id"], plans)
+ await session.commit()
+ return repo["id"], production.opportunity_id
+
+
+async def test_opportunities_are_grouped_bounded_and_split_by_context(
+ client: AsyncClient, app
+) -> None:
+ repo_id, opportunity_id = await _seed(app, client)
+ production = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/performance-opportunities", params={"limit": 1}
+ )
+ ).json()
+
+ assert len(production["items"]) == 1
+ assert production["items"][0]["opportunity_id"] == opportunity_id
+ assert production["items"][0]["affected_call_sites_total"] == 2
+ assert production["items"][0]["confidence"] == "medium"
+ assert production["items"][0]["plan_status"] == "available"
+ assert production["items"][0]["plan_id"]
+ assert production["summary"] == {
+ "total": 2,
+ "production_total": 1,
+ "tooling_total": 0,
+ "test_total": 1,
+ "with_plan_total": 1,
+ "without_plan_total": 1,
+ }
+
+ test_page = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/performance-opportunities",
+ params={"context": "test"},
+ )
+ ).json()
+ assert test_page["total"] == 1
+ assert test_page["items"][0]["plan_id"] is None
+ assert test_page["items"][0]["plan_status"] == "no_safe_plan"
+
+
+async def test_raw_evidence_is_paged_and_plan_matching_never_falls_back(
+ client: AsyncClient, app
+) -> None:
+ repo_id, opportunity_id = await _seed(app, client)
+ first = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}/findings",
+ params={"limit": 1},
+ )
+ ).json()
+ second = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}/findings",
+ params={"limit": 1, "offset": first["next_offset"]},
+ )
+ ).json()
+ assert first["total"] == 2
+ assert len(first["items"]) == len(second["items"]) == 1
+ assert first["items"][0]["id"] != second["items"][0]["id"]
+
+ async with app.state.session_factory() as session:
+ rows = await crud.get_refactoring_suggestions(session, repo_id)
+ rows[0].plan_json = '{"opportunity_id":"unrelated"}'
+ await session.commit()
+ page = (await client.get(f"/api/repos/{repo_id}/health/performance-opportunities")).json()
+ assert page["items"][0]["plan_id"] is None
+ assert page["items"][0]["plan_status"] == "not_persisted"
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 145f8a70f..5c4ba3300 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -6,6 +6,7 @@ import tempfile
from pathlib import Path
from httpx import AsyncClient
+from sqlalchemy import event
from repowise.core.persistence import (
batch_upsert_graph_edges,
@@ -223,6 +224,139 @@ async def test_type_filter_narrows_plans_but_keeps_summary(client: AsyncClient,
assert body["summary"]["total"] == 4
+async def test_paged_targets_are_bounded_deterministic_and_server_filtered(
+ client: AsyncClient, app
+) -> None:
+ repo_id = await _seed(client, app)
+ legacy = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()
+ first = (
+ await client.get(f"/api/repos/{repo_id}/refactoring/targets/page", params={"limit": 2})
+ ).json()
+ second = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets/page",
+ params={"limit": 2, "offset": first["next_offset"]},
+ )
+ ).json()
+
+ assert len(first["items"]) == 2
+ assert first["total"] == 4
+ assert first["has_more"] is True
+ assert [item["id"] for item in first["items"] + second["items"]] == [
+ item["id"] for item in legacy["plans"]
+ ]
+
+ filtered = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets/page",
+ params={
+ "search": "helper.do_work",
+ "confidence": "medium",
+ "effort": "S",
+ "sort": "file",
+ },
+ )
+ ).json()
+ assert filtered["total"] == 1
+ assert filtered["items"][0]["refactoring_type"] == "move_method"
+ assert filtered["summary"]["total"] == 4
+
+
+async def test_paged_targets_query_count_is_constant_as_payload_grows(
+ client: AsyncClient, app, test_engine
+) -> None:
+ repo_id = await _seed(client, app)
+
+ async def request_count(limit: int) -> int:
+ statements: list[str] = []
+
+ def record(*args) -> None:
+ statements.append(str(args[2]))
+
+ event.listen(test_engine.sync_engine, "before_cursor_execute", record)
+ try:
+ response = await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets/page", params={"limit": limit}
+ )
+ assert response.status_code == 200
+ finally:
+ event.remove(test_engine.sync_engine, "before_cursor_execute", record)
+ return len(statements)
+
+ small = await request_count(1)
+ async with app.state.session_factory() as session:
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ {
+ "refactoring_type": "extract_method",
+ "file_path": f"pkg/many_{index}.py",
+ "target_symbol": f"work_{index}",
+ "line_start": 1,
+ "line_end": 30,
+ "plan": {"suggested_name": f"part_{index}"},
+ "evidence": {"slice_nloc": 12, "ccn_removed": 2},
+ "impact_delta": 0.2,
+ "effort_bucket": "S",
+ "blast_radius": {"files": [f"pkg/many_{index}.py"], "file_count": 1},
+ "confidence": "high",
+ "source_biomarker": "high_complexity",
+ }
+ for index in range(80)
+ ],
+ )
+ await session.commit()
+
+ large = await request_count(60)
+ assert large == small
+
+
+async def test_paged_targets_filter_performance_plans_without_redefining_rank(
+ client: AsyncClient, app
+) -> None:
+ repo_id = await _seed(client, app)
+ async with app.state.session_factory() as session:
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ {
+ "refactoring_type": "performance_fix",
+ "file_path": "pkg/hub.py",
+ "target_symbol": "pkg/hub.py::load",
+ "plan": {
+ "opportunity_id": "opp-exact",
+ "strategy": "batch_or_prefetch_io",
+ "affected_locations_total": 4,
+ },
+ "evidence": {"rank_factors": {"multiplier_shape": 3, "affected_call_sites": 4}},
+ "impact_delta": 0.0,
+ "effort_bucket": "M",
+ "blast_radius": {"files": ["pkg/hub.py"], "file_count": 1},
+ "confidence": "medium",
+ "source_biomarker": "io_in_loop",
+ }
+ ],
+ )
+ await session.commit()
+
+ all_page = (await client.get(f"/api/repos/{repo_id}/refactoring/targets/page")).json()
+ performance = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets/page",
+ params={"refactoring_type": "performance_fix"},
+ )
+ ).json()
+ expected = next(
+ item for item in all_page["items"] if item["refactoring_type"] == "performance_fix"
+ )
+ assert performance["items"] == [expected]
+ assert performance["summary"]["performance_total"] == 1
+ assert expected["impact_delta"] == 0.0
+ assert expected["benefit"] > 0
+
+
async def test_file_path_filter_narrows_plans_but_keeps_summary(client: AsyncClient, app) -> None:
repo_id = await _seed(client, app)
resp = await client.get(