Skip to content

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

feat(refactoring): make the composed opportunity the unit on every surface (#1998)

Raghav Chamadiya736ae6840ea6
diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.ts
index 5ccb30035..89dfee70b 100644
--- a/packages/api-client/src/refactoring.ts
+++ b/packages/api-client/src/refactoring.ts
@@ -3,14 +3,29 @@
* Backend: packages/server/src/repowise/server/routers/refactoring.py
*/
-import { apiGet, apiPost, apiPut } from "./client";
+import { apiGet, apiPatch, apiPost, apiPut } from "./client";
import type {
GeneratedCode,
+ RefactoringOpportunityDetail,
+ RefactoringOpportunityPage,
+ RefactoringOpportunityStatusUpdate,
+ RefactoringOrder,
RefactoringPlanPage,
RefactoringPlan,
+ RefactoringPlanStatusUpdate,
+ RefactoringSummaryResponse,
RefactoringTargets,
+ RefactoringTriageStatus,
+ RefactoringView,
} from "@repowise-dev/types/refactoring";
+export type {
+ RefactoringOpportunityDetail,
+ RefactoringOpportunityPage,
+ RefactoringSummaryResponse,
+ RefactoringTriageStatus,
+};
+
export interface RefactoringSettings {
enabled: boolean;
provider: string | null;
@@ -101,3 +116,112 @@ export async function updateRefactoringSettings(
): Promise<RefactoringSettings> {
return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, settings);
}
+
+// ---------------------------------------------------------------------------
+// Composed opportunities (R4's read model). The plan endpoints above stay: a
+// plan is still addressable by id, and the drawer's per-step detail reads them.
+// ---------------------------------------------------------------------------
+
+export interface RefactoringOpportunityParams {
+ /** Lead refactoring type, not the type of any member step. */
+ refactoringType?: string;
+ /** Triage state. Defaults to `open` server-side. */
+ status?: RefactoringTriageStatus;
+ confidence?: string;
+ effort?: string;
+ /** One repo-relative path. This is how a file surface asks for its own work. */
+ filePath?: string;
+ /** Substring of the file path, for the board's search box. */
+ search?: string;
+ /** Only opportunities carrying at least one mechanical step. */
+ mechanical?: boolean;
+ view?: RefactoringView;
+ order?: RefactoringOrder;
+ /** Steps inlined per row. 0 for a list that renders counts and opens a drawer. */
+ stepPreview?: number;
+ limit?: number;
+ offset?: number;
+}
+
+export async function getRefactoringOpportunities(
+ repoId: string,
+ params: RefactoringOpportunityParams = {},
+): Promise<RefactoringOpportunityPage> {
+ return apiGet<RefactoringOpportunityPage>(
+ `/api/repos/${repoId}/refactoring/opportunities`,
+ {
+ refactoring_type: params.refactoringType,
+ status: params.status,
+ confidence: params.confidence,
+ effort: params.effort,
+ file_path: params.filePath,
+ search: params.search,
+ // Only sent when true: the server defaults it to false, and sending
+ // `false` would turn a shared default into a caller's assertion.
+ mechanical: params.mechanical ? true : undefined,
+ view: params.view,
+ order: params.order,
+ step_preview: params.stepPreview,
+ limit: params.limit,
+ offset: params.offset,
+ },
+ );
+}
+
+export async function getRefactoringOpportunity(
+ repoId: string,
+ opportunityId: string,
+ opts: {
+ stepLimit?: number;
+ stepOffset?: number;
+ evidenceLimit?: number;
+ evidenceOffset?: number;
+ } = {},
+): Promise<RefactoringOpportunityDetail> {
+ return apiGet<RefactoringOpportunityDetail>(
+ `/api/repos/${repoId}/refactoring/opportunities/${encodeURIComponent(opportunityId)}`,
+ {
+ step_limit: opts.stepLimit,
+ step_offset: opts.stepOffset,
+ evidence_limit: opts.evidenceLimit,
+ evidence_offset: opts.evidenceOffset,
+ },
+ );
+}
+
+/** The repository rollup and its one lead, by primary key. */
+export async function getRefactoringOpportunitySummary(
+ repoId: string,
+): Promise<RefactoringSummaryResponse> {
+ return apiGet<RefactoringSummaryResponse>(`/api/repos/${repoId}/refactoring/summary`);
+}
+
+/**
+ * Record a decision about one opportunity.
+ *
+ * One request, not one per step: the server applies the transition to every
+ * member plan through the same owner the plan route uses, then rolls the
+ * opportunity's own state up from them.
+ */
+export async function updateRefactoringOpportunityStatus(
+ repoId: string,
+ opportunityId: string,
+ status: RefactoringTriageStatus,
+): Promise<RefactoringOpportunityStatusUpdate> {
+ return apiPatch<RefactoringOpportunityStatusUpdate>(
+ `/api/repos/${repoId}/refactoring/opportunities/${encodeURIComponent(opportunityId)}/status`,
+ { status },
+ );
+}
+
+/** Record a decision about one plan (one step of an opportunity). */
+export async function updateRefactoringPlanStatus(
+ repoId: string,
+ suggestionId: string,
+ status: RefactoringTriageStatus,
+): Promise<RefactoringPlanStatusUpdate> {
+ return apiPatch<RefactoringPlanStatusUpdate>(
+ `/api/repos/${repoId}/refactoring/${encodeURIComponent(suggestionId)}/status`,
+ { status },
+ );
+}
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index 9c09c6b5c..c5b20dd84 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
@@ -15,6 +15,7 @@ import click
from rich.table import Table
from repowise.cli.helpers import console
+from repowise.core.analysis.health.models import primary_finding
def _effort_bucket(nloc: int) -> tuple[str, int]:
@@ -66,7 +67,7 @@ def _render_refactoring_targets(
m = metric_by_path.get(path)
nloc = m.nloc if m is not None else 0
score = m.score if m is not None else 10.0
- primary = max(fs, key=lambda x: x.health_impact)
+ primary = primary_finding(fs)
total_impact = round(sum(x.health_impact for x in fs), 3)
bucket, weight = _effort_bucket(nloc)
file_sugg = sugg_by_file.get(path, [])
@@ -104,8 +105,31 @@ def _render_refactoring_targets(
else:
ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]
+ # The composed unit. One opportunity per file, ranked, with its plans as
+ # ordered steps - the same vocabulary the board, the drawer and the agent
+ # contract speak. The type-grouped dump this replaced made type the
+ # organizing principle, so a file needing a split and two extractions
+ # appeared three times in three sections.
+ opportunities, _leads = _compose(findings, suggestions)
+ plan_by_id = _plans_by_public_id(suggestions, ranked_plans)
+ claimed = {s.plan_id for o in opportunities for s in o.steps} | {
+ e.plan_id for o in opportunities for e in o.evidence
+ }
+ unattached = [row for pid, row in plan_by_id.items() if pid not in claimed]
+
if fmt == "json":
- click.echo(json.dumps({"targets": targets, "refactoring_plans": ranked_plans}, indent=2))
+ click.echo(
+ json.dumps(
+ {
+ "targets": targets,
+ "refactoring_opportunities": [
+ _opportunity_row(o) for o in opportunities
+ ],
+ "refactoring_plans": ranked_plans,
+ },
+ indent=2,
+ )
+ )
return
if fmt == "md":
click.echo("# Refactoring targets\n")
@@ -115,12 +139,8 @@ def _render_refactoring_targets(
f"score {t['score']:.1f}/10, -{t['total_impact']:.2f}) "
f"— {t['primary_biomarker']}: {t['primary_reason']}"
)
- _render_extract_class_plans_md(ranked_plans)
- _render_extract_helper_plans_md(ranked_plans)
- _render_extract_method_plans_md(ranked_plans)
- _render_move_method_plans_md(ranked_plans)
- _render_break_cycle_plans_md(ranked_plans)
- _render_split_file_plans_md(ranked_plans)
+ _render_opportunities_md(opportunities, plan_by_id)
+ _render_unattached_md(unattached)
return
table = Table(title=f"Refactoring targets ({len(targets)})")
@@ -140,260 +160,362 @@ def _render_refactoring_targets(
t["primary_biomarker"],
)
console.print(table)
- _render_extract_class_plans_console(ranked_plans)
- _render_extract_helper_plans_console(ranked_plans)
- _render_extract_method_plans_console(ranked_plans)
- _render_move_method_plans_console(ranked_plans)
- _render_break_cycle_plans_console(ranked_plans)
- _render_split_file_plans_console(ranked_plans)
-
-
-def _render_extract_class_plans_console(plans: list[dict]) -> None:
- """Print the concrete Extract Class splits below the table — the wedge."""
- ec_plans = [p for p in plans if p["refactoring_type"] == "extract_class"]
- if not ec_plans:
- return
- console.print(f"\n[bold]Extract Class plans ({len(ec_plans)})[/bold]")
- for p in ec_plans:
- ev = p["evidence"]
- groups = p["plan"].get("groups", [])
- console.print(
- f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim] — "
- f"LCOM4={ev.get('lcom4')}, {ev.get('method_count')} methods, "
- f"WMC={ev.get('wmc')} → split into {len(groups)} classes "
- f"[dim](recover ~{p['impact_delta']:.2f}, effort {p['effort_bucket']}, "
- f"{p['confidence']} confidence)[/dim]"
- )
- for i, g in enumerate(groups, 1):
- fields = ", ".join(g["fields"]) or "—"
- console.print(
- f" [bold]{i}.[/bold] methods: {', '.join(g['methods'])}\n"
- f" [dim]fields:[/dim] {fields}"
- )
+ _render_opportunities_console(opportunities, plan_by_id)
+ _render_unattached_console(unattached)
-def _render_extract_class_plans_md(plans: list[dict]) -> None:
- ec_plans = [p for p in plans if p["refactoring_type"] == "extract_class"]
- if not ec_plans:
- return
- click.echo("\n## Extract Class plans\n")
- for p in ec_plans:
- groups = p["plan"].get("groups", [])
- click.echo(
- f"- **{p['target_symbol']}** ({p['file_path']}) — "
- f"LCOM4={p['evidence'].get('lcom4')}, split into {len(groups)} classes:"
- )
- for i, g in enumerate(groups, 1):
- fields = ", ".join(g["fields"]) or "—"
- click.echo(f" {i}. methods: {', '.join(g['methods'])} · fields: {fields}")
+def _compose(findings: list, suggestions: list) -> tuple[list, dict]:
+ """Fold the detector rows into ranked per-file opportunities.
+ The same pure function the analyzer and the server both call, so the CLI
+ cannot drift into a third answer about what the work is or how it ranks.
+ Returns the opportunities and a lookup from plan id to the serialized plan,
+ so a step can render its own type-specific detail.
+ """
+ from repowise.core.analysis.health.models import primary_biomarker_by_file
+ from repowise.core.analysis.health.refactoring.opportunity import compose_opportunities
-def _render_extract_helper_plans_console(plans: list[dict]) -> None:
- """Print the concrete Extract Helper (clone dedup) plans below the table."""
- eh_plans = [p for p in plans if p["refactoring_type"] == "extract_helper"]
- if not eh_plans:
- return
- console.print(f"\n[bold]Extract Helper plans ({len(eh_plans)})[/bold]")
- for p in eh_plans:
- ev = p["evidence"]
- occ = p["plan"].get("occurrences", [])
- site = p["plan"].get("suggested_site", {}) or {}
- # ``directory`` first: it is the only namespace new plans carry, and on
- # plans stored before that it was the correct one anyway (``module`` held
- # a community label naming a directory the occurrences were not in).
- where = site.get("directory") or site.get("module") or "a shared module"
- co = ev.get("co_change_count", 0)
- console.print(
- f"\n[cyan]{ev.get('duplicated_lines')} duplicated lines[/cyan] across "
- f"{len(occ)} sites → extract a helper near [bold]{where}[/bold] "
- f"[dim](recover ~{p['impact_delta']:.2f}, effort {p['effort_bucket']}, "
- f"{p['confidence']} confidence" + (f", co-changed {co}x" if co else "") + ")[/dim]"
- )
- for o in occ:
- console.print(f" [dim]-[/dim] {o['file']}:{o['line_start']}-{o['line_end']}")
+ leads = primary_biomarker_by_file(findings) if findings else {}
+ opportunities = compose_opportunities(suggestions, primary_biomarker_by_file=leads)
+ return opportunities, leads
-def _render_extract_helper_plans_md(plans: list[dict]) -> None:
- eh_plans = [p for p in plans if p["refactoring_type"] == "extract_helper"]
- if not eh_plans:
- return
- click.echo("\n## Extract Helper plans\n")
- for p in eh_plans:
- ev = p["evidence"]
- occ = p["plan"].get("occurrences", [])
- site = p["plan"].get("suggested_site", {}) or {}
- # ``directory`` first: it is the only namespace new plans carry, and on
- # plans stored before that it was the correct one anyway (``module`` held
- # a community label naming a directory the occurrences were not in).
- where = site.get("directory") or site.get("module") or "a shared module"
- click.echo(
- f"- **{ev.get('duplicated_lines')} duplicated lines** across "
- f"{len(occ)} sites — extract a helper near `{where}`:"
+def _plans_by_public_id(suggestions: list, ranked_plans: list[dict]) -> dict[str, dict]:
+ """Serialized plans keyed by the id composition uses for a step.
+
+ Composition stamps public ids over the same suggestion list, in the same
+ order, so zipping the two is exact. Keyed rather than positional because
+ ``serialize_recommendations`` returns rank order, and pairing by position
+ against the input is how a step ends up rendering another plan's detail.
+ """
+ from repowise.core.analysis.health.refactoring.identity import assign_public_ids
+ from repowise.core.analysis.health.refactoring.recommendations import rehydrate_suggestion
+
+ hydrated = [rehydrate_suggestion(row) for row in suggestions]
+ ids = assign_public_ids(hydrated)
+ by_key: dict[tuple, str] = {}
+ for suggestion, public_id in zip(hydrated, ids, strict=True):
+ by_key[(suggestion.refactoring_type, suggestion.file_path, suggestion.target_symbol)] = (
+ public_id
)
- for o in occ:
- click.echo(f" - {o['file']}:{o['line_start']}-{o['line_end']}")
+ out: dict[str, dict] = {}
+ for plan in ranked_plans:
+ key = (plan["refactoring_type"], plan["file_path"], plan["target_symbol"])
+ public_id = by_key.get(key)
+ if public_id:
+ out[public_id] = plan
+ return out
+
+
+def _opportunity_row(o) -> dict:
+ """The wire shape, matching the server's queue row field for field."""
+ return {
+ "opportunity_id": o.opportunity_id,
+ "file_path": o.file_path,
+ "lead_biomarker": o.lead_biomarker,
+ "lead_refactoring_type": o.lead_refactoring_type,
+ "addresses_primary_problem": o.addresses_primary_problem,
+ "effort_bucket": o.effort_bucket,
+ "confidence": o.confidence,
+ "step_count": len(o.steps),
+ "mechanical_steps": sum(
+ 1 for s in o.steps if s.applicability.classification == "mechanical"
+ ),
+ "recoverable_health": round(float(o.recoverable_health), 3),
+ "rank_score": round(float(o.rank_score), 4),
+ "steps": [
+ {
+ "plan_id": s.plan_id,
+ "refactoring_type": s.refactoring_type,
+ "target_symbol": s.target_symbol,
+ "file_path": s.file_path,
+ "line_start": s.line_start,
+ "line_end": s.line_end,
+ "classification": s.applicability.classification,
+ "reasons": list(s.applicability.reasons),
+ "unknowns": list(s.applicability.unknowns),
+ "relocated_by": s.relocated_by,
+ }
+ for s in o.steps
+ ],
+ "evidence": [
+ {
+ "plan_id": e.plan_id,
+ "refactoring_type": e.refactoring_type,
+ "target_symbol": e.target_symbol,
+ }
+ for e in o.evidence
+ ],
+ }
+
+def _primary_word(value) -> str:
+ """Tri-state, and the unknown case says so rather than reading as a no."""
+ if value is True:
+ return "addresses the file's main problem"
+ if value is False:
+ return "does not address the file's main problem"
+ return "no dominant problem recorded"
-def _render_extract_method_plans_console(plans: list[dict]) -> None:
- """Print the concrete Extract Method (long-function split) plans below the table."""
- em_plans = [p for p in plans if p["refactoring_type"] == "extract_method"]
- if not em_plans:
+
+def _render_opportunities_console(opportunities: list, plan_by_id: dict) -> None:
+ if not opportunities:
return
- console.print(f"\n[bold]Extract Method plans ({len(em_plans)})[/bold]")
- for p in em_plans:
- pl = p["plan"]
- ev = p["evidence"]
- span = pl.get("span", {}) or {}
- params = ", ".join(pl.get("params", [])) or "—"
- returns = ", ".join(pl.get("returns", [])) or "none"
+ console.print(f"\n[bold]Refactoring opportunities ({len(opportunities)})[/bold]")
+ console.print(
+ "[dim]One per file, in rank order. Steps are in dependency-safe order.[/dim]"
+ )
+ for rank, o in enumerate(opportunities, 1):
+ mech = sum(1 for s in o.steps if s.applicability.classification == "mechanical")
console.print(
- f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim] — "
- f"extract lines {span.get('start')}-{span.get('end')} "
- f"[dim]({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN, "
- f"recover ~{p['impact_delta']:.2f}, effort {p['effort_bucket']}, "
- f"{p['confidence']} confidence)[/dim]"
+ f"\n[bold]{rank}.[/bold] [cyan]{o.file_path}[/cyan] [dim]-[/dim] "
+ f"{len(o.steps)} step(s), {mech} mechanical "
+ f"[dim](effort {o.effort_bucket}, {o.confidence} confidence, "
+ f"recover ~{o.recoverable_health:.2f}, "
+ f"{_primary_word(o.addresses_primary_problem)})[/dim]"
)
- console.print(f" [dim]params (in):[/dim] {params} [dim]returns (out):[/dim] {returns}")
+ for i, s in enumerate(o.steps, 1):
+ mark = "mechanical" if s.applicability.classification == "mechanical" else "judgment"
+ span = f":{s.line_start}-{s.line_end}" if s.line_start else ""
+ console.print(
+ f" [bold]{i}.[/bold] {s.refactoring_type} [green]{s.target_symbol}[/green] "
+ f"[dim]{s.file_path}{span}[/dim] [dim]({mark})[/dim]"
+ )
+ if s.relocated_by:
+ # The step's own path and span describe where the symbol was.
+ console.print(
+ " [yellow]moved by an earlier step - locate it again "
+ "before applying[/yellow]"
+ )
+ for line in _plan_detail_console(plan_by_id.get(s.plan_id, {})):
+ console.print(line)
+ if s.applicability.unknowns:
+ console.print(
+ f" [dim]not established: {', '.join(s.applicability.unknowns)}[/dim]"
+ )
+ for e in o.evidence:
+ console.print(
+ f" [dim]evidence:[/dim] {e.refactoring_type} {e.target_symbol} "
+ "[dim](an observation, not a step)[/dim]"
+ )
-def _render_extract_method_plans_md(plans: list[dict]) -> None:
- em_plans = [p for p in plans if p["refactoring_type"] == "extract_method"]
- if not em_plans:
+def _render_opportunities_md(opportunities: list, plan_by_id: dict) -> None:
+ if not opportunities:
return
- click.echo("\n## Extract Method plans\n")
- for p in em_plans:
- pl = p["plan"]
- ev = p["evidence"]
- span = pl.get("span", {}) or {}
- params = ", ".join(pl.get("params", [])) or "—"
- returns = ", ".join(pl.get("returns", [])) or "none"
+ click.echo("\n## Refactoring opportunities\n")
+ click.echo("One per file, in rank order. Steps are in dependency-safe order.\n")
+ for rank, o in enumerate(opportunities, 1):
+ mech = sum(1 for s in o.steps if s.applicability.classification == "mechanical")
click.echo(
- f"- **{p['target_symbol']}** ({p['file_path']}) — extract lines "
- f"{span.get('start')}-{span.get('end')} ({ev.get('slice_nloc')} lines, "
- f"-{ev.get('ccn_removed')} CCN) · in: {params} · out: {returns}"
+ f"{rank}. **{o.file_path}** - {len(o.steps)} step(s), {mech} mechanical "
+ f"(effort {o.effort_bucket}, {o.confidence} confidence, "
+ f"recover ~{o.recoverable_health:.2f}, "
+ f"{_primary_word(o.addresses_primary_problem)})"
)
+ for i, s in enumerate(o.steps, 1):
+ mark = "mechanical" if s.applicability.classification == "mechanical" else "judgment"
+ span = f":{s.line_start}-{s.line_end}" if s.line_start else ""
+ click.echo(
+ f" {i}. {s.refactoring_type} **{s.target_symbol}** "
+ f"({s.file_path}{span}) - {mark}"
+ )
+ if s.relocated_by:
+ click.echo(
+ " - moved by an earlier step; locate it again before applying"
+ )
+ for line in _plan_detail_md(plan_by_id.get(s.plan_id, {})):
+ click.echo(line)
+ if s.applicability.unknowns:
+ click.echo(f" - not established: {', '.join(s.applicability.unknowns)}")
+ for e in o.evidence:
+ click.echo(
+ f" - evidence: {e.refactoring_type} {e.target_symbol} "
+ "(an observation, not a step)"
+ )
-def _render_move_method_plans_console(plans: list[dict]) -> None:
- """Print the concrete Move Method (feature-envy) plans below the table."""
- mm_plans = [p for p in plans if p["refactoring_type"] == "move_method"]
- if not mm_plans:
+def _render_unattached_console(plans: list[dict]) -> None:
+ """Plans no opportunity claims.
+
+ A file whose only plans are demoted clones publishes no opportunity, so
+ without this the CLI would print a smaller number than the analyzer found
+ and call it the total. They are listed as observations, under their own
+ heading, rather than folded back in as work.
+ """
+ if not plans:
+ return
+ console.print(f"\n[bold]Unattached observations ({len(plans)})[/bold]")
+ console.print(
+ "[dim]Real duplication, not ranked work: no file's opportunity is built "
+ "on them.[/dim]"
+ )
+ for p in plans:
+ console.print(f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim]")
+ for line in _plan_detail_console(p):
+ console.print(line)
+
+
+def _render_unattached_md(plans: list[dict]) -> None:
+ if not plans:
return
- console.print(f"\n[bold]Move Method plans ({len(mm_plans)})[/bold]")
- for p in mm_plans:
- pl = p["plan"]
- ev = p["evidence"]
+ click.echo("\n## Unattached observations\n")
+ click.echo(
+ "Real duplication, not ranked work: no file's opportunity is built on them.\n"
+ )
+ for p in plans:
+ click.echo(f"- **{p['target_symbol']}** ({p['file_path']})")
+ for line in _plan_detail_md(p):
+ click.echo(line)
+
+
+def _plan_detail_console(p: dict) -> list[str]:
+ """The type-specific detail for one step, as console lines.
+
+ These used to be six sections, one per refactoring type, printed under the
+ table. Type was the organizing principle, so a file needing a split and two
+ extractions appeared three times in three places and the reader had to
+ reassemble it. The detail itself was the good part and is unchanged; it is
+ the grouping that went.
+ """
+ kind = p["refactoring_type"]
+ pl = p.get("plan") or {}
+ ev = p.get("evidence") or {}
+ out: list[str] = []
+
+ if kind == "extract_class":
+ groups = pl.get("groups", [])
+ out.append(
+ f" [dim]LCOM4={ev.get('lcom4')}, {ev.get('method_count')} methods, "
+ f"WMC={ev.get('wmc')} -> split into {len(groups)} classes[/dim]"
+ )
+ for i, g in enumerate(groups, 1):
+ fields = ", ".join(g["fields"]) or "-"
+ out.append(f" {i}. methods: {', '.join(g['methods'])} [dim]fields:[/dim] {fields}")
+ elif kind == "extract_helper":
+ occ = pl.get("occurrences", [])
+ co = ev.get("co_change_count", 0)
+ out.append(
+ f" [dim]{ev.get('duplicated_lines')} duplicated lines across {len(occ)} sites, "
+ f"extract near [/dim][bold]{_helper_site(pl)}[/bold]"
+ + (f" [dim](co-changed {co}x)[/dim]" if co else "")
+ )
+ for o in occ:
+ out.append(f" [dim]-[/dim] {o['file']}:{o['line_start']}-{o['line_end']}")
+ elif kind == "extract_method":
+ span = pl.get("span", {}) or {}
+ params = ", ".join(pl.get("params", [])) or "-"
+ returns = ", ".join(pl.get("returns", [])) or "none"
+ out.append(
+ f" [dim]extract lines {span.get('start')}-{span.get('end')} "
+ f"({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN)[/dim]"
+ )
+ out.append(f" [dim]in:[/dim] {params} [dim]out:[/dim] {returns}")
+ elif kind == "move_method":
to_file = pl.get("to_file")
dest = f"{pl.get('to_class')}" + (f" [dim]({to_file})[/dim]" if to_file else "")
- console.print(
- f"\n[cyan]{pl.get('from_class')}.{pl.get('method')}[/cyan] "
- f"[dim]({p['file_path']})[/dim] → move to [bold]{dest}[/bold] "
+ out.append(
+ f" [dim]move to[/dim] [bold]{dest}[/bold] "
f"[dim](uses {ev.get('foreign_calls')} of its members vs "
- f"{ev.get('own_calls')} of its own, effort {p['effort_bucket']}, "
- f"{p['confidence']} confidence)[/dim]"
- )
-
-
-def _render_move_method_plans_md(plans: list[dict]) -> None:
- mm_plans = [p for p in plans if p["refactoring_type"] == "move_method"]
- if not mm_plans:
- return
- click.echo("\n## Move Method plans\n")
- for p in mm_plans:
- pl = p["plan"]
- ev = p["evidence"]
- dest = pl.get("to_class")
- if pl.get("to_file"):
- dest = f"{dest} ({pl['to_file']})"
- click.echo(
- f"- **{pl.get('from_class')}.{pl.get('method')}** ({p['file_path']}) "
- f"— move to `{dest}` "
- f"(uses {ev.get('foreign_calls')} vs {ev.get('own_calls')} own members)"
+ f"{ev.get('own_calls')} of its own)[/dim]"
)
-
-
-def _render_break_cycle_plans_console(plans: list[dict]) -> None:
- """Print the concrete Break Cycle (import-cycle cut) plans below the table."""
- bc_plans = [p for p in plans if p["refactoring_type"] == "break_cycle"]
- if not bc_plans:
- return
- console.print(f"\n[bold]Break Cycle plans ({len(bc_plans)})[/bold]")
- for p in bc_plans:
- pl = p["plan"]
- ev = p["evidence"]
+ elif kind == "break_cycle":
cuts = pl.get("cut_edges", [])
- console.print(
- f"\n[cyan]Import cycle of {ev.get('cycle_size')} files[/cyan] "
- f"[dim]({ev.get('edge_count')} edges)[/dim] → cut "
- f"{len(cuts)} edge(s) "
- f"[dim](effort {p['effort_bucket']}, {p['confidence']} confidence)[/dim]"
+ out.append(
+ f" [dim]import cycle of {ev.get('cycle_size')} files "
+ f"({ev.get('edge_count')} edges), cut {len(cuts)} edge(s)[/dim]"
)
for e in cuts:
- console.print(f" [dim]-[/dim] invert {e['from']} → {e['to']}")
- for f in pl.get("cycle", []):
- console.print(f" [dim]·[/dim] {f}")
-
-
-def _render_break_cycle_plans_md(plans: list[dict]) -> None:
- bc_plans = [p for p in plans if p["refactoring_type"] == "break_cycle"]
- if not bc_plans:
- return
- click.echo("\n## Break Cycle plans\n")
- for p in bc_plans:
- pl = p["plan"]
- ev = p["evidence"]
- cuts = pl.get("cut_edges", [])
- click.echo(f"- **Import cycle of {ev.get('cycle_size')} files** — cut {len(cuts)} edge(s):")
- for e in cuts:
- click.echo(f" - invert {e['from']} -> {e['to']}")
-
-
-def _render_split_file_plans_console(plans: list[dict]) -> None:
- """Print the concrete Split File (module decomposition) plans below the table."""
- sf_plans = [p for p in plans if p["refactoring_type"] == "split_file"]
- if not sf_plans:
- return
- console.print(f"\n[bold]Split File plans ({len(sf_plans)})[/bold]")
- for p in sf_plans:
- pl = p["plan"]
- ev = p["evidence"]
+ out.append(f" [dim]-[/dim] invert {e['from']} -> {e['to']}")
+ elif kind == "split_file":
groups = pl.get("groups", [])
- br = p["blast_radius"]
- shim = " [dim]+shim[/dim]" if pl.get("shim_required") else ""
- console.print(
- f"\n[cyan]{p['file_path']}[/cyan] — "
- f"{ev.get('symbol_count')} symbols, {ev.get('file_nloc')} NLOC, "
- f"modularity {ev.get('modularity')} → split into {len(groups)} files{shim} "
- f"[dim](effort {p['effort_bucket']}, {p['confidence']} confidence, "
- f"{br.get('import_rewrites', 0)} import rewrites in "
+ br = p.get("blast_radius") or {}
+ shim = " +shim" if pl.get("shim_required") else ""
+ out.append(
+ f" [dim]{ev.get('symbol_count')} symbols, {ev.get('file_nloc')} NLOC, "
+ f"modularity {ev.get('modularity')} -> split into {len(groups)} files{shim} "
+ f"({br.get('import_rewrites', 0)} import rewrites in "
f"{br.get('dependent_count', 0)} files)[/dim]"
)
for i, g in enumerate(groups, 1):
- console.print(
- f" [bold]{i}.[/bold] [green]{g.get('suggested_file') or '(unnamed)'}[/green]: "
+ out.append(
+ f" {i}. [green]{g.get('suggested_file') or '(unnamed)'}[/green]: "
f"{', '.join(g.get('symbols', []))}"
)
residual = pl.get("residual")
if residual and residual.get("symbols"):
- console.print(f" [dim]core (shared):[/dim] {', '.join(residual['symbols'])}")
+ out.append(f" [dim]core (shared):[/dim] {', '.join(residual['symbols'])}")
+ return out
-def _render_split_file_plans_md(plans: list[dict]) -> None:
- sf_plans = [p for p in plans if p["refactoring_type"] == "split_file"]
- if not sf_plans:
- return
- click.echo("\n## Split File plans\n")
- for p in sf_plans:
- pl = p["plan"]
- ev = p["evidence"]
+def _plan_detail_md(p: dict) -> list[str]:
+ """The same detail, as Markdown lines."""
+ kind = p["refactoring_type"]
+ pl = p.get("plan") or {}
+ ev = p.get("evidence") or {}
+ out: list[str] = []
+
+ if kind == "extract_class":
groups = pl.get("groups", [])
- click.echo(
- f"- **{p['file_path']}** — {ev.get('symbol_count')} symbols, "
- f"modularity {ev.get('modularity')}, split into {len(groups)} files:"
+ out.append(
+ f" - LCOM4={ev.get('lcom4')}, split into {len(groups)} classes:"
+ )
+ for i, g in enumerate(groups, 1):
+ fields = ", ".join(g["fields"]) or "-"
+ out.append(f" {i}. methods: {', '.join(g['methods'])} · fields: {fields}")
+ elif kind == "extract_helper":
+ occ = pl.get("occurrences", [])
+ out.append(
+ f" - {ev.get('duplicated_lines')} duplicated lines across {len(occ)} sites, "
+ f"extract a helper near `{_helper_site(pl)}`:"
+ )
+ for o in occ:
+ out.append(f" - {o['file']}:{o['line_start']}-{o['line_end']}")
+ elif kind == "extract_method":
+ span = pl.get("span", {}) or {}
+ params = ", ".join(pl.get("params", [])) or "-"
+ returns = ", ".join(pl.get("returns", [])) or "none"
+ out.append(
+ f" - extract lines {span.get('start')}-{span.get('end')} "
+ f"({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN) · "
+ f"in: {params} · out: {returns}"
+ )
+ elif kind == "move_method":
+ dest = pl.get("to_class")
+ if pl.get("to_file"):
+ dest = f"{dest} ({pl['to_file']})"
+ out.append(
+ f" - move to `{dest}` "
+ f"(uses {ev.get('foreign_calls')} vs {ev.get('own_calls')} own members)"
+ )
+ elif kind == "break_cycle":
+ cuts = pl.get("cut_edges", [])
+ out.append(f" - import cycle of {ev.get('cycle_size')} files, cut {len(cuts)} edge(s):")
+ for e in cuts:
+ out.append(f" - invert {e['from']} -> {e['to']}")
+ elif kind == "split_file":
+ groups = pl.get("groups", [])
+ out.append(
+ f" - {ev.get('symbol_count')} symbols, modularity {ev.get('modularity')}, "
+ f"split into {len(groups)} files:"
)
for i, g in enumerate(groups, 1):
name = g.get("suggested_file") or "(unnamed)"
- click.echo(f" {i}. `{name}`: {', '.join(g.get('symbols', []))}")
+ out.append(f" {i}. `{name}`: {', '.join(g.get('symbols', []))}")
residual = pl.get("residual")
if residual and residual.get("symbols"):
- click.echo(f" - core (shared): {', '.join(residual['symbols'])}")
+ out.append(f" - core (shared): {', '.join(residual['symbols'])}")
+ return out
+
+
+def _helper_site(pl: dict) -> str:
+ """Where a shared helper should live.
+
+ ``directory`` first: it is the only namespace new plans carry, and on plans
+ stored before that it was the correct one anyway - ``module`` held a
+ community label naming a directory the occurrences were not in on 905 of 905
+ measured rows, so rendering it told people to put a shared helper in a
+ package two thirds of its callers are not in.
+ """
+ site = pl.get("suggested_site", {}) or {}
+ return site.get("directory") or site.get("module") or "a shared module"
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index dfe5ed855..dd588420a 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -52,10 +52,11 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:
Extracted because the rule was written out four times - the MCP file leads,
the REST work queue, the code-health serializers and the CLI table - and
- only the MCP copy remembered the continuous exclusion. The MCP copy and the
- refactoring composition layer read this one; the other three still hold
- their own, and adopting it would change what they lead with, which is a
- surface decision rather than a refactor. See the plan's Backlog.
+ only the MCP copy remembered the continuous exclusion. All four read this
+ one now. Adopting it did change what three of them lead with, which is why
+ it was a surface decision rather than a refactor: on the dogfood index 134
+ of 3,011 files moved, and every one of them had been led by
+ ``coverage_gradient``.
"""
from .biomarkers.registry import continuous_biomarkers
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
index aa5a5fa1b..4fcc1c9f8 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py
@@ -441,8 +441,26 @@ def opportunity_status(
Resolved only when every step is; one step a person marked a false positive
does not resolve the work the others still describe. An unknown plan id
reads as ``open``, because a step nobody has triaged is outstanding.
+
+ ``false_positive`` needs every step to be one. It is reported separately
+ from ``resolved`` because the two are different claims - the work was done
+ against the work was never real - and a surface offering the four triage
+ states has to be able to read back the state a person chose.
+ """
+ return roll_up_status(plan_status.get(step.plan_id, "open") for step in opportunity.steps)
+
+
+def roll_up_status(step_states: Iterable[str]) -> str:
+ """The rollup rule itself, over the member states alone.
+
+ Split out so the transition writer, which holds stored rows rather than
+ composed objects, applies the same rule instead of restating it.
"""
- states = {plan_status.get(step.plan_id, "open") for step in opportunity.steps}
+ states = set(step_states)
+ if not states:
+ return "open"
+ if states == {"false_positive"}:
+ return "false_positive"
if states <= {"resolved", "false_positive"}:
return "resolved"
if states <= {"acknowledged", "resolved", "false_positive"}:
@@ -461,4 +479,5 @@ __all__ = [
"opportunity_kernel",
"opportunity_public_id",
"opportunity_status",
+ "roll_up_status",
]
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index e80924db0..7cc4b4549 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -82,6 +82,7 @@ from .refactoring_opportunities import (
get_refactoring_summary,
list_refactoring_opportunities,
refactoring_facet_counts,
+ update_refactoring_opportunity_status,
)
__all__ = [
@@ -141,6 +142,7 @@ __all__ = [
"tests_covering_files",
"update_dead_code_status",
"update_health_finding_status",
+ "update_refactoring_opportunity_status",
"update_refactoring_suggestion_status",
"upsert_health_findings",
"upsert_health_metrics",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index 514cc7898..42aa2b799 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -29,6 +29,7 @@ from ...models import (
_new_uuid,
_now_utc,
)
+from ...sql import LIKE_ESCAPE, escape_like
if TYPE_CHECKING:
from ....analysis.health.refactoring.opportunity import (
@@ -41,6 +42,11 @@ _PERF_TYPE = "performance_fix"
# ``false_positive`` are the two that stop describing work.
_LIVE_PLAN_STATUSES = frozenset({"open", "acknowledged"})
+# Terminal states a person chose. An opportunity in one of these is not composed
+# again, so the reconciler must not read its absence as "the work disappeared"
+# and restate the decision as its own.
+_DECIDED_STATUSES = frozenset({"resolved", "false_positive"})
+
# Orders the queue can be read in. Every one ends in a unique column so the
# total order is deterministic and a deep offset cannot repeat or skip a row.
_ORDERS: dict[str, tuple[Any, ...]] = {
@@ -122,6 +128,7 @@ def _details_payload(
*,
validations: dict[str, dict[str, Any]],
finding_ids: dict[str, list[str]],
+ figures: dict[str, int] | None = None,
) -> dict[str, Any]:
"""Everything explanatory, kept out of the indexed columns.
@@ -154,6 +161,9 @@ def _details_payload(
"rank_factors": dict(opportunity.rank_factors),
"why_ranked": [dict(item) for item in opportunity.why_ranked],
"validation_profiles": list(profiles.values()),
+ # Absent rather than zero on a store written before this existed: a
+ # zero here would plot a 1,400-line file at the origin.
+ **(figures or {}),
**(
{"lead_finding_ids": finding_ids.get(opportunity.lead_biomarker or "", [])}
if finding_ids
@@ -305,6 +315,7 @@ async def finalize_refactoring_opportunities(
step_plan_ids = {step.plan_id for item in opportunities for step in item.steps}
step_rows = [row for row in live_plans if row.public_id in step_plan_ids]
validations: dict[str, dict[str, Any]] = {}
+ file_figures: dict[str, dict[str, int]] = {}
if step_rows:
# Keyed by the storage id ``rehydrate_suggestion`` carries through, never
# by position: ``hydrate_recommendations`` returns its results in rank
@@ -317,6 +328,16 @@ async def finalize_refactoring_opportunities(
public_id = public_by_storage.get(
getattr(recommendation.suggestion, "id", None)
)
+ # The file's size and reach, which hydration has already computed
+ # here and which nothing else on the read path can answer cheaply.
+ # Recorded per file so the structural field can plot one mark per
+ # opportunity without joining back to the unbounded plan list.
+ path = getattr(recommendation.suggestion, "file_path", None)
+ if path and path not in file_figures:
+ file_figures[path] = {
+ "file_nloc": int(recommendation.file_nloc or 0),
+ "dependents": int(recommendation.dependents or 0),
+ }
# Through ``as_dict`` rather than the attribute: ``validation`` is a
# dataclass, and the serialized form is the one every surface shows.
validation = recommendation.as_dict().get("validation")
@@ -335,6 +356,7 @@ async def finalize_refactoring_opportunities(
item,
validations=validations,
finding_ids=finding_ids.get(item.file_path, {}),
+ figures=file_figures.get(item.file_path),
)
for item in opportunities
}
@@ -433,7 +455,11 @@ async def _reconcile_opportunities(
setattr(row, name, value)
row.updated_at = now
for key, row in stored.items():
- if key not in seen and row.status != "resolved":
+ # A person's decision stands. Both terminal states mean "nobody will
+ # compose this again", so an uncomposed row is expected in either case -
+ # but they are different claims, and auto-resolving a dismissal would
+ # quietly restate "this was never real" as "this got done".
+ if key not in seen and row.status not in _DECIDED_STATUSES:
row.status = "resolved"
row.updated_at = now
await session.flush()
@@ -474,10 +500,11 @@ def _opportunity_filters(
repository_id: str,
*,
status: str,
- lead_type: str | None,
+ lead_types: list[str] | None,
confidence: str | None,
effort: str | None,
file_paths: list[str] | None,
+ path_contains: str | None,
mechanical_only: bool,
addresses_primary: bool | None,
) -> list[Any]:
@@ -485,14 +512,31 @@ def _opportunity_filters(
RefactoringOpportunity.repository_id == repository_id,
RefactoringOpportunity.status == status,
]
- if lead_type is not None:
- predicates.append(RefactoringOpportunity.lead_refactoring_type == lead_type)
+ if lead_types:
+ # One value is still one equality; a list is how the board's
+ # "Structural" tab asks for its four types without four round trips.
+ predicates.append(
+ RefactoringOpportunity.lead_refactoring_type == lead_types[0]
+ if len(lead_types) == 1
+ else RefactoringOpportunity.lead_refactoring_type.in_(lead_types)
+ )
if confidence is not None:
predicates.append(RefactoringOpportunity.confidence == confidence)
if effort is not None:
predicates.append(RefactoringOpportunity.effort_bucket == effort)
if file_paths is not None:
predicates.append(RefactoringOpportunity.file_path.in_(file_paths))
+ if path_contains:
+ # A residual filter over the open set, not an index seek: the board's
+ # search box is the one caller, and it is bounded by open row count
+ # rather than by page. Escaping goes through the shared helper so a
+ # path fragment is read as a path fragment here the same way it is
+ # everywhere else that builds a LIKE.
+ predicates.append(
+ RefactoringOpportunity.file_path.ilike(
+ f"%{escape_like(path_contains)}%", escape=LIKE_ESCAPE
+ )
+ )
if mechanical_only:
predicates.append(RefactoringOpportunity.mechanical_steps > 0)
if addresses_primary is not None:
@@ -507,10 +551,11 @@ async def list_refactoring_opportunities(
repository_id: str,
*,
status: str = "open",
- lead_type: str | None = None,
+ lead_types: list[str] | None = None,
confidence: str | None = None,
effort: str | None = None,
file_paths: list[str] | None = None,
+ path_contains: str | None = None,
mechanical_only: bool = False,
addresses_primary: bool | None = None,
order: str = DEFAULT_ORDER,
@@ -521,10 +566,11 @@ async def list_refactoring_opportunities(
predicates = _opportunity_filters(
repository_id,
status=status,
- lead_type=lead_type,
+ lead_types=lead_types,
confidence=confidence,
effort=effort,
file_paths=file_paths,
+ path_contains=path_contains,
mechanical_only=mechanical_only,
addresses_primary=addresses_primary,
)
@@ -562,6 +608,80 @@ async def get_refactoring_opportunity(
return result.scalar_one_or_none()
+async def update_refactoring_opportunity_status(
+ session: AsyncSession,
+ repository_id: str,
+ opportunity_id: str,
+ status: str,
+ *,
+ reason: str = "user",
+) -> tuple[RefactoringOpportunity, int] | None:
+ """Transition one opportunity by transitioning the steps it is made of.
+
+ An opportunity has no lifecycle of its own: its state is the rollup of its
+ member plans, and those already have one transition owner. So this applies
+ that owner to each member and then re-reads the rollup, rather than writing
+ a second, divergent decision onto the summary row.
+
+ The stored ``status`` column is refreshed here too, because it is what every
+ indexed read filters on - leaving it for the next index would hide a
+ dismissed opportunity from nothing at all. Returns ``None`` for an unknown
+ id, and raises ``ValueError`` for a status outside the triage vocabulary.
+ """
+ from ....analysis.health.refactoring.opportunity import roll_up_status
+ from .refactoring import ALLOWED_STATUSES, update_refactoring_suggestion_status
+
+ if status not in ALLOWED_STATUSES:
+ raise ValueError(f"unknown refactoring status: {status}")
+ row = await get_refactoring_opportunity(session, repository_id, opportunity_id)
+ if row is None:
+ return None
+
+ # Stored as a JSON string, like every other ``*_json`` column.
+ raw = row.details_json
+ details: dict[str, Any] = {}
+ if isinstance(raw, str) and raw:
+ try:
+ loaded = json.loads(raw)
+ except ValueError:
+ loaded = None
+ if isinstance(loaded, dict):
+ details = loaded
+ elif isinstance(raw, dict):
+ details = raw
+ plan_ids = [
+ step.get("plan_id")
+ for step in details.get("steps", [])
+ if isinstance(step, dict) and step.get("plan_id")
+ ]
+ states: list[str] = []
+ updated = 0
+ for plan_id in plan_ids:
+ plan = await update_refactoring_suggestion_status(
+ session, repository_id, str(plan_id), status, reason=reason
+ )
+ # A step whose plan no longer resolves is not silently counted as
+ # transitioned; it reads as open, which is what an untriaged step is.
+ states.append(plan.status if plan is not None else "open")
+ if plan is not None:
+ updated += 1
+
+ # Nothing was written, so there is no decision to roll up, and the row is
+ # left exactly as it was. This branch matters because the rollup of an empty
+ # set is ``open``: without it, a row whose steps are missing or whose plan
+ # ids no longer resolve would answer a request to dismiss it with a cheerful
+ # "open" and an HTTP 200, and the one thing the caller asked for would be
+ # the one thing that did not happen. The caller reads ``steps_updated`` to
+ # tell this apart from success.
+ if not updated:
+ return row, 0
+
+ row.status = roll_up_status(states)
+ row.updated_at = _now_utc()
+ await session.flush()
+ return row, updated
+
+
async def get_refactoring_summary(
session: AsyncSession, repository_id: str
) -> RefactoringSummary | None:
@@ -609,4 +729,5 @@ __all__ = [
"get_refactoring_summary",
"list_refactoring_opportunities",
"refactoring_facet_counts",
+ "update_refactoring_opportunity_status",
]
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index f952867b4..4f336ba9e 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -11,6 +11,7 @@ from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.models import primary_finding
from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
@@ -100,7 +101,7 @@ async def health_work_queue(
m = metric_by_path.get(file_path)
nloc = m.nloc if m is not None else 0
score = m.score if m is not None else 10.0
- primary = max(fs, key=lambda x: x.health_impact)
+ primary = primary_finding(fs)
total_impact = round(sum(x.health_impact for x in fs), 3)
effort_bucket = _effort_for_nloc(nloc)
if effort_rank[effort_bucket] > max_effort_rank:
diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.py
index 20b7ea5dc..96a0b7645 100644
--- a/packages/server/src/repowise/server/routers/code_health/serializers.py
+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from typing import Any
+from repowise.core.analysis.health.models import primary_finding
from repowise.core.analysis.health.signals import FileSignals
from repowise.core.analysis.health.trends import FileTrend
@@ -54,7 +55,7 @@ def _primary_and_magnitude(findings: list[Any]) -> dict:
"""
if not findings:
return {"primary_biomarker": None, "primary_reason": None, "total_deduction": None}
- primary = max(findings, key=lambda x: x.health_impact)
+ primary = primary_finding(findings)
total = sum(float(x.health_impact or 0.0) for x in findings)
return {
"primary_biomarker": primary.biomarker_type,
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 293792603..1697c95d3 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -395,31 +395,54 @@ def _service(session: AsyncSession, repo_id: str) -> RefactoringHealthService:
@router.get("/{repo_id}/refactoring/opportunities")
async def get_refactoring_opportunities(
repo_id: str,
- refactoring_type: str | None = Query(None, description="Filter by lead refactoring type"),
+ refactoring_type: str | None = Query(
+ None, description="Lead refactoring type, or several comma-separated"
+ ),
+ status: str = Query(
+ "open", description="open | acknowledged | resolved | false_positive"
+ ),
confidence: str | None = Query(None, description="low | medium | high"),
effort: str | None = Query(None, description="S | M | L | XL"),
file_path: str | None = Query(None, description="One repo-relative file path"),
+ search: str | None = Query(None, description="Substring of the file path"),
mechanical: bool = Query(False, description="Only opportunities with a mechanical step"),
view: str = Query(DEFAULT_VIEW, description=" | ".join(CANONICAL_VIEWS)),
order: str | None = Query(None, description=" | ".join(CANONICAL_ORDERS)),
+ step_preview: int = Query(
+ _STEPS_PER_ROW,
+ ge=0,
+ le=20,
+ description="Steps inlined per row. 0 for a list that renders counts only.",
+ ),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
- """One page of composed opportunities, with facets and the rollup."""
+ """One page of composed opportunities, with facets and the rollup.
+
+ ``step_preview`` defaults to three, which is what an agent reading the queue
+ wants. A product list that renders the step *counts* and opens a drawer for
+ the rest asks for zero: the steps are most of the row's bytes and none of
+ its pixels.
+ """
query, ignored = parse_query(
lead_type=refactoring_type,
+ status=status,
confidence=confidence,
effort=effort,
mechanical=mechanical,
file_paths=[file_path] if file_path else None,
+ search=search,
view=view,
order=order,
limit=limit,
offset=offset,
)
page = await _service(session, repo_id).page(
- query, steps_per_item=_STEPS_PER_ROW, with_facets=True, with_summary=True
+ query,
+ steps_per_item=step_preview if step_preview > 0 else None,
+ with_facets=True,
+ with_summary=True,
)
body: dict[str, Any] = {
"items": page.items,
@@ -468,6 +491,55 @@ async def get_refactoring_opportunity_detail(
return detail
+class RefactoringOpportunityStatusUpdate(BaseModel):
+ """The finding-triage vocabulary, applied to a whole opportunity."""
+
+ status: str = Field(..., description="open | acknowledged | resolved | false_positive")
+
+
[email protected]("/{repo_id}/refactoring/opportunities/{opportunity_id}/status")
+async def update_refactoring_opportunity_state(
+ repo_id: str,
+ opportunity_id: str,
+ payload: RefactoringOpportunityStatusUpdate,
+ session: AsyncSession = Depends(get_db_session),
+) -> dict:
+ """Record a decision about one opportunity, and so about all of its steps.
+
+ One request rather than one per step: the transition is applied to every
+ member plan through the same owner the plan route uses, and the
+ opportunity's own state is the rollup of what those plans then say.
+ """
+ if payload.status not in ALLOWED_STATUSES:
+ raise HTTPException(status_code=400, detail=f"invalid status: {payload.status}")
+ result = await crud.update_refactoring_opportunity_status(
+ session, repo_id, opportunity_id, payload.status
+ )
+ if result is None:
+ raise HTTPException(
+ status_code=404, detail=f"refactoring opportunity not found: {opportunity_id}"
+ )
+ row, updated = result
+ if not updated:
+ # The opportunity exists but none of its steps could be written, so
+ # nothing was decided. Saying 200 here would report the caller's own
+ # request back to them as the stored state.
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"refactoring opportunity {opportunity_id} has no resolvable steps to "
+ "transition; re-index the repository and try again"
+ ),
+ )
+ await session.commit()
+ return {
+ "opportunity_id": row.opportunity_id,
+ "status": row.status,
+ "steps_updated": updated,
+ "status_changed_at": row.updated_at.isoformat() if row.updated_at else None,
+ }
+
+
@router.get("/{repo_id}/refactoring/settings", response_model=RefactoringSettings)
async def get_refactoring_settings(
repo_id: str,
diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.py
index 32473c9ad..51741e9cc 100644
--- a/packages/server/src/repowise/server/services/refactoring_health.py
+++ b/packages/server/src/repowise/server/services/refactoring_health.py
@@ -16,6 +16,7 @@ module reads what the finalizer wrote.
from __future__ import annotations
import json
+from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Any, Literal
@@ -52,6 +53,9 @@ DEFAULT_VIEW = "diversified"
# default resolves to the value that list has always defaulted to.
_PLAN_VIEWS = {"canonical": "canonical", "file_spread": "file_spread", "diversified": "canonical"}
+# The triage vocabulary, shared with health findings.
+_STATUSES = ("open", "acknowledged", "resolved", "false_positive")
+
CANONICAL_ORDERS = ("queue", "rank", "health", "effort", "file")
_CONFIDENCES = ("low", "medium", "high")
_EFFORTS = ("S", "M", "L", "XL")
@@ -75,12 +79,14 @@ _UNAVAILABLE = {
class RefactoringQuery:
"""A normalized queue request. The only shape either adapter passes down."""
- lead_type: str | None = None
+ lead_types: tuple[str, ...] | None = None
+ status: str = "open"
confidence: str | None = None
effort: str | None = None
mechanical_only: bool = False
addresses_primary: bool | None = None
file_paths: tuple[str, ...] | None = None
+ path_contains: str | None = None
view: str = DEFAULT_VIEW
order: str | None = None
limit: int = 20
@@ -107,12 +113,14 @@ class RefactoringPage:
def parse_query(
*,
- lead_type: str | None = None,
+ lead_type: str | Sequence[str] | None = None,
+ status: str | None = None,
confidence: str | None = None,
effort: str | None = None,
mechanical: bool | None = None,
addresses_primary: bool | None = None,
file_paths: list[str] | tuple[str, ...] | None = None,
+ search: str | None = None,
view: str | None = None,
order: str | None = None,
limit: int = 20,
@@ -134,18 +142,37 @@ def parse_query(
ignored[name] = value
return None
+ def admit_many(
+ name: str, value: str | Sequence[str] | None, allowed: tuple[str, ...]
+ ) -> tuple[str, ...] | None:
+ """One value or several. A comma-separated string is how a query
+ parameter carries a set; every member is admitted on its own, so a
+ misspelling in a list is reported rather than narrowing the result to
+ the members that happened to be spelled right."""
+ if value is None:
+ return None
+ raw = value.split(",") if isinstance(value, str) else list(value)
+ kept = [item.strip() for item in raw if item.strip()]
+ good = tuple(item for item in kept if item in allowed)
+ bad = [item for item in kept if item not in allowed]
+ if bad:
+ ignored[name] = ",".join(bad)
+ return good or None
+
resolved_view = view or DEFAULT_VIEW
if resolved_view not in _VIEW_ORDERS:
ignored["refactoring_view"] = resolved_view
resolved_view = DEFAULT_VIEW
return (
RefactoringQuery(
- lead_type=admit("refactoring_type", lead_type, _TYPES),
+ lead_types=admit_many("refactoring_type", lead_type, _TYPES),
+ status=admit("status", status, _STATUSES) or "open",
confidence=admit("confidence", confidence, _CONFIDENCES),
effort=admit("effort", effort, _EFFORTS),
mechanical_only=bool(mechanical),
addresses_primary=addresses_primary,
file_paths=tuple(file_paths) if file_paths else None,
+ path_contains=(search or "").strip() or None,
view=resolved_view,
order=admit("order", order, CANONICAL_ORDERS),
limit=max(int(limit), 0),
@@ -208,10 +235,12 @@ class RefactoringHealthService:
rows, total = await list_refactoring_opportunities(
self._session,
self._repository_id,
- lead_type=query.lead_type,
+ status=query.status,
+ lead_types=list(query.lead_types) if query.lead_types else None,
confidence=query.confidence,
effort=query.effort,
file_paths=list(query.file_paths) if query.file_paths else None,
+ path_contains=query.path_contains,
mechanical_only=query.mechanical_only,
addresses_primary=query.addresses_primary,
order=query.resolved_order,
@@ -229,7 +258,12 @@ class RefactoringHealthService:
offset=query.offset,
next_offset=next_offset if next_offset < total else None,
facets=(
- await refactoring_facet_counts(self._session, self._repository_id)
+ # Scoped to the status being listed. Facets counting the open
+ # set while the list shows the resolved one would put a badge on
+ # a tab that returns nothing.
+ await refactoring_facet_counts(
+ self._session, self._repository_id, status=query.status
+ )
if with_facets
else {}
),
@@ -551,6 +585,12 @@ class RefactoringHealthService:
"rank_factors": details.get("rank_factors") or {},
"why_ranked": details.get("why_ranked") or [],
}
+ # The file's own size and reach, recorded by the finalizer. Omitted when
+ # the store predates them, so a surface can tell "not measured" from a
+ # genuine zero rather than plotting an unmeasured file at the origin.
+ for key in ("file_nloc", "dependents"):
+ if isinstance(details.get(key), int):
+ payload[key] = details[key]
if steps_limit is not None:
kept = steps[: max(steps_limit, 0)]
payload["steps"] = kept
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 912bfdc1a..982525224 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -170,7 +170,38 @@ export interface OpportunityEvidence {
summary: Record<string, unknown>;
}
-export type OpportunityStatus = "open" | "acknowledged" | "resolved";
+/**
+ * The triage vocabulary, shared with health findings so Code Health has one
+ * triage system. An opportunity's state is rolled up from its member steps;
+ * ``false_positive`` is reached only when every step is one, so a single wrong
+ * step never dismisses the work the others still describe.
+ */
+export type OpportunityStatus =
+ | "open"
+ | "acknowledged"
+ | "resolved"
+ | "false_positive";
+
+/** The state a person can ask for. Same vocabulary, named for the write side. */
+export type RefactoringTriageStatus = OpportunityStatus;
+
+/** ``PATCH .../refactoring/opportunities/{id}/status``. */
+export interface RefactoringOpportunityStatusUpdate {
+ opportunity_id: string;
+ status: OpportunityStatus;
+ /** The member plans the transition was applied to. */
+ steps_updated: number;
+ status_changed_at: string | null;
+}
+
+/** ``PATCH .../refactoring/{id}/status``, one step. */
+export interface RefactoringPlanStatusUpdate {
+ id: string;
+ public_id: string | null;
+ status: OpportunityStatus;
+ status_reason: string | null;
+ status_changed_at: string | null;
+}
export interface RefactoringOpportunity {
/** ``refop<model>_<digest>`` over the member plan ids. */
@@ -200,6 +231,10 @@ export interface RefactoringOpportunity {
queue_position: number;
rank_factors: Record<string, number>;
why_ranked: Array<{ factor: string; value: number }>;
+ /** Lines in the lead file. Absent when the store predates the figure. */
+ file_nloc?: number;
+ /** Files importing the lead file. Absent when the store predates the figure. */
+ dependents?: number;
steps?: OpportunityStep[];
steps_total?: number;
steps_emitted?: number;
@@ -261,6 +296,13 @@ export interface RefactoringOpportunityDetailResolved extends RefactoringOpportu
/** Named orderings for the queue. ``diversified`` is the default. */
export type RefactoringView = "diversified" | "canonical" | "file_spread";
+/**
+ * Named orderings. ``queue`` is the diversified default; ``rank`` is the honest
+ * tied order; ``health`` is the explicit worst-files-first view. All are indexed
+ * columns, so none costs a sort.
+ */
+export type RefactoringOrder = "queue" | "rank" | "health" | "effort" | "file";
+
/** No stored analysis: the counts genuinely do not exist, so none are present. */
export interface RefactoringRollupUnavailable {
status: "unavailable";
diff --git a/packages/ui/__tests__/refactoring/opportunity-lifecycle.test.tsx b/packages/ui/__tests__/refactoring/opportunity-lifecycle.test.tsx
new file mode 100644
index 000000000..a916e6b1f
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/opportunity-lifecycle.test.tsx
@@ -0,0 +1,146 @@
+/**
+ * The board row as an opportunity, and its triage control.
+ *
+ * A row used to be a detector output, so a file with fifteen of them filled the
+ * screen fifteen times and carried no lifecycle at all. These pin the row's
+ * facts, the four triage states, and the two states that are easy to get wrong:
+ * an optimistic click that the server rejects, and `addresses_primary_problem`
+ * being tri-state rather than a boolean.
+ */
+
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+
+import { OpportunityRows } from "../../src/refactoring/opportunity-rows";
+import {
+ addressesPrimaryShort,
+ stepSummary,
+} from "../../src/refactoring/opportunity";
+
+function opportunity(
+ overrides: Partial<RefactoringOpportunity> = {},
+): RefactoringOpportunity {
+ return {
+ opportunity_id: "refop2_row",
+ refactoring_model_version: 2,
+ status: "open",
+ file_path: "packages/core/src/big.py",
+ lead_biomarker: "nested_complexity",
+ lead_refactoring_type: "split_file",
+ addresses_primary_problem: true,
+ effort_bucket: "M",
+ confidence: "high",
+ step_count: 3,
+ mechanical_steps: 2,
+ judgment_steps: 1,
+ evidence_total: 4,
+ affected_files_total: 2,
+ recoverable_health: 1.4,
+ rank_score: 1.45,
+ rank_position: 1,
+ queue_position: 1,
+ rank_factors: {},
+ why_ranked: [],
+ ...overrides,
+ };
+}
+
+describe("OpportunityRows", () => {
+ it("leads with the file and says how much work it is", () => {
+ render(<OpportunityRows opportunities={[opportunity()]} onOpen={() => {}} />);
+ expect(screen.getByText("big.py")).toBeTruthy();
+ expect(screen.getByText("packages/core/src/big.py")).toBeTruthy();
+ expect(screen.getByText("3 steps, 2 mechanical")).toBeTruthy();
+ // The lead cause, in words, not a token.
+ expect(screen.getByText(/Split File, against nested complexity/)).toBeTruthy();
+ });
+
+ it("keeps addresses_primary_problem in three states", () => {
+ expect(addressesPrimaryShort(true)).toBe("Main problem");
+ expect(addressesPrimaryShort(false)).toBe("Side problem");
+ // `null` is "no dominant problem was recorded", which is not "no".
+ expect(addressesPrimaryShort(null)).toBe("Lead unknown");
+ expect(addressesPrimaryShort(undefined)).toBe("Lead unknown");
+ });
+
+ it("says all-mechanical and all-judgment rather than a bare count", () => {
+ expect(stepSummary(opportunity({ step_count: 1, mechanical_steps: 0, judgment_steps: 1 })))
+ .toBe("1 step, all judgment");
+ expect(stepSummary(opportunity({ step_count: 2, mechanical_steps: 2, judgment_steps: 0 })))
+ .toBe("2 steps, all mechanical");
+ });
+
+ it("offers the four triage states and reports the chosen one", async () => {
+ const onStatusChange = vi.fn().mockResolvedValue(undefined);
+ render(
+ <OpportunityRows
+ opportunities={[opportunity()]}
+ onOpen={() => {}}
+ onStatusChange={onStatusChange}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /More actions/ }));
+ for (const label of ["Open", "Acknowledged", "Resolved", "False positive"]) {
+ expect(screen.getByRole("menuitemradio", { name: label })).toBeTruthy();
+ }
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Acknowledged" }));
+ expect(onStatusChange).toHaveBeenCalledWith(
+ expect.objectContaining({ opportunity_id: "refop2_row" }),
+ "acknowledged",
+ );
+ });
+
+ it("shows the new state immediately and rolls it back when the server refuses", async () => {
+ const onStatusChange = vi.fn().mockRejectedValue(new Error("nope"));
+ render(
+ <OpportunityRows
+ opportunities={[opportunity()]}
+ onOpen={() => {}}
+ onStatusChange={onStatusChange}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /More actions/ }));
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "Resolved" }));
+
+ // The optimistic label must not survive a rejected write, and the failure
+ // has to be visible rather than leaving a state the server never accepted
+ // looking committed.
+ await waitFor(() => expect(screen.getByRole("status")).toBeTruthy());
+ expect(screen.getByText("Could not save")).toBeTruthy();
+ expect(screen.queryByText("Resolved")).toBeNull();
+ });
+
+ it("marks a triaged row without relying on colour alone", () => {
+ render(
+ <OpportunityRows
+ opportunities={[opportunity({ status: "false_positive" })]}
+ onOpen={() => {}}
+ />,
+ );
+ expect(screen.getByText("False positive")).toBeTruthy();
+ });
+
+ it("states the status on every row, including an untouched one", () => {
+ // It used to appear only once a row left `open`, so the list had no column
+ // to scan for what had already been dealt with, and marking a row changed
+ // its height. An always-present value is quieter, not louder: `open` is
+ // rendered in the tertiary ink and only a decision takes the accent.
+ render(<OpportunityRows opportunities={[opportunity()]} onOpen={() => {}} />);
+ expect(screen.getByText("Open")).toBeTruthy();
+ });
+
+ it("labels its columns, because six unlabelled values is a jumble", () => {
+ render(<OpportunityRows opportunities={[opportunity()]} onOpen={() => {}} />);
+ for (const heading of ["Type", "File", "Work", "Health", "Status"]) {
+ expect(screen.getByText(heading)).toBeTruthy();
+ }
+ });
+
+ it("hides the triage group entirely when the host cannot write", async () => {
+ render(<OpportunityRows opportunities={[opportunity()]} onOpen={() => {}} onAiPrompt={() => {}} />);
+ fireEvent.click(screen.getByRole("button", { name: /More actions/ }));
+ expect(screen.queryByRole("menuitemradio")).toBeNull();
+ expect(screen.getByRole("menuitem", { name: /Copy prompt/ })).toBeTruthy();
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
new file mode 100644
index 000000000..ef458bb7f
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
@@ -0,0 +1,245 @@
+/**
+ * What the pasted refactoring prompt has to carry.
+ *
+ * The plan-level prompt it sits beside embeds the steps and nothing that
+ * identifies the record, so an agent could execute it and had no way to ask for
+ * it, report against it, or notice it had gone stale. These pin the four things
+ * that were missing: the id, the call that resolves the id, the evidence, and
+ * the mechanical/judgment split — plus the ordering hazard, which is the one
+ * that makes a correct-looking step edit the wrong file.
+ */
+
+import { describe, expect, it } from "vitest";
+import type {
+ RefactoringOpportunityDetailResolved,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
+
+import { buildRefactoringOpportunityPrompt } from "../../src/health/ai-prompt-builder";
+
+function plan(overrides: Partial<RefactoringPlan> = {}): RefactoringPlan {
+ return {
+ id: "refac2_split",
+ refactoring_type: "split_file",
+ file_path: "src/big.py",
+ target_symbol: "big.py",
+ line_start: 1,
+ line_end: 900,
+ plan: {
+ groups: [{ suggested_file: "big_io.py", symbols: ["read", "write"] }],
+ shim_required: true,
+ },
+ evidence: { symbol_count: 40, file_nloc: 900, modularity: 0.61 },
+ impact_delta: 1.2,
+ effort_bucket: "L",
+ blast_radius: { files: ["src/other.py"], file_count: 1 },
+ confidence: "high",
+ source_biomarker: "long_file",
+ rank_score: 1.45,
+ ...overrides,
+ };
+}
+
+function detail(
+ overrides: Partial<RefactoringOpportunityDetailResolved> = {},
+): RefactoringOpportunityDetailResolved {
+ return {
+ resolved: true,
+ opportunity_id: "refop2_abc123",
+ refactoring_model_version: 2,
+ status: "open",
+ file_path: "src/big.py",
+ lead_biomarker: "long_file",
+ lead_refactoring_type: "split_file",
+ addresses_primary_problem: true,
+ effort_bucket: "L",
+ confidence: "high",
+ step_count: 2,
+ mechanical_steps: 1,
+ judgment_steps: 1,
+ evidence_total: 1,
+ affected_files_total: 2,
+ recoverable_health: 1.4,
+ rank_score: 1.45,
+ rank_position: 1,
+ queue_position: 1,
+ rank_factors: {},
+ why_ranked: [],
+ steps: [
+ {
+ plan_id: "refac2_split",
+ refactoring_type: "split_file",
+ target_symbol: "big.py",
+ file_path: "src/big.py",
+ line_start: 1,
+ line_end: 900,
+ effort_bucket: "L",
+ confidence: "high",
+ impact_delta: 1.2,
+ source_biomarker: "long_file",
+ relocated_by: null,
+ applicability: {
+ classification: "judgment",
+ reasons: ["changes_symbol_home"],
+ facts: {},
+ unknowns: ["framework_registration"],
+ },
+ },
+ {
+ plan_id: "refac2_extract",
+ refactoring_type: "extract_method",
+ target_symbol: "big.py::render",
+ file_path: "src/big.py",
+ line_start: 400,
+ line_end: 460,
+ effort_bucket: "S",
+ confidence: "high",
+ impact_delta: 0.4,
+ source_biomarker: "complex_method",
+ relocated_by: "refac2_split",
+ applicability: {
+ classification: "mechanical",
+ reasons: ["dataflow_proved_extraction"],
+ facts: {},
+ unknowns: [],
+ },
+ },
+ ],
+ steps_total: 2,
+ steps_emitted: 2,
+ evidence: [
+ {
+ plan_id: "refac2_clone",
+ refactoring_type: "extract_helper",
+ target_symbol: "big.py:10-25",
+ source_biomarker: "dry_violation",
+ summary: { duplicated_lines: 16, occurrence_count: 2 },
+ },
+ ],
+ evidence_emitted: 1,
+ evidence_truncated: false,
+ affected_files: ["src/big.py", "src/other.py"],
+ validation_profiles: [
+ {
+ id: "validation_1",
+ basis: "measured",
+ via: "coverage",
+ total: 3,
+ tests: ["tests/test_big.py"],
+ truncated: false,
+ affected_files: ["src/big.py"],
+ affected_symbols: [],
+ commands: ["pytest tests/test_big.py"],
+ targets: [],
+ },
+ ],
+ plans: [plan()],
+ next_actions: [],
+ ordering_note: "Step 2 is relocated by step 1.",
+ ...overrides,
+ };
+}
+
+describe("buildRefactoringOpportunityPrompt", () => {
+ it("carries the opportunity id so the work can be reported back", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toContain("refop2_abc123");
+ // And in the completion contract, not only as a header fact.
+ expect(text).toMatch(/opportunity id `refop2_abc123`/);
+ });
+
+ it("names the call that resolves the id, but only for a flavor that can make it", () => {
+ const mcp = buildRefactoringOpportunityPrompt({
+ opportunity: detail(),
+ flavor: "claude-code-mcp",
+ });
+ expect(mcp).toContain('get_health(opportunity_id="refop2_abc123")');
+
+ // An id with no tool that accepts it is noise; the non-MCP flavors say so
+ // rather than naming a call they cannot invoke.
+ for (const flavor of ["generic", "claude-code", "cursor"] as const) {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail(), flavor });
+ expect(text).toContain("refop2_abc123");
+ expect(text).not.toContain("get_health(opportunity_id=");
+ expect(text).toMatch(/no tool here that resolves it/i);
+ }
+ });
+
+ it("marks every step mechanical or judgment, with its reason", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toMatch(/Judgment — changes symbol home/);
+ expect(text).toMatch(/Mechanical — dataflow proved extraction/);
+ // An unknown is first-class: it must not read as a check that passed.
+ expect(text).toMatch(/Not established: framework registration/);
+ });
+
+ it("warns that a relocated step's own coordinates go stale", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toContain("Locate it again first");
+ expect(text).toContain("refac2_split");
+ expect(text).toMatch(/where it was, not where it will be/);
+ });
+
+ it("does not warn about ordering when no step is relocated", () => {
+ const steps = detail().steps.map((s) => ({ ...s, relocated_by: null }));
+ // Omitted, not set to undefined: the wire type is exact-optional, and the
+ // server omits the key rather than emitting a null when nothing relocates.
+ const { ordering_note: _omitted, ...rest } = detail();
+ const text = buildRefactoringOpportunityPrompt({
+ opportunity: { ...rest, steps },
+ });
+ expect(text).not.toContain("Locate it again first");
+ });
+
+ it("renders the evidence as observation, never as work", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toContain("## Evidence behind the diagnosis");
+ expect(text).toMatch(/Supporting observations, not extra work/);
+ expect(text).toContain("Extract Helper");
+ });
+
+ it("preserves all three states of addresses_primary_problem", () => {
+ const yes = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ addresses_primary_problem: true }),
+ });
+ expect(yes).toMatch(/address the file's dominant diagnosed problem/);
+ expect(yes).not.toMatch(/do NOT address/);
+
+ const no = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ addresses_primary_problem: false }),
+ });
+ expect(no).toMatch(/do NOT address the file's dominant diagnosed problem/);
+
+ // `null` is not `false`. Reading one as the other turns "we could not tell"
+ // into an accusation about the plan.
+ const unknown = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ addresses_primary_problem: null }),
+ });
+ expect(unknown).toMatch(/No dominant problem was recorded/);
+ expect(unknown).toMatch(/not answered either way/);
+ expect(unknown).not.toMatch(/do NOT address/);
+ });
+
+ it("carries the runnable validation commands", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toContain("## Validation plan");
+ expect(text).toContain("pytest tests/test_big.py");
+ expect(text).toMatch(/3 guarding tests via coverage/);
+ });
+
+ it("names the validation gap rather than staying silent about it", () => {
+ const profiles = [
+ { ...detail().validation_profiles[0]!, basis: "unknown" as const, total: 0, tests: [] },
+ ];
+ const text = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ validation_profiles: profiles }),
+ });
+ expect(text).toMatch(/treat this as a validation gap/);
+ });
+
+ it("tells the agent to keep the co-affected files consistent", () => {
+ const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
+ expect(text).toContain("src/other.py");
+ expect(text).not.toMatch(/Keep these co-affected files consistent:.*src\/big\.py/);
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx b/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx
index 8341e2a2e..8e9935a27 100644
--- a/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx
+++ b/packages/ui/__tests__/refactoring/phase4-plan-contract.test.tsx
@@ -1,6 +1,9 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+import type {
+ RefactoringOpportunity,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
import { PriorityExplanation } from "../../src/refactoring/priority-explanation";
import { PlanDetail } from "../../src/refactoring/plan-detail";
@@ -24,6 +27,29 @@ const base = {
rank_score: 8.25,
} satisfies RefactoringPlan;
+const opportunity: RefactoringOpportunity = {
+ opportunity_id: "refop2_board",
+ refactoring_model_version: 2,
+ status: "open",
+ file_path: "src/shared.py",
+ lead_biomarker: "long_file",
+ lead_refactoring_type: "split_file",
+ addresses_primary_problem: true,
+ effort_bucket: "M",
+ confidence: "high",
+ step_count: 2,
+ mechanical_steps: 1,
+ judgment_steps: 1,
+ evidence_total: 0,
+ affected_files_total: 1,
+ recoverable_health: 1.4,
+ rank_score: 1.452,
+ rank_position: 1,
+ queue_position: 1,
+ rank_factors: {},
+ why_ranked: [],
+};
+
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 }} />);
@@ -59,16 +85,18 @@ describe("Phase 4 structured plan contract", () => {
expect(screen.getByText(/unavailable from this older server/)).toBeTruthy();
});
- it("renders a server-filtered performance plan without re-ranking it locally", () => {
+ it("renders a server-ordered opportunity without re-ranking it locally", () => {
render(
<RefactoringBoard
- plans={[base]}
+ opportunities={[opportunity]}
showLede={false}
serverState={{
query: "",
- sort: "canonical",
- efforts: [],
- confidences: [],
+ order: "queue",
+ status: "open",
+ effort: null,
+ confidence: null,
+ mechanicalOnly: false,
total: 1,
offset: 0,
nextOffset: null,
@@ -76,9 +104,11 @@ describe("Phase 4 structured plan contract", () => {
onServerStateChange={() => {}}
/>,
);
- expect(screen.getByText("Performance")).toBeTruthy();
- expect(screen.getByText("1 plan")).toBeTruthy();
- expect(screen.getByText("src/shared.py::load")).toBeTruthy();
+ expect(screen.getByText("Split File")).toBeTruthy();
+ // The count names the status it is counting, so a filtered list cannot
+ // read as the repository total.
+ expect(screen.getByText(/1 open\s+opportunity/)).toBeTruthy();
+ expect(screen.getByText("src/shared.py")).toBeTruthy();
});
it("links the shared intervention and does not mislabel observations as paths", () => {
diff --git a/packages/ui/__tests__/refactoring/structural-field.test.tsx b/packages/ui/__tests__/refactoring/structural-field.test.tsx
new file mode 100644
index 000000000..4e829b75c
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/structural-field.test.tsx
@@ -0,0 +1,235 @@
+/**
+ * The structural field: one mark per file, four distinguishable shapes, and a
+ * hue assignment derived from the data rather than fixed per type.
+ *
+ * The field used to fill every mark with one accent at two opacities, so colour
+ * encoded nothing, and `extract_class` and `move_method` both drew a triangle,
+ * so two of the four types were indistinguishable on the only channel that
+ * carried type at all.
+ */
+
+import { render, screen } from "@testing-library/react";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+
+import {
+ isRecededType,
+ salienceFill,
+ salienceOrder,
+ structuralMarks,
+ type StructuralMark,
+} from "../../src/refactoring/opportunity";
+import { StructuralMap } from "../../src/refactoring/structural-map";
+
+function opportunity(
+ overrides: Partial<RefactoringOpportunity> = {},
+): RefactoringOpportunity {
+ return {
+ opportunity_id: `refop2_${overrides.file_path ?? "x"}`,
+ refactoring_model_version: 2,
+ status: "open",
+ file_path: "src/a.py",
+ lead_biomarker: "long_file",
+ lead_refactoring_type: "split_file",
+ addresses_primary_problem: true,
+ effort_bucket: "M",
+ confidence: "high",
+ step_count: 2,
+ mechanical_steps: 1,
+ judgment_steps: 1,
+ evidence_total: 0,
+ affected_files_total: 1,
+ recoverable_health: 1,
+ rank_score: 1,
+ rank_position: 1,
+ queue_position: 1,
+ rank_factors: {},
+ why_ranked: [],
+ file_nloc: 400,
+ dependents: 12,
+ ...overrides,
+ };
+}
+
+function mark(leadType: string, i: number): StructuralMark {
+ return {
+ opportunityId: `refop2_${leadType}_${i}`,
+ filePath: `src/${leadType}${i}.py`,
+ leadType,
+ stepCount: 1,
+ status: "open",
+ x: 5,
+ y: 100,
+ };
+}
+
+describe("structuralMarks", () => {
+ it("draws one mark per file, not one per plan", () => {
+ // The same file caught by two detectors composes to one opportunity, so it
+ // can only ever produce one mark. That is the whole point of the unit.
+ const marks = structuralMarks([
+ opportunity({ file_path: "src/a.py", opportunity_id: "refop2_a" }),
+ opportunity({ file_path: "src/b.py", opportunity_id: "refop2_b" }),
+ ]);
+ expect(marks).toHaveLength(2);
+ expect(marks.map((m) => m.filePath)).toEqual(["src/a.py", "src/b.py"]);
+ });
+
+ it("keeps only the structural lead types", () => {
+ const marks = structuralMarks([
+ opportunity({ lead_refactoring_type: "split_file", opportunity_id: "s" }),
+ opportunity({ lead_refactoring_type: "extract_method", opportunity_id: "e" }),
+ opportunity({ lead_refactoring_type: "break_cycle", opportunity_id: "b" }),
+ ]);
+ expect(marks.map((m) => m.leadType)).toEqual(["split_file", "break_cycle"]);
+ });
+
+ it("drops an opportunity with no measured figures instead of plotting the origin", () => {
+ // Absent is not zero. A store written before the finalizer recorded these
+ // has neither figure, and a 1,400-line file at (0, 0) is a lie.
+ const { file_nloc: _n, ...noLines } = opportunity();
+ const { dependents: _d, ...noReach } = opportunity();
+ expect(structuralMarks([noLines])).toHaveLength(0);
+ expect(structuralMarks([noReach])).toHaveLength(0);
+ // A file nothing imports is a measured zero, and belongs on the field.
+ expect(structuralMarks([opportunity({ dependents: 0 })])).toHaveLength(1);
+ });
+});
+
+describe("salience", () => {
+ it("derives the hue order from the data, never from a fixed per-type map", () => {
+ const splitLed = [mark("split_file", 1), mark("split_file", 2), mark("break_cycle", 1)];
+ expect(salienceOrder(splitLed).slice(0, 2)).toEqual(["split_file", "break_cycle"]);
+ // `accent-primary`, not `accent-fill`: they are the same orange in dark
+ // mode, but light deepens the former to clear the 3.0 non-text floor on
+ // warm paper (2.12:1 against 4.58:1, measured).
+ expect(salienceFill("split_file", salienceOrder(splitLed))).toBe(
+ "var(--color-accent-primary)",
+ );
+
+ // A repo whose cycles outnumber its oversized files gets the opposite
+ // assignment. A hardcoded hue would paint its dominant type as the rare one.
+ const cycleLed = [mark("break_cycle", 1), mark("break_cycle", 2), mark("split_file", 1)];
+ expect(salienceOrder(cycleLed).slice(0, 2)).toEqual(["break_cycle", "split_file"]);
+ expect(salienceFill("break_cycle", salienceOrder(cycleLed))).toBe(
+ "var(--color-accent-primary)",
+ );
+ expect(salienceFill("split_file", salienceOrder(cycleLed))).toBe(
+ "var(--color-accent-secondary)",
+ );
+ });
+
+ it("spends the accent pair, then neutrals - never the sequential ramp", () => {
+ const order = ["split_file", "break_cycle", "move_method", "extract_class"];
+ const fills = order.map((t) => salienceFill(t, order));
+ expect(fills).toEqual([
+ "var(--color-accent-primary)",
+ "var(--color-accent-secondary)",
+ "var(--color-neutral-1)",
+ "var(--color-neutral-2)",
+ ]);
+ // globals.css reserves --color-ramp-* for magnitude; these are categories.
+ expect(fills.some((f) => f.includes("ramp"))).toBe(false);
+ });
+
+ it("breaks a count tie deterministically", () => {
+ const tied = [mark("break_cycle", 1), mark("split_file", 1)];
+ expect(salienceOrder(tied)).toEqual(salienceOrder([...tied].reverse()));
+ });
+
+ it("knows which types have receded past the two hues", () => {
+ const order = ["split_file", "break_cycle", "move_method"];
+ expect(isRecededType("split_file", order)).toBe(false);
+ expect(isRecededType("break_cycle", order)).toBe(false);
+ expect(isRecededType("move_method", order)).toBe(true);
+ });
+});
+
+describe("StructuralMap", () => {
+ // The field sizes itself from its container, and jsdom reports every element
+ // as zero-width, so without this it renders its axes and legend and no marks
+ // at all - which would let every assertion below pass vacuously.
+ let clientWidth: PropertyDescriptor | undefined;
+ beforeAll(() => {
+ clientWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "clientWidth");
+ Object.defineProperty(HTMLElement.prototype, "clientWidth", {
+ configurable: true,
+ get: () => 900,
+ });
+ });
+ afterAll(() => {
+ if (clientWidth) Object.defineProperty(HTMLElement.prototype, "clientWidth", clientWidth);
+ });
+
+ const fourTypes: StructuralMark[] = [
+ { ...mark("split_file", 1), x: 3, y: 100 },
+ { ...mark("break_cycle", 1), x: 9, y: 300 },
+ { ...mark("move_method", 1), x: 20, y: 500 },
+ { ...mark("extract_class", 1), x: 40, y: 700 },
+ ];
+
+ it("gives each of the four structural types its own shape", () => {
+ const { container } = render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ const svg = container.querySelector("svg");
+ // Circle (split_file) plus three distinct paths. `extract_class` and
+ // `move_method` used to share the triangle, so two types drew identically.
+ const paths = [...(svg?.querySelectorAll("path") ?? [])].map((p) => p.getAttribute("d"));
+ const unique = new Set(paths.filter(Boolean));
+ expect(unique.size).toBe(3);
+ });
+
+ it("names every mark, so type survives with no colour at all", () => {
+ render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ for (const label of ["Split File", "Break Cycle", "Move Method", "Extract Class"]) {
+ expect(screen.getAllByLabelText(new RegExp(`^${label},`)).length).toBeGreaterThan(0);
+ }
+ });
+
+ it("keeps every mark reachable by keyboard", () => {
+ render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ const marks = screen.getAllByRole("button");
+ expect(marks).toHaveLength(4);
+ for (const node of marks) expect(node.getAttribute("tabindex")).toBe("0");
+ });
+
+ it("says out loud when a type has receded into grey", () => {
+ render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ expect(screen.getByText(/Shape is the type/)).toBeTruthy();
+ expect(screen.getByText(/the rarer types sit in grey/)).toBeTruthy();
+ });
+
+ it("outlines every mark, so a receded fill is never the only thing drawing it", () => {
+ // The neutral tiers sit between 1.25:1 and 2.45:1 against the page in both
+ // themes, under the 3.0 floor for non-text UI. The stroke is what carries
+ // visibility; the fill only ranks attention.
+ const { container } = render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ const drawn = [...container.querySelectorAll("svg path, svg circle")].filter((node) =>
+ node.getAttribute("fill")?.startsWith("var("),
+ );
+ expect(drawn.length).toBeGreaterThan(0);
+ for (const node of drawn) {
+ expect(node.getAttribute("stroke")).toBe("var(--color-text-tertiary)");
+ }
+ });
+
+ it("is a group, not an image, so its marks stay in the accessibility tree", () => {
+ const { container } = render(<StructuralMap marks={fourTypes} onSelect={() => {}} />);
+ const svg = container.querySelector("svg");
+ expect(svg?.getAttribute("role")).toBe("group");
+ });
+
+ it("stays quiet about receding when only the two hues are in play", () => {
+ render(
+ <StructuralMap
+ marks={[fourTypes[0]!, fourTypes[1]!]}
+ onSelect={() => {}}
+ />,
+ );
+ expect(screen.queryByText(/Shape is the type/)).toBeNull();
+ });
+
+ it("states its own bound rather than covering part of the subject silently", () => {
+ render(<StructuralMap marks={fourTypes} dropped={7} onSelect={() => {}} />);
+ expect(screen.getByText(/7 not plotted/)).toBeTruthy();
+ });
+});
diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsx
index a082a6143..60a562e0f 100644
--- a/packages/ui/src/files/file-health-tab.tsx
+++ b/packages/ui/src/files/file-health-tab.tsx
@@ -18,10 +18,12 @@ import {
import { healthBandTextColor, type Severity } from "../health/tokens";
import { FileTrendChart } from "../health/file-trend-chart";
import { FileSignalsPanel } from "../health/file-signals-panel";
+import { FindingOpportunityLink } from "../health/file-opportunity";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { SeverityMark } from "../health/severity-mark";
import { formatNumber } from "../lib/format";
import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import { FileSection, Fig } from "./file-section";
export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";
@@ -44,6 +46,15 @@ interface FileHealthTabProps {
partnerHref?: ((path: string) => string) | undefined;
/** Build a symbol-page href for a function row. */
symbolHref?: ((symbolId: string) => string) | undefined;
+ /**
+ * The file's composed refactoring opportunity. This is the surface a reader is
+ * on once they have decided which file they care about, so it is the most
+ * natural place to hand them the plan - and it was the one with no link at
+ * all. Findings whose cause the opportunity does not address get none, so the
+ * page never offers a plan for a problem the plan does not answer.
+ */
+ opportunity?: RefactoringOpportunity | null | undefined;
+ refactoringOpportunityHref?: ((opportunityId: string) => string) | undefined;
}
/** Collapsed finding-card height guess; cards expand and are measured live. */
@@ -68,6 +79,8 @@ export function FileHealthTab({
onFindingStatusChange,
partnerHref,
symbolHref,
+ opportunity,
+ refactoringOpportunityHref,
}: FileHealthTabProps) {
const [statusOverride, setStatusOverride] = useState<Record<string, FindingStatus>>({});
const [savingId, setSavingId] = useState<string | null>(null);
@@ -256,6 +269,11 @@ export function FileHealthTab({
details={f.details as BiomarkerDetailsRecord | null}
onPartnerHref={partnerHref}
/>
+ <FindingOpportunityLink
+ opportunity={opportunity}
+ biomarkerType={f.biomarker_type}
+ href={refactoringOpportunityHref}
+ />
{onFindingStatusChange && (
// One control, four states — a segmented selector for a
// single field, not rule 14's pile of independent verbs
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 7686a5b86..c996510fa 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -14,7 +14,11 @@
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 type {
+ OpportunityStep,
+ RefactoringOpportunityDetailResolved,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
import type { HealthWorkItem } from "./refactoring-card";
@@ -27,6 +31,9 @@ import {
extractMethodPlan,
helperSite,
moveTarget,
+ splitGroups,
+ splitResidual,
+ splitShimRequired,
} from "../refactoring/types";
import { typeMeta } from "../refactoring/meta";
@@ -1542,6 +1549,33 @@ function refactoringPlanSteps(plan: RefactoringPlan): string {
"For each edge, invert the dependency or introduce an abstraction/interface so the importer no longer needs the importee at module load time. Don't just move the import inside a function unless that genuinely breaks the cycle.",
].join("\n");
}
+ case "split_file": {
+ const groups = splitGroups(plan).filter((g) => g.symbols.length > 0);
+ const residual = splitResidual(plan);
+ const shim = splitShimRequired(plan);
+ const lines = groups.map(
+ (g, i) => `- **${g.suggested_file ?? `part${i + 1}`}** — ${g.symbols.join(", ")}`,
+ );
+ return [
+ `Split \`${plan.file_path}\` into ${groups.length} file${
+ groups.length === 1 ? "" : "s"
+ } along the seams below. Move each group's symbols together:`,
+ "",
+ lines.join("\n"),
+ residual.length
+ ? `\nLeave in the original file (shared by more than one group): ${residual
+ .map((symbol) => `\`${symbol}\``)
+ .join(", ")}.`
+ : "",
+ "",
+ shim
+ ? "Other files import this module, so keep the original path importable: re-export the moved symbols from it, or update every importer. Do not break the existing import surface."
+ : "Update every importer of the moved symbols.",
+ "The suggested filenames are a starting point, not a requirement; rename them if the repo has a clearer convention.",
+ ]
+ .filter((line) => line !== "")
+ .join("\n");
+ }
default:
return "Apply the refactoring described above.";
}
@@ -1683,6 +1717,248 @@ export interface FileHealthPromptSignals {
age_days?: number | null;
}
+export interface BuildRefactoringOpportunityPromptOptions {
+ opportunity: RefactoringOpportunityDetailResolved;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+/** `- Mechanical (dataflow proved the extraction).` */
+function stepApplicabilityLine(step: OpportunityStep): string {
+ const classification =
+ step.applicability.classification === "mechanical" ? "Mechanical" : "Judgment";
+ const reasons = step.applicability.reasons.map((r) => r.replace(/_/g, " ")).join("; ");
+ const unknowns = step.applicability.unknowns.length
+ ? ` Not established: ${step.applicability.unknowns
+ .map((u) => u.replace(/_/g, " "))
+ .join(", ")}.`
+ : "";
+ return `${classification}${reasons ? ` — ${reasons}` : ""}.${unknowns}`;
+}
+
+/**
+ * The ordered steps, each one saying what kind of change it is.
+ *
+ * `relocated_by` gets its own sentence rather than a footnote. A step it marks
+ * names an earlier step that moves its symbol to another file, so its own path
+ * and span describe where the symbol *was* — an agent that follows those
+ * coordinates after applying step one lands in the wrong file, and nothing else
+ * in the payload would tell it so.
+ */
+function opportunitySteps(opportunity: RefactoringOpportunityDetailResolved): string {
+ const byId = new Map(opportunity.plans.map((plan) => [plan.id, plan]));
+ return opportunity.steps
+ .map((step, i) => {
+ const plan = byId.get(step.plan_id);
+ const meta = typeMeta(step.refactoring_type);
+ const lines: (string | null)[] = [
+ `${i + 1}. **${meta.label}** — ${planSourceLink(step.file_path, step.line_start, step.line_end)}${
+ step.target_symbol ? ` — \`${step.target_symbol}\`` : ""
+ }`,
+ ` - Step id: \`${step.plan_id}\``,
+ ` - ${stepApplicabilityLine(step)}`,
+ step.relocated_by
+ ? ` - **Locate it again first.** Step \`${step.relocated_by}\` moves this symbol to another file, so the path and lines above are where it was, not where it will be when you get here.`
+ : null,
+ plan
+ ? indentBlock(refactoringPlanSteps(plan), " ")
+ : // Not a silent gap: a step whose payload did not come back still
+ // says so rather than rendering a header with no instruction.
+ ` - The detail for this step was not in this payload. Ask for it by id: \`${step.plan_id}\`.`,
+ ];
+ return lines.filter(Boolean).join("\n");
+ })
+ .join("\n\n");
+}
+
+/** Indent a multi-line block so it reads as the body of its numbered step. */
+function indentBlock(body: string, pad: string): string {
+ return body
+ .split("\n")
+ .map((line) => (line.trim() === "" ? "" : `${pad}${line}`))
+ .join("\n");
+}
+
+/** The observations behind the diagnosis, never presented as work. */
+function opportunityEvidence(opportunity: RefactoringOpportunityDetailResolved): string {
+ if (opportunity.evidence.length === 0) return "";
+ const rows = opportunity.evidence.map((item) => {
+ const meta = typeMeta(item.refactoring_type);
+ const detail = Object.entries(item.summary)
+ .filter(([, value]) => value !== null && value !== undefined && value !== "")
+ .map(([key, value]) => `${key.replace(/_/g, " ")}: ${String(value)}`)
+ .join("; ");
+ return `- ${meta.label}${item.target_symbol ? ` \`${item.target_symbol}\`` : ""}${
+ detail ? ` — ${detail}` : ""
+ }`;
+ });
+ return [
+ "## Evidence behind the diagnosis",
+ "",
+ "Supporting observations, not extra work. They are why the diagnosis reads the way it does.",
+ "",
+ rows.join("\n"),
+ opportunity.evidence_truncated
+ ? `\n${opportunity.evidence_emitted} of ${opportunity.evidence_total} shown.`
+ : "",
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+/** The validation profiles the steps share, with their runnable commands. */
+function opportunityValidation(opportunity: RefactoringOpportunityDetailResolved): string {
+ if (opportunity.validation_profiles.length === 0) return "";
+ const blocks = opportunity.validation_profiles.map((profile) => {
+ const evidence =
+ profile.basis === "unknown"
+ ? "No measured or inferred guarding test was found; treat this as a validation gap."
+ : `${profile.total} guarding test${profile.total === 1 ? "" : "s"} via ${
+ profile.via ?? profile.basis
+ }${profile.truncated ? ` (showing ${profile.tests.length})` : ""}.`;
+ return bulletList([
+ evidence,
+ profile.tests.length
+ ? `Tests: ${profile.tests.map((test) => `\`${test}\``).join(", ")}.`
+ : null,
+ profile.commands.length
+ ? `Run: ${profile.commands.map((command) => `\`${command}\``).join("; ")}.`
+ : null,
+ ]);
+ });
+ return ["## Validation plan", "", blocks.join("\n")].join("\n");
+}
+
+/**
+ * The line that tells an MCP-capable agent it can pull this record itself.
+ *
+ * An id in a prompt with no call that resolves it is noise — the work-queue
+ * prompt prints `- Target: <id>` and nothing accepts it, which is the mistake
+ * this deliberately does not repeat. So the id is stated for every flavor,
+ * because it is how a person reports completion and how staleness is detected,
+ * but only the MCP flavor is told to call anything with it. Every other flavor
+ * gets the whole plan inlined above and is told plainly that it cannot query
+ * back, rather than being handed a tool name it has no way to invoke.
+ */
+function opportunityHandoff(
+ opportunity: RefactoringOpportunityDetailResolved,
+ flavor: AiPromptFlavor,
+): string {
+ if (flavor === "claude-code-mcp") {
+ return [
+ "## Pull this record yourself",
+ "",
+ `\`get_health(opportunity_id="${opportunity.opportunity_id}")\``,
+ "",
+ "That returns this same opportunity from the index: every ordered step with its mechanical/judgment classification and reasons, the member plans' payloads, the validation profiles with runnable commands, the evidence, and structured next actions. Call it before you start — the steps below are a snapshot, and the index is the record.",
+ ].join("\n");
+ }
+ return [
+ "## This opportunity's id",
+ "",
+ `\`${opportunity.opportunity_id}\``,
+ "",
+ "Quote it when you report back. You have no tool here that resolves it, so everything needed to execute the work is inlined above rather than left behind a call you cannot make.",
+ ].join("\n");
+}
+
+/**
+ * Build a ready-to-paste prompt that hands a coding agent ONE composed
+ * refactoring opportunity: the file, what it leads with, its ordered steps with
+ * the mechanical/judgment split, the evidence, the validation commands, and the
+ * stable id that resolves back to the record.
+ *
+ * This is the opportunity-level sibling of `buildRefactoringPlanPrompt`, which
+ * still handles a single step.
+ */
+export function buildRefactoringOpportunityPrompt({
+ opportunity,
+ flavor = "generic",
+ repoName,
+}: BuildRefactoringOpportunityPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const meta = typeMeta(opportunity.lead_refactoring_type || "");
+ const others = opportunity.affected_files.filter((f) => f !== opportunity.file_path);
+
+ // Tri-state, and all three states survive. `null` means no dominant finding
+ // was recorded to compare against, which is not the claim `false` makes.
+ const primaryLine =
+ opportunity.addresses_primary_problem === true
+ ? "These steps address the file's dominant diagnosed problem."
+ : opportunity.addresses_primary_problem === false
+ ? "These steps do NOT address the file's dominant diagnosed problem — they are real work, but not the biggest cost in this file. Say so if you think something else should come first."
+ : "No dominant problem was recorded for this file, so whether these steps address the main one is unknown — not answered either way.";
+
+ const anyRelocated = opportunity.steps.some((step) => Boolean(step.relocated_by));
+
+ const constraintList = [
+ "Preserve behavior exactly — this is a refactoring, not a feature change. No public API or observable behavior should shift.",
+ "Apply the steps in the order given. It is dependency-safe; reordering it is not.",
+ anyRelocated
+ ? "Where a step says to locate its symbol again, do that before touching it: an earlier step moves it, so the recorded path and lines go stale mid-run."
+ : null,
+ "A step marked Judgment has an unproven obligation. Read the real code and decide before applying it; do not treat it like a mechanical one.",
+ "Run the project's tests (and type-checker/linter) after the change; the suite must stay green.",
+ "If, after reading the real code, a step looks wrong or unsafe, stop and explain why instead of forcing it — the detection is static and can be a false positive.",
+ others.length > 0
+ ? `Keep these co-affected files consistent: ${others.map((f) => `\`${f}\``).join(", ")}.`
+ : null,
+ ];
+
+ const completionContract = [
+ "1. The refactored code, with each step above applied in order.",
+ "2. Per step: whether you applied it, and for anything you skipped, the reason.",
+ "3. A short note on what you renamed or introduced and why.",
+ "4. Confirmation the tests pass (or the exact failures if they don't).",
+ `5. The opportunity id \`${opportunity.opportunity_id}\`, so the work can be matched back to the record.`,
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## ${meta.label} in \`${opportunity.file_path}\`${repoLine}`,
+ "",
+ bulletList([
+ `Opportunity: \`${opportunity.opportunity_id}\``,
+ `File: \`${opportunity.file_path}\``,
+ opportunity.lead_biomarker
+ ? `Leading cause: ${opportunity.lead_biomarker.replace(/_/g, " ")}.`
+ : null,
+ `${opportunity.step_count} step${opportunity.step_count === 1 ? "" : "s"}: ${opportunity.mechanical_steps} mechanical, ${opportunity.judgment_steps} judgment.`,
+ opportunity.recoverable_health > 0
+ ? `Recovers ~${opportunity.recoverable_health.toFixed(2)} of health score if applied.`
+ : null,
+ `Effort: ${opportunity.effort_bucket} bucket. Detector confidence: ${opportunity.confidence}.`,
+ primaryLine,
+ ]),
+ "",
+ "## The steps, in order",
+ "",
+ anyRelocated
+ ? `${opportunity.ordering_note ?? "One or more steps below are moved by an earlier step; each says so on its own line."}\n`
+ : "",
+ opportunitySteps(opportunity),
+ "",
+ opportunityEvidence(opportunity),
+ "",
+ opportunityValidation(opportunity),
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ opportunityHandoff(opportunity, flavor),
+ "",
+ explorationCloser(flavor, opportunity.file_path, "refactor"),
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
export interface BuildFileHealthPromptOptions {
file: FileHealthPromptInput;
findings?: FileHealthPromptFinding[];
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index c5d632bc8..3ac682a52 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -14,7 +14,10 @@ import type {
} from "@repowise-dev/types/health";
import type { Paginated } from "@repowise-dev/types";
import type { CodeHealthOverlay } from "./map/types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+import type {
+ RefactoringOpportunity,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
/** Subset of the findings list query the shared views need. */
export interface CodeHealthFindingsQuery {
@@ -105,6 +108,13 @@ export interface CodeHealthAdapter {
symbolHref?(symbolId: string): string | undefined;
/** Exact stable-id handoff into the existing structured-plan page. */
refactoringPlanHref?(planId: string, opportunityId: string): string;
+ /**
+ * The file's one composed refactoring opportunity, or null when it has none.
+ * Optional: a host that cannot answer offers no link rather than a dead one.
+ */
+ getFileOpportunity?(filePath: string): Promise<RefactoringOpportunity | null>;
+ /** Deep link into the refactoring surface for one opportunity. */
+ refactoringOpportunityHref?(opportunityId: string): string;
/**
* Where this cause lives on the one map. Optional: a host without a galaxy
* offers no link rather than a second map.
diff --git a/packages/ui/src/health/file-opportunity.tsx b/packages/ui/src/health/file-opportunity.tsx
new file mode 100644
index 000000000..be0bf576f
--- /dev/null
+++ b/packages/ui/src/health/file-opportunity.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+/**
+ * The finding -> opportunity link, for every surface that lists a file's
+ * findings.
+ *
+ * Until now this existed once, for one biomarker family: the performance tab
+ * passed `refactoringPlanHref` and the performance queue and drawer used it.
+ * Everywhere else a reader who had just been told what is wrong with a file had
+ * no way to reach the plan the same analysis wrote for it.
+ *
+ * Three facts make the general version cheap and honest:
+ *
+ * - **A file has at most one opportunity.** Measured on the dogfood index: 581
+ * open opportunities over 581 distinct files. So this is one lookup per file
+ * surface, not one per finding, and there is no ambiguity about which record a
+ * finding points at.
+ * - **A step names the cause it answers.** The link is offered only where the
+ * opportunity's lead cause or one of its steps actually addresses that
+ * finding's biomarker. Linking every finding to the file's opportunity would
+ * tell a reader their coverage gap has a plan when the plan is to split the
+ * file.
+ * - **It is not the performance lens.** These rows carry step counts and the
+ * mechanical split, never a benefit figure or a runtime claim; performance
+ * causes keep their own link, their own semantics and their own lens gate.
+ */
+
+import * as React from "react";
+import { Wrench } from "lucide-react";
+
+import { stepSummary } from "../refactoring/opportunity";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+
+export interface FileOpportunityAdapter {
+ /** The file's one composed opportunity, or null. Steps included. */
+ getFileOpportunity?(filePath: string): Promise<RefactoringOpportunity | null>;
+ /** Deep link into the refactoring surface. Omit and nothing links. */
+ refactoringOpportunityHref?(opportunityId: string): string;
+}
+
+/**
+ * Fetch a file's opportunity once, for the whole findings list.
+ *
+ * Returns `null` for "asked, and there is none" and `undefined` for "not asked
+ * yet or this host cannot ask", so a caller never renders a "no plan" claim it
+ * has not established.
+ */
+export function useFileOpportunity(
+ adapter: FileOpportunityAdapter,
+ filePath: string | null | undefined,
+): RefactoringOpportunity | null | undefined {
+ const [value, setValue] = React.useState<RefactoringOpportunity | null | undefined>(
+ undefined,
+ );
+ const fetcher = adapter.getFileOpportunity;
+
+ React.useEffect(() => {
+ if (!fetcher || !filePath) {
+ setValue(undefined);
+ return;
+ }
+ let live = true;
+ setValue(undefined);
+ void fetcher(filePath)
+ .then((result) => {
+ if (live) setValue(result ?? null);
+ })
+ .catch(() => {
+ // A failed lookup is not "no opportunity". Staying undefined keeps the
+ // surface silent rather than asserting a clean file.
+ if (live) setValue(undefined);
+ });
+ return () => {
+ live = false;
+ };
+ }, [fetcher, filePath]);
+
+ return value;
+}
+
+/**
+ * Whether this opportunity answers this finding's cause.
+ *
+ * The lead biomarker or any step's source biomarker. A step list truncated by
+ * the server can only lose a match, never invent one, so the worst case is a
+ * link that is not offered.
+ */
+export function opportunityAddresses(
+ opportunity: RefactoringOpportunity | null | undefined,
+ biomarkerType: string,
+): boolean {
+ if (!opportunity) return false;
+ if (opportunity.lead_biomarker === biomarkerType) return true;
+ return (opportunity.steps ?? []).some((step) => step.source_biomarker === biomarkerType);
+}
+
+export interface FindingOpportunityLinkProps {
+ opportunity: RefactoringOpportunity | null | undefined;
+ biomarkerType: string;
+ href?: ((opportunityId: string) => string) | undefined;
+ /** Host navigation, for a surface that routes rather than follows an anchor. */
+ onNavigate?: ((href: string) => void) | undefined;
+}
+
+/** The link itself. Renders nothing unless there is a real, addressing plan. */
+export function FindingOpportunityLink({
+ opportunity,
+ biomarkerType,
+ href,
+ onNavigate,
+}: FindingOpportunityLinkProps) {
+ if (!opportunity || !href) return null;
+ if (!opportunityAddresses(opportunity, biomarkerType)) return null;
+ const target = href(opportunity.opportunity_id);
+ if (!target) return null;
+
+ return (
+ <a
+ href={target}
+ onClick={
+ onNavigate
+ ? (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onNavigate(target);
+ }
+ : (e) => e.stopPropagation()
+ }
+ className="inline-flex items-center gap-1.5 rounded text-[11.5px] font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <Wrench className="h-3 w-3" aria-hidden="true" />
+ Refactoring plan: {stepSummary(opportunity)}
+ </a>
+ );
+}
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index 178a20101..e33e40eff 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -117,6 +117,12 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
limit: 1000,
})) as HealthWorkItemFinding[];
+ // Undefined when this host cannot answer, so the card stays silent rather
+ // than rendering "no plan" for a question it never asked.
+ const loadOpportunity = adapter.getFileOpportunity
+ ? (filePath: string) => adapter.getFileOpportunity!(filePath)
+ : undefined;
+
// The prompt promises the agent "every marker", so hydrate before opening
// rather than letting the builder fall back to the primary finding alone.
const openPrompt = async (t: HealthWorkItem) => {
@@ -372,6 +378,8 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
onStatusChange={handleStatus}
onGeneratePrompt={(t) => void openPrompt(t)}
onLoadFindings={loadFindings}
+ onLoadOpportunity={loadOpportunity}
+ refactoringOpportunityHref={adapter.refactoringOpportunityHref}
/>
</section>
))}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 89437ef5b..f5126e106 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -20,6 +20,7 @@ import { AiPromptButton } from "./ai-prompt-button";
import { AiPromptModal } from "./ai-prompt-modal";
import { buildFileHealthAiPrompt } from "./ai-prompt-builder";
import { FileSignalsPanel } from "./file-signals-panel";
+import { FindingOpportunityLink } from "./file-opportunity";
import { CollapsibleSection } from "../shared/collapsible-section";
import { formatRelativeTimeOrNull } from "../lib/format";
import { Sparkline } from "./sparkline";
@@ -38,6 +39,7 @@ import type {
FileSignals,
PerformanceOpportunity,
} from "@repowise-dev/types/health";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import { SeverityMark } from "./severity-mark";
import { ImpactFigure } from "./impact-figure";
@@ -90,6 +92,13 @@ export interface HealthFileDrawerProps {
} | null;
findings?: HealthDrawerFinding[];
suggestions?: Record<string, string>;
+ /**
+ * The file's composed refactoring opportunity, when the host can supply one.
+ * Findings whose cause it addresses get a link to it; the rest do not, so the
+ * drawer never offers a plan for a problem the plan does not answer.
+ */
+ opportunity?: RefactoringOpportunity | null | undefined;
+ refactoringOpportunityHref?: ((opportunityId: string) => string) | undefined;
/** Per-file score trajectory; renders a compact sparkline when populated. */
trend?: FileHealthTrend | null;
/** Process / people / topology signals; the panel is silent when absent. */
@@ -143,6 +152,8 @@ export function HealthFileDrawer({
breakdown,
findings = [],
suggestions = {},
+ opportunity,
+ refactoringOpportunityHref,
trend,
signals,
fileViewHref,
@@ -257,6 +268,11 @@ export function HealthFileDrawer({
{suggestions[f.biomarker_type]}
</p>
) : null}
+ <FindingOpportunityLink
+ opportunity={opportunity}
+ biomarkerType={f.biomarker_type}
+ href={refactoringOpportunityHref}
+ />
{onFindingStatusChange ? (
<div className="flex flex-wrap items-center gap-1.5 pt-1">
{TRIAGE_STATUSES.map((opt) => {
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index f095ff7ea..34d534c3b 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -39,6 +39,7 @@ export * from "./code-health-lede";
export * from "./coverage-lede";
export * from "./severity-mark";
export * from "./code-health-adapter";
+export * from "./file-opportunity";
export * from "./triage-view";
export * from "./findings-view";
export * from "./performance-view";
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index 8247b7bf2..dfcec1045 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -7,6 +7,8 @@ import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
import { type Severity } from "./tokens";
import { ImpactFigure } from "./impact-figure";
+import { FindingOpportunityLink } from "./file-opportunity";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import { SeverityMark } from "./severity-mark";
export type EffortBucket = "S" | "M" | "L" | "XL";
@@ -52,6 +54,17 @@ export interface HealthWorkItemCardProps {
onSelect?: ((target: HealthWorkItem) => void) | undefined;
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
onGeneratePrompt?: ((target: HealthWorkItem) => void) | undefined;
+ /** This file's composed refactoring opportunity, if the host already has one. */
+ opportunity?: RefactoringOpportunity | null | undefined;
+ /**
+ * Resolve this file's opportunity on first expand, alongside the findings.
+ * Lazy for the same reason they are: a queue of hundreds of collapsed cards
+ * should not fetch a plan for every one of them.
+ */
+ onLoadOpportunity?:
+ | ((filePath: string) => Promise<RefactoringOpportunity | null>)
+ | undefined;
+ refactoringOpportunityHref?: ((opportunityId: string) => string) | undefined;
/**
* Fetch this file's findings, called on first expand. The list response
* deliberately omits them — serializing every file's findings to render a
@@ -86,6 +99,9 @@ export function HealthWorkItemCard({
onSelect,
onStatusChange,
onGeneratePrompt,
+ opportunity,
+ refactoringOpportunityHref,
+ onLoadOpportunity,
onLoadFindings,
expandable = true,
highlighted = false,
@@ -93,6 +109,10 @@ export function HealthWorkItemCard({
const [expanded, setExpanded] = useState(false);
const [loaded, setLoaded] = useState<HealthWorkItemFinding[] | null>(null);
const [loadFailed, setLoadFailed] = useState(false);
+ const [loadedOpportunity, setLoadedOpportunity] = useState<
+ RefactoringOpportunity | null | undefined
+ >(undefined);
+ const shownOpportunity = opportunity ?? loadedOpportunity;
// `finding_count` is on every target, so the expander's presence and its
// label no longer depend on shipping the findings themselves.
@@ -102,7 +122,15 @@ export function HealthWorkItemCard({
const toggle = async () => {
const next = !expanded;
setExpanded(next);
- if (!next || findings || !onLoadFindings) return;
+ if (!next) return;
+ if (onLoadOpportunity && opportunity === undefined && loadedOpportunity === undefined) {
+ // A failure here stays `undefined` rather than becoming `null`: the card
+ // must not claim a file has no plan when the lookup is what failed.
+ void onLoadOpportunity(target.file_path)
+ .then((result) => setLoadedOpportunity(result ?? null))
+ .catch(() => undefined);
+ }
+ if (findings || !onLoadFindings) return;
setLoadFailed(false);
try {
setLoaded(await onLoadFindings(target.file_path));
@@ -228,6 +256,11 @@ export function HealthWorkItemCard({
<ImpactFigure impact={f.health_impact} className="ml-auto text-xs" />
</div>
<p className="text-xs text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>
+ <FindingOpportunityLink
+ opportunity={shownOpportunity}
+ biomarkerType={f.biomarker_type}
+ href={refactoringOpportunityHref}
+ />
{onStatusChange ? (
<div className="flex flex-wrap gap-1 pt-1">
<StatusButton current={f.status} value="acknowledged" onClick={() => onStatusChange(f.id, "acknowledged")} label="Acknowledge" />
diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsx
index b37e2ab8b..5cd2d300b 100644
--- a/packages/ui/src/health/refactoring-target-list.tsx
+++ b/packages/ui/src/health/refactoring-target-list.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo, useState } from "react";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import {
HealthWorkItemCard,
type HealthWorkItem,
@@ -28,6 +29,11 @@ export interface HealthWorkQueueListProps {
onLoadFindings?:
| ((filePath: string) => Promise<HealthWorkItemFinding[]>)
| undefined;
+ /** Resolve a file's composed refactoring opportunity, on first expand. */
+ onLoadOpportunity?:
+ | ((filePath: string) => Promise<RefactoringOpportunity | null>)
+ | undefined;
+ refactoringOpportunityHref?: ((opportunityId: string) => string) | undefined;
emptyMessage?: string;
/** File path of the card to flash-highlight (quadrant click). */
highlightedPath?: string | null | undefined;
@@ -39,6 +45,8 @@ export function HealthWorkQueueList({
onStatusChange,
onGeneratePrompt,
onLoadFindings,
+ onLoadOpportunity,
+ refactoringOpportunityHref,
emptyMessage = "No health work items match the current filters.",
highlightedPath,
}: HealthWorkQueueListProps) {
@@ -83,6 +91,8 @@ export function HealthWorkQueueList({
onStatusChange={onStatusChange}
onGeneratePrompt={onGeneratePrompt}
onLoadFindings={onLoadFindings}
+ onLoadOpportunity={onLoadOpportunity}
+ refactoringOpportunityHref={refactoringOpportunityHref}
highlighted={highlightedPath === t.file_path}
/>
))}
diff --git a/packages/ui/src/refactoring/index.ts b/packages/ui/src/refactoring/index.ts
index 5887326ae..489afe211 100644
--- a/packages/ui/src/refactoring/index.ts
+++ b/packages/ui/src/refactoring/index.ts
@@ -5,10 +5,9 @@ export * from "./plan-before";
export * from "./plan-comparison";
export * from "./diff-view";
export * from "./generate-code-panel";
-export * from "./plan-rows";
-// Retired from the web surface, still mounted by the VS Code webview, which
-// has not been reworked. A use was removed here, not the component.
-export * from "./refactoring-plan-card";
+export * from "./opportunity";
+export * from "./opportunity-rows";
+export * from "./opportunity-drawer";
export * from "./structural-map";
export * from "./start-here";
export * from "./refactoring-lede";
diff --git a/packages/ui/src/refactoring/opportunity-drawer.tsx b/packages/ui/src/refactoring/opportunity-drawer.tsx
new file mode 100644
index 000000000..57c6315a2
--- /dev/null
+++ b/packages/ui/src/refactoring/opportunity-drawer.tsx
@@ -0,0 +1,518 @@
+"use client";
+
+/**
+ * The opportunity inspector, as a right-hand drawer.
+ *
+ * The single-plan drawer next door still exists and is still the right surface
+ * for one step, which is what a deep link from the performance queue and the
+ * VS Code webview both carry. This one is the composed unit: a file's whole
+ * refactoring, its steps in dependency-safe order, and the evidence they rest
+ * on.
+ *
+ * Three things it says that a list of plans could not:
+ *
+ * - **Order matters, and one kind of step invalidates the next.** A step
+ * carrying `relocated_by` names an earlier step that moves its symbol to
+ * another file, so its own file and span describe where the symbol *was*.
+ * That is stated once at the top of the list and again on each affected step,
+ * because a reader who scrolls straight to step four would otherwise follow a
+ * line number into the wrong file.
+ * - **Mechanical is not a synonym for safe-to-automate-later.** Each step says
+ * which it is and why, and names what the layer could not establish rather
+ * than leaving an unknown looking like a cleared check.
+ * - **Evidence is not instruction.** Demoted clone groups and triggering
+ * findings sit under their own heading, worded as observations.
+ */
+
+import * as React from "react";
+import { Layers, Sparkles, Terminal } from "lucide-react";
+
+import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
+import { Skeleton, SkeletonRegion } from "../ui/skeleton";
+import { formatNumber } from "../lib/format";
+import { ValidationSummary } from "./validation-summary";
+import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
+import {
+ ORDERING_NOTE,
+ STATUS_LABEL,
+ TRIAGE_STATUSES,
+ addressesPrimaryLabel,
+ humanizeBiomarker,
+ isRelocated,
+} from "./opportunity";
+import type {
+ OpportunityStatus,
+ OpportunityStep,
+ RefactoringOpportunityDetail,
+ RefactoringOpportunityDetailResolved,
+} from "@repowise-dev/types/refactoring";
+
+/** The drill-down an agent should call. Same shape the performance drawer uses,
+ * because it is the same agent surface. */
+export function opportunityHandoffCall(opportunityId: string): string {
+ return `get_health(opportunity_id="${opportunityId}")`;
+}
+
+export interface OpportunityDrawerProps {
+ detail: RefactoringOpportunityDetail | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ loading?: boolean | undefined;
+ error?: string | undefined;
+ onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;
+ onStatusChange?:
+ | ((
+ detail: RefactoringOpportunityDetailResolved,
+ status: OpportunityStatus,
+ ) => Promise<void> | void)
+ | undefined;
+ /** Open one step as a single plan, in the plan inspector. */
+ onOpenStep?: ((planId: string) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}
+
+export function OpportunityDrawer({
+ detail,
+ open,
+ onOpenChange,
+ loading = false,
+ error,
+ onAiPrompt,
+ onStatusChange,
+ onOpenStep,
+ fileHref,
+}: OpportunityDrawerProps) {
+ const resolved = detail?.resolved ? detail : null;
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ closeLabel="Close opportunity"
+ className="w-full max-w-[680px] sm:w-[92vw]"
+ >
+ {resolved ? (
+ <DrawerBody
+ detail={resolved}
+ onAiPrompt={onAiPrompt}
+ onStatusChange={onStatusChange}
+ onOpenStep={onOpenStep}
+ fileHref={fileHref}
+ />
+ ) : loading ? (
+ <>
+ <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">
+ Loading opportunity
+ </SheetTitle>
+ <SkeletonRegion className="space-y-4 px-5 py-5" label="Loading opportunity">
+ <Skeleton className="h-16 rounded-none" />
+ <Skeleton className="h-40 rounded-none" />
+ </SkeletonRegion>
+ </>
+ ) : detail && !detail.resolved ? (
+ <>
+ <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">
+ Opportunity unavailable
+ </SheetTitle>
+ <div className="space-y-2 px-5 py-5 text-sm text-[var(--color-text-secondary)]">
+ <p>
+ Nothing resolves for{" "}
+ <span className="break-all font-mono text-xs">{detail.opportunity_id}</span>.
+ </p>
+ {detail.model_state?.state === "stale_model" ? (
+ <p>
+ It was written by an older analysis model. Re-index the repository and open it
+ again from the list.
+ </p>
+ ) : (
+ <p>It may have been resolved by a later analysis, or it was never minted here.</p>
+ )}
+ </div>
+ </>
+ ) : error ? (
+ <>
+ <SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">
+ Opportunity unavailable
+ </SheetTitle>
+ <p className="px-5 py-5 text-sm text-[var(--color-text-secondary)]">{error}</p>
+ </>
+ ) : (
+ <SheetTitle className="sr-only">Refactoring opportunity</SheetTitle>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function DrawerBody({
+ detail,
+ onAiPrompt,
+ onStatusChange,
+ onOpenStep,
+ fileHref,
+}: {
+ detail: RefactoringOpportunityDetailResolved;
+ onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;
+ onStatusChange?:
+ | ((
+ detail: RefactoringOpportunityDetailResolved,
+ status: OpportunityStatus,
+ ) => Promise<void> | void)
+ | undefined;
+ onOpenStep?: ((planId: string) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}) {
+ const meta = typeMeta(detail.lead_refactoring_type || "");
+ const name = detail.file_path.split("/").pop() ?? detail.file_path;
+ const others = detail.affected_files.filter((f) => f !== detail.file_path);
+ const anyRelocated = detail.steps.some(isRelocated);
+
+ const [pending, setPending] = React.useState<OpportunityStatus | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const status = pending ?? detail.status;
+
+ React.useEffect(() => {
+ setPending(null);
+ }, [detail.status]);
+
+ const setStatus = React.useCallback(
+ async (next: OpportunityStatus) => {
+ if (!onStatusChange) return;
+ setPending(next);
+ setFailed(false);
+ try {
+ await onStatusChange(detail, next);
+ } catch {
+ setPending(null);
+ setFailed(true);
+ }
+ },
+ [onStatusChange, detail],
+ );
+
+ const facts: string[] = [
+ `${EFFORT_LABEL[detail.effort_bucket]} effort`,
+ `${CONFIDENCE_LABEL[detail.confidence]} confidence`,
+ `${detail.step_count} step${detail.step_count === 1 ? "" : "s"}, ${detail.mechanical_steps} mechanical`,
+ ];
+ if (detail.affected_files_total > 1) {
+ facts.push(`${formatNumber(detail.affected_files_total)} files affected`);
+ }
+
+ return (
+ <>
+ <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">
+ <div className="text-[11px] text-[var(--color-text-secondary)]">
+ {meta.label}
+ {detail.lead_biomarker ? ` · against ${humanizeBiomarker(detail.lead_biomarker)}` : ""}
+ </div>
+ <SheetTitle className="mt-0.5 break-words font-mono text-[15px] font-semibold text-[var(--color-text-primary)]">
+ {name}
+ </SheetTitle>
+ <p className="mt-1 break-all font-mono text-[11.5px] text-[var(--color-text-tertiary)]">
+ {detail.file_path}
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-[var(--color-border-default)] px-5 py-2.5 text-[12.5px] text-[var(--color-text-secondary)]">
+ {facts.map((f) => (
+ <span key={f}>{f}</span>
+ ))}
+ {detail.recoverable_health > 0 ? (
+ <span className="font-medium tabular-nums text-[var(--color-success)]">
+ +{detail.recoverable_health.toFixed(1)} health
+ </span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">No score change</span>
+ )}
+ </div>
+
+ <div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">
+ {/* Tri-state, stated in words. `null` is its own sentence: the layer had
+ no dominant finding to compare against, which is not the same claim
+ as "these steps address something else". */}
+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">
+ {addressesPrimaryLabel(detail.addresses_primary_problem)}.{" "}
+ {detail.addresses_primary_problem === false
+ ? "The steps below are still real work; they are just not what is costing this file the most."
+ : meta.blurb}
+ </p>
+
+ {onStatusChange ? (
+ <section>
+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Triage
+ </h4>
+ <div role="radiogroup" aria-label="Triage this opportunity" className="flex flex-wrap gap-1.5">
+ {TRIAGE_STATUSES.map((option) => {
+ const current = option.value === status;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={current}
+ disabled={current}
+ onClick={() => void setStatus(option.value)}
+ className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
+ current
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {option.label}
+ </button>
+ );
+ })}
+ </div>
+ <p className="mt-1.5 text-[11.5px] text-[var(--color-text-tertiary)]">
+ Applies to all {detail.step_count} step{detail.step_count === 1 ? "" : "s"}.{" "}
+ {status === "false_positive"
+ ? "A false positive is suppressed on every later analysis."
+ : "Currently " + STATUS_LABEL[status].toLowerCase() + "."}
+ </p>
+ <p
+ role="status"
+ className={
+ failed ? "mt-1 text-[11.5px] text-[var(--color-error)]" : "sr-only"
+ }
+ >
+ {failed ? "Could not save that. The opportunity is unchanged." : ""}
+ </p>
+ </section>
+ ) : null}
+
+ <section>
+ <h4 className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ The steps, in order
+ </h4>
+ {anyRelocated ? (
+ <p className="mb-3 rounded-md border border-[var(--color-caution)]/40 bg-[var(--color-caution)]/10 px-3 py-2 text-[12.5px] text-[var(--color-text-secondary)]">
+ {detail.ordering_note ?? ORDERING_NOTE}
+ </p>
+ ) : null}
+ <ol className="space-y-3">
+ {detail.steps.map((step, i) => (
+ <StepCard
+ key={step.plan_id}
+ step={step}
+ index={i}
+ onOpenStep={onOpenStep}
+ fileHref={fileHref}
+ />
+ ))}
+ </ol>
+ {detail.steps_emitted < detail.steps_total ? (
+ <p className="mt-2 text-[11.5px] text-[var(--color-text-tertiary)]">
+ Showing {detail.steps_emitted} of {detail.steps_total} steps.
+ </p>
+ ) : null}
+ </section>
+
+ {detail.validation_profiles.length > 0 ? (
+ <section>
+ <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Validation
+ </h4>
+ <div className="space-y-4">
+ {detail.validation_profiles.map((profile) => (
+ <ValidationSummary
+ key={profile.id}
+ validation={profile}
+ fileHref={(path) => fileHref?.(path, null)}
+ />
+ ))}
+ </div>
+ </section>
+ ) : null}
+
+ {detail.evidence.length > 0 ? (
+ <section>
+ <h4 className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Evidence
+ </h4>
+ {/* Named as observation, not instruction. These are mostly demoted
+ clone groups: real duplication, not a change worth making on its
+ own account. */}
+ <p className="mb-2.5 text-[12.5px] text-[var(--color-text-secondary)]">
+ Supporting observations on this file. They are why the diagnosis reads the way it
+ does, not extra work to do.
+ </p>
+ <ul className="space-y-1.5">
+ {detail.evidence.map((item) => (
+ <li
+ key={item.plan_id}
+ className="border-t border-[var(--color-border-default)] pt-1.5 text-[12.5px] text-[var(--color-text-secondary)]"
+ >
+ <span className="text-[var(--color-text-tertiary)]">
+ {typeMeta(item.refactoring_type).label}
+ </span>
+ {item.target_symbol ? (
+ <span className="ml-2 break-all font-mono text-[12px] text-[var(--color-text-primary)]">
+ {item.target_symbol}
+ </span>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ {detail.evidence_truncated ? (
+ <p className="mt-2 text-[11.5px] text-[var(--color-text-tertiary)]">
+ Showing {detail.evidence_emitted} of {detail.evidence_total} observations.
+ </p>
+ ) : null}
+ </section>
+ ) : null}
+
+ {others.length > 0 ? (
+ <section>
+ <h4 className="mb-2 flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <Layers className="h-3.5 w-3.5" />
+ Also affected
+ </h4>
+ <ul className="space-y-1">
+ {others.map((f) => {
+ const href = fileHref?.(f, null);
+ return (
+ <li key={f}>
+ {href ? (
+ <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"
+ >
+ {f}
+ </a>
+ ) : (
+ <span className="break-all font-mono text-xs text-[var(--color-text-secondary)]">
+ {f}
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ ) : null}
+
+ <section>
+ <h4 className="mb-2 flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <Terminal className="h-3.5 w-3.5" />
+ Ask for this by id
+ </h4>
+ <p className="text-[12.5px] text-[var(--color-text-secondary)]">
+ Copy the prompt with the Claude + MCP flavor and it carries this call, so the agent
+ can pull the same record itself rather than working from the pasted copy. The other
+ flavors inline the whole plan instead, because they have no tool that resolves an id.
+ </p>
+ <p className="mt-1.5 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">
+ {opportunityHandoffCall(detail.opportunity_id)}
+ </p>
+ </section>
+ </div>
+
+ {onAiPrompt ? (
+ <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(detail)}
+ 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 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <Sparkles className="h-4 w-4" aria-hidden="true" />
+ Copy prompt for an agent
+ </button>
+ <span className="hidden text-xs text-[var(--color-text-tertiary)] sm:block">
+ The ordered steps, the evidence, and the id to query it back.
+ </span>
+ </div>
+ ) : null}
+ </>
+ );
+}
+
+function StepCard({
+ step,
+ index,
+ onOpenStep,
+ fileHref,
+}: {
+ step: OpportunityStep;
+ index: number;
+ onOpenStep?: ((planId: string) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}) {
+ const meta = typeMeta(step.refactoring_type);
+ const mechanical = step.applicability.classification === "mechanical";
+ const href = fileHref?.(step.file_path, step.line_start);
+ const span = step.line_start
+ ? `${step.line_start}${step.line_end ? `–${step.line_end}` : ""}`
+ : null;
+
+ return (
+ <li className="rounded-lg border border-[var(--color-border-default)] px-3.5 py-3">
+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {String(index + 1).padStart(2, "0")}
+ </span>
+ <span className="text-[12.5px] text-[var(--color-text-secondary)]">{meta.label}</span>
+ {/* Not a colour-only mark: the word is the signal, and the tint only
+ reinforces it. */}
+ <span
+ className={`rounded px-1.5 py-0.5 text-[11px] font-medium ${
+ mechanical
+ ? "bg-[var(--color-success)]/12 text-[var(--color-success)]"
+ : "bg-[var(--color-bg-inset)] text-[var(--color-text-secondary)]"
+ }`}
+ >
+ {mechanical ? "Mechanical" : "Judgment"}
+ </span>
+ {isRelocated(step) ? (
+ <span className="rounded bg-[var(--color-caution)]/15 px-1.5 py-0.5 text-[11px] font-medium text-[var(--color-caution)]">
+ Moved by an earlier step
+ </span>
+ ) : null}
+ </div>
+
+ <button
+ type="button"
+ onClick={onOpenStep ? () => onOpenStep(step.plan_id) : undefined}
+ disabled={!onOpenStep}
+ className="mt-1 block break-all text-left font-mono text-[13px] font-medium text-[var(--color-text-primary)] enabled:hover:text-[var(--color-accent-primary)]"
+ >
+ {step.target_symbol || meta.label}
+ </button>
+
+ <p className="mt-0.5 break-all font-mono text-[11px] text-[var(--color-text-tertiary)]">
+ {href ? (
+ <a href={href} className="underline-offset-2 hover:underline">
+ {step.file_path}
+ {span ? `:${span}` : ""}
+ </a>
+ ) : (
+ <>
+ {step.file_path}
+ {span ? `:${span}` : ""}
+ </>
+ )}
+ </p>
+
+ {isRelocated(step) ? (
+ <p className="mt-1.5 text-[12px] text-[var(--color-text-secondary)]">
+ An earlier step moves this symbol out of that file, so the path and lines above say where
+ it was. Find it again before applying this one.
+ </p>
+ ) : null}
+
+ {step.applicability.reasons.length > 0 ? (
+ <p className="mt-1.5 text-[12px] text-[var(--color-text-secondary)]">
+ {step.applicability.reasons.map(humanizeBiomarker).join("; ")}.
+ </p>
+ ) : null}
+
+ {step.applicability.unknowns.length > 0 ? (
+ // An unknown is first-class. Leaving it out would let a check the layer
+ // never ran read as a check that passed.
+ <p className="mt-1 text-[12px] text-[var(--color-text-tertiary)]">
+ Not established: {step.applicability.unknowns.map(humanizeBiomarker).join(", ")}.
+ </p>
+ ) : null}
+ </li>
+ );
+}
diff --git a/packages/ui/src/refactoring/opportunity-rows.tsx b/packages/ui/src/refactoring/opportunity-rows.tsx
new file mode 100644
index 000000000..be89b1ee5
--- /dev/null
+++ b/packages/ui/src/refactoring/opportunity-rows.tsx
@@ -0,0 +1,420 @@
+"use client";
+
+/**
+ * The opportunity list, as hairline rows. One row is one file's refactoring.
+ *
+ * This replaced a grid of `RefactoringPlanCard`s, and then replaced the plan
+ * rows that replaced them. Each card carried a type-coloured rail, a tinted
+ * type chip, a bordered metric footer and a second bordered strip holding its
+ * own AI-prompt button - four borders and two click targets per plan, sixty at
+ * a time - and forced three truncations each, which is a layout decision
+ * reported to the reader as missing content.
+ *
+ * The unit change is the bigger one. A row used to be a detector output, so a
+ * file with fifteen of them filled the screen fifteen times and the reader had
+ * to reassemble "this file needs work" themselves. A row is now the composed
+ * opportunity: the file, what it leads with, how many steps, and how many of
+ * those are mechanical.
+ *
+ * Marks stay conditional rather than universal, per "mark only what needs
+ * attention": confidence renders only when it is not high, recovered health
+ * only when there is any, and lifecycle only once a person has moved it off
+ * `open`.
+ */
+
+import * as React from "react";
+
+import { formatNumber } from "../lib/format";
+import { typeMeta } from "./meta";
+import {
+ STATUS_LABEL,
+ TRIAGE_STATUSES,
+ addressesPrimaryLabel,
+ addressesPrimaryShort,
+ opportunityLede,
+ stepSummary,
+} from "./opportunity";
+import type {
+ OpportunityStatus,
+ RefactoringOpportunity,
+} from "@repowise-dev/types/refactoring";
+
+export interface OpportunityRowsProps {
+ opportunities: RefactoringOpportunity[];
+ onOpen?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ /** The overflow verb: hand this opportunity to a coding agent. */
+ onAiPrompt?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ /** Record a triage decision. Controls hide entirely when absent. */
+ onStatusChange?:
+ | ((
+ opportunity: RefactoringOpportunity,
+ status: OpportunityStatus,
+ ) => Promise<void> | void)
+ | undefined;
+ /** Link to the file, used by the overflow menu. */
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ /** Lit from the map above, when a row is also plotted. */
+ highlightedId?: string | null | undefined;
+ onHighlight?: ((id: string | null) => void) | undefined;
+}
+
+const EFFORT_WORD: Record<string, string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+ XL: "Extra large",
+};
+
+/**
+ * One grid, named once.
+ *
+ * The header and the rows have to share a template or they drift the first time
+ * a column is resized, and a header that does not line up with its column is
+ * worse than no header. The file column is the flexible one because it is the
+ * only cell whose content has no natural width.
+ */
+const GRID =
+ "grid grid-cols-[minmax(0,1fr)_auto] gap-x-5 gap-y-2 px-3 " +
+ "lg:grid-cols-[116px_minmax(0,1fr)_150px_104px_96px_32px]";
+
+export function OpportunityRows({
+ opportunities,
+ onOpen,
+ onAiPrompt,
+ onStatusChange,
+ fileHref,
+ highlightedId,
+ onHighlight,
+}: OpportunityRowsProps) {
+ return (
+ <div className="flex flex-col">
+ {/* Hidden below `lg`, where the row stacks and the labels would outnumber
+ the values they label. */}
+ <div
+ aria-hidden
+ className={`${GRID} hidden border-b border-[var(--color-border-default)] pb-2 pt-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] lg:grid`}
+ >
+ <span>Type</span>
+ <span>File</span>
+ <span>Work</span>
+ <span>Health</span>
+ <span>Status</span>
+ <span className="sr-only">Actions</span>
+ </div>
+ {opportunities.map((opportunity) => (
+ <OpportunityRow
+ key={opportunity.opportunity_id}
+ opportunity={opportunity}
+ onOpen={onOpen}
+ onAiPrompt={onAiPrompt}
+ onStatusChange={onStatusChange}
+ fileHref={fileHref}
+ onHighlight={onHighlight}
+ lit={opportunity.opportunity_id === highlightedId}
+ />
+ ))}
+ </div>
+ );
+}
+
+function OpportunityRow({
+ opportunity,
+ onOpen,
+ onAiPrompt,
+ onStatusChange,
+ fileHref,
+ onHighlight,
+ lit,
+}: {
+ opportunity: RefactoringOpportunity;
+ onOpen?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ onAiPrompt?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ onStatusChange?:
+ | ((
+ opportunity: RefactoringOpportunity,
+ status: OpportunityStatus,
+ ) => Promise<void> | void)
+ | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ onHighlight?: ((id: string | null) => void) | undefined;
+ lit: boolean;
+}) {
+ const meta = typeMeta(opportunity.lead_refactoring_type || "");
+ const effort = EFFORT_WORD[opportunity.effort_bucket] ?? opportunity.effort_bucket;
+ const href = fileHref?.(opportunity.file_path);
+ const gain = opportunity.recoverable_health;
+ const name = opportunity.file_path.split("/").pop() ?? opportunity.file_path;
+
+ // Optimistic, with the server's answer as the authority. A triage click that
+ // waits for a round trip reads as a dead control on a list this long.
+ const [pending, setPending] = React.useState<OpportunityStatus | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const status = pending ?? opportunity.status;
+
+ const setStatus = React.useCallback(
+ async (next: OpportunityStatus) => {
+ if (!onStatusChange) return;
+ setPending(next);
+ setFailed(false);
+ try {
+ await onStatusChange(opportunity, next);
+ } catch {
+ // Roll back to whatever the row was handed, and say so rather than
+ // leaving a state the server never accepted looking committed.
+ setPending(null);
+ setFailed(true);
+ }
+ },
+ [onStatusChange, opportunity],
+ );
+
+ React.useEffect(() => {
+ // The refetched row is the truth; drop the optimistic value once it lands.
+ setPending(null);
+ }, [opportunity.status]);
+
+ return (
+ <div
+ data-refactoring-opportunity={opportunity.opportunity_id}
+ onMouseEnter={() => onHighlight?.(opportunity.opportunity_id)}
+ onMouseLeave={() => onHighlight?.(null)}
+ className={`${GRID} items-start border-t border-[var(--color-border-default)] py-3 ${
+ lit ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]"
+ }`}
+ >
+ <div className="order-2 text-xs text-[var(--color-text-secondary)] lg:order-none lg:pt-px">
+ {meta.label}
+ </div>
+
+ <button
+ type="button"
+ onClick={onOpen ? () => onOpen(opportunity) : undefined}
+ disabled={!onOpen}
+ onFocus={() => onHighlight?.(opportunity.opportunity_id)}
+ onBlur={() => onHighlight?.(null)}
+ className="group order-1 col-span-2 min-w-0 text-left lg:order-none lg:col-span-1"
+ >
+ <span className="block break-words font-mono text-[13.5px] font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
+ {name}
+ </span>
+ {/* Full path, no ellipsis: a truncated title reports a layout decision
+ to the reader as missing content. */}
+ <span className="mt-0.5 block break-all font-mono text-[11.5px] text-[var(--color-text-tertiary)]">
+ {opportunity.file_path}
+ </span>
+ <span className="mt-1 block text-[12px] text-[var(--color-text-secondary)]">
+ {opportunityLede(opportunity)}
+ </span>
+ </button>
+
+ <div className="order-3 text-[12.5px] text-[var(--color-text-secondary)] lg:order-none lg:pt-px">
+ {stepSummary(opportunity)}
+ <br />
+ <span className="text-[11.5px] text-[var(--color-text-tertiary)]">
+ {effort} effort
+ {opportunity.affected_files_total > 1
+ ? `, ${formatNumber(opportunity.affected_files_total)} files`
+ : ""}
+ </span>
+ {opportunity.confidence !== "high" ? (
+ <span className="ml-2 inline-flex items-center gap-1.5 text-[11.5px] text-[var(--color-caution)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-current" />
+ {opportunity.confidence} confidence
+ </span>
+ ) : null}
+ </div>
+
+ <div className="order-4 space-y-1 text-[12.5px] tabular-nums lg:order-none lg:pt-px">
+ {gain > 0 ? (
+ <span className="block font-medium text-[var(--color-success)]">
+ +{gain.toFixed(1)} health
+ </span>
+ ) : (
+ <span className="block text-[var(--color-text-tertiary)]">no score change</span>
+ )}
+ {/* Tri-state, and the unknown case says so. Reading "no" onto "we could
+ not tell" would turn a missing input into an accusation. */}
+ <span
+ title={addressesPrimaryLabel(opportunity.addresses_primary_problem)}
+ className={
+ opportunity.addresses_primary_problem === true
+ ? "block text-[11.5px] text-[var(--color-text-secondary)]"
+ : "block text-[11.5px] text-[var(--color-text-tertiary)]"
+ }
+ >
+ {addressesPrimaryShort(opportunity.addresses_primary_problem)}
+ </span>
+ </div>
+
+ {/* Its own column. Triage was a line that appeared inside the health cell
+ only once a row left `open`, so the list had no column a reader could
+ scan down to see what they had already dealt with - and the row's
+ height changed when they marked one. */}
+ <div className="order-5 text-[12.5px] lg:order-none lg:pt-px">
+ <span
+ className={
+ status === "open"
+ ? "text-[var(--color-text-tertiary)]"
+ : "font-medium text-[var(--color-accent-primary)]"
+ }
+ >
+ {STATUS_LABEL[status]}
+ </span>
+ {/* Rendered whether or not it has anything to say: several screen
+ readers announce a text change inside a live region but not the
+ arrival of the region itself. */}
+ <span
+ role="status"
+ className={
+ failed ? "mt-0.5 block text-[11.5px] text-[var(--color-error)]" : "sr-only"
+ }
+ >
+ {failed ? "Could not save" : ""}
+ </span>
+ </div>
+
+ <div className="order-6 justify-self-end lg:order-none lg:-mt-1">
+ <RowOverflow
+ opportunity={opportunity}
+ status={status}
+ onAiPrompt={onAiPrompt}
+ onStatusChange={onStatusChange ? setStatus : undefined}
+ href={href}
+ />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The row's second-order verbs.
+ *
+ * Opening the opportunity is the row itself. Everything else lives here so a
+ * 580-row list is not 580 clusters of controls the reader has to parse before
+ * they can read a row - and so each verb can have its real name rather than an
+ * abbreviation that only expands for someone who already knows the model.
+ */
+function RowOverflow({
+ opportunity,
+ status,
+ onAiPrompt,
+ onStatusChange,
+ href,
+}: {
+ opportunity: RefactoringOpportunity;
+ status: OpportunityStatus;
+ onAiPrompt?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ onStatusChange?: ((status: OpportunityStatus) => void) | undefined;
+ href?: string | undefined;
+}) {
+ const [open, setOpen] = React.useState(false);
+ const ref = React.useRef<HTMLDivElement | null>(null);
+ const triggerRef = React.useRef<HTMLButtonElement | null>(null);
+
+ // Closing unmounts the menu, and if the focused item was inside it the
+ // browser drops focus to <body>. On a list this long that ejects a keyboard
+ // reader to the top of the document on every triage action.
+ const close = React.useCallback((restoreFocus = true) => {
+ setOpen(false);
+ if (restoreFocus) triggerRef.current?.focus();
+ }, []);
+
+ React.useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ // A click elsewhere is the reader moving on; taking focus back would
+ // fight them for it.
+ if (ref.current && !ref.current.contains(e.target as Node)) close(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") close();
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open, close]);
+
+ if (!onAiPrompt && !href && !onStatusChange) return null;
+
+ return (
+ <div className="relative" ref={ref}>
+ <button
+ ref={triggerRef}
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded={open}
+ aria-label={`More actions for ${opportunity.file_path}`}
+ onClick={() => setOpen((v) => !v)}
+ className="rounded-md px-1.5 py-1 leading-none text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-primary)]"
+ >
+ <span aria-hidden>&#183;&#183;&#183;</span>
+ </button>
+ {open ? (
+ <div
+ role="menu"
+ className="absolute right-0 top-full z-20 mt-1 w-60 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-md"
+ >
+ {onAiPrompt ? (
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ close();
+ onAiPrompt(opportunity);
+ }}
+ className="block w-full px-3 py-2 text-left text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ Copy prompt for an agent
+ </button>
+ ) : null}
+ {href ? (
+ <a
+ href={href}
+ role="menuitem"
+ className="block px-3 py-2 text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ Open file
+ </a>
+ ) : null}
+ {onStatusChange ? (
+ <div
+ role="group"
+ aria-label="Triage this opportunity"
+ className="mt-1 border-t border-[var(--color-border-default)] pt-1"
+ >
+ <p className="px-3 pb-1 pt-1 text-[11px] uppercase tracking-[0.08em] text-[var(--color-text-tertiary)]">
+ Triage
+ </p>
+ {TRIAGE_STATUSES.map((option) => {
+ const current = option.value === status;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="menuitemradio"
+ aria-checked={current}
+ disabled={current}
+ onClick={() => {
+ close();
+ onStatusChange(option.value);
+ }}
+ className={`block w-full px-3 py-2 text-left text-[13px] ${
+ current
+ ? "font-medium text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {option.label}
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/opportunity.ts b/packages/ui/src/refactoring/opportunity.ts
new file mode 100644
index 000000000..53ff8243e
--- /dev/null
+++ b/packages/ui/src/refactoring/opportunity.ts
@@ -0,0 +1,222 @@
+/**
+ * View model for the composed opportunity: the unit the board, the map and the
+ * drawer all speak.
+ *
+ * Pure functions over the wire types, so every surface derives the same words
+ * from the same fields instead of each writing its own sentence. Nothing here
+ * fetches, and nothing renders.
+ */
+
+import type {
+ OpportunityStatus,
+ OpportunityStep,
+ RefactoringOpportunity,
+} from "@repowise-dev/types/refactoring";
+
+import { STRUCTURAL_TYPES } from "./types";
+import { TYPE_ORDER, typeMeta } from "./meta";
+
+/** The four triage states, in the order a person moves through them. */
+export const TRIAGE_STATUSES: { value: OpportunityStatus; label: string }[] = [
+ { value: "open", label: "Open" },
+ { value: "acknowledged", label: "Acknowledged" },
+ { value: "resolved", label: "Resolved" },
+ { value: "false_positive", label: "False positive" },
+];
+
+export const STATUS_LABEL: Record<OpportunityStatus, string> = {
+ open: "Open",
+ acknowledged: "Acknowledged",
+ resolved: "Resolved",
+ false_positive: "False positive",
+};
+
+/**
+ * Whether the file's dominant finding is what these steps address.
+ *
+ * Tri-state on purpose. `null` means no dominant finding was recorded to
+ * compare against, which is a different claim from "no, they address something
+ * else" - and on a real index the `false` answers are the honest ones, so
+ * flattening the two would turn "we could not tell" into an accusation.
+ */
+export function addressesPrimaryLabel(value: boolean | null | undefined): string {
+ if (value === true) return "Addresses the file's main problem";
+ if (value === false) return "Does not address the file's main problem";
+ return "No dominant problem recorded for this file";
+}
+
+export function addressesPrimaryShort(value: boolean | null | undefined): string {
+ if (value === true) return "Main problem";
+ if (value === false) return "Side problem";
+ return "Lead unknown";
+}
+
+/** `3 steps - 2 mechanical`: the shape of the work, in the row's own words. */
+export function stepSummary(opportunity: RefactoringOpportunity): string {
+ const steps = `${opportunity.step_count} step${opportunity.step_count === 1 ? "" : "s"}`;
+ if (opportunity.mechanical_steps === 0) return `${steps}, all judgment`;
+ if (opportunity.judgment_steps === 0) return `${steps}, all mechanical`;
+ return `${steps}, ${opportunity.mechanical_steps} mechanical`;
+}
+
+/** `nested_complexity` -> `nested complexity`. */
+export function humanizeBiomarker(token: string): string {
+ return token.replace(/_/g, " ").trim();
+}
+
+/** One sentence naming what the opportunity is, for a row's second line. */
+export function opportunityLede(opportunity: RefactoringOpportunity): string {
+ const meta = typeMeta(opportunity.lead_refactoring_type || "");
+ const cause = opportunity.lead_biomarker
+ ? humanizeBiomarker(opportunity.lead_biomarker)
+ : null;
+ return cause ? `${meta.label}, against ${cause}` : meta.label;
+}
+
+/**
+ * A step whose file and span describe where its symbol *was*.
+ *
+ * `relocated_by` names an earlier step that moves the symbol to another file,
+ * so an ordered list handed to anyone - a reader or an agent - has to say the
+ * later step must be located again before it is applied.
+ */
+export function isRelocated(step: OpportunityStep): boolean {
+ return Boolean(step.relocated_by);
+}
+
+export const ORDERING_NOTE =
+ "Steps are in dependency-safe order. A step marked as relocated names an " +
+ "earlier step that moves its symbol to another file, so its own file and " +
+ "line range say where the symbol was: find it again before applying it.";
+
+// ---------------------------------------------------------------------------
+// The structural field
+// ---------------------------------------------------------------------------
+
+/** One mark: one file's structural opportunity, at that file's coordinates. */
+export interface StructuralMark {
+ opportunityId: string;
+ filePath: string;
+ leadType: string;
+ stepCount: number;
+ status: OpportunityStatus;
+ /** Files that import this one. */
+ x: number;
+ /** Lines in the file. */
+ y: number;
+}
+
+const STRUCTURAL = new Set<string>(STRUCTURAL_TYPES as readonly string[]);
+
+/**
+ * The structural opportunities that can be placed on the field.
+ *
+ * The two axes are properties of the *file* - how big it is, how much imports
+ * it - and the finalizer records them onto the opportunity because it is the
+ * only place on the write path that has already computed them. Reading them off
+ * the row is what lets the field draw one mark per opportunity: it used to plot
+ * one per plan, so a file big enough to split and also caught in a cycle
+ * appeared twice and the sprawl the composed unit removed came back as ink.
+ *
+ * An opportunity whose figures are absent - a store written before they were
+ * recorded, or a file the analyzer never measured - is dropped rather than
+ * plotted at the origin. The caller counts what it dropped and says so.
+ */
+export function structuralMarks(opportunities: RefactoringOpportunity[]): StructuralMark[] {
+ const marks: StructuralMark[] = [];
+ for (const item of opportunities) {
+ if (!STRUCTURAL.has(item.lead_refactoring_type)) continue;
+ const x = item.dependents;
+ const y = item.file_nloc;
+ // Absent is not zero. A file nothing imports has a measured `dependents` of
+ // 0 and belongs on the field - it is the left edge of the axis, and it is
+ // often the entrypoint. Only a figure the store never recorded is dropped.
+ // (A zero `file_nloc` is a different matter: an empty file has nothing to
+ // split, and the log-scaled x needs a positive value anyway.)
+ if (x === undefined || !y) continue;
+ marks.push({
+ opportunityId: item.opportunity_id,
+ filePath: item.file_path,
+ leadType: item.lead_refactoring_type,
+ stepCount: item.step_count,
+ status: item.status,
+ x,
+ y,
+ });
+ }
+ return marks;
+}
+
+/**
+ * Salience order for the structural types present, most common first.
+ *
+ * Derived from the marks in hand, never fixed per type: the four structural
+ * types are wildly unequal on this repo (74 / 17 / 6 / 3 per cent) but there is
+ * no reason another codebase's cycles could not outnumber its oversized files,
+ * and a hardcoded hue would then paint the dominant category as the rare one.
+ * `TYPE_ORDER` breaks count ties, so the assignment is stable across renders.
+ */
+export function salienceOrder(marks: StructuralMark[]): string[] {
+ const counts = new Map<string, number>();
+ for (const mark of marks) counts.set(mark.leadType, (counts.get(mark.leadType) ?? 0) + 1);
+ const rank = (type: string) => {
+ const at = (TYPE_ORDER as readonly string[]).indexOf(type);
+ return at === -1 ? TYPE_ORDER.length : at;
+ };
+ return [...counts.entries()]
+ .sort((a, b) => b[1] - a[1] || rank(a[0]) - rank(b[0]))
+ .map(([type]) => type);
+}
+
+/**
+ * Two hues, then neutrals - the pattern the commits area chart already uses.
+ *
+ * The accent/secondary pair, and deliberately not the sequential
+ * `--color-ramp-*` steps: globals.css reserves the ramp for magnitude, so
+ * spending it on unrelated categories would claim an order the types do not
+ * have, and it would add orange rather than reduce it. Type is carried in full
+ * by the mark's shape, and named in the legend and the hover card, so hue here
+ * only ranks attention - which is why the tail can recede into neutrals without
+ * anything becoming unreadable.
+ *
+ * **`--color-accent-primary`, not `--color-accent-fill`.** They are the same
+ * bright orange in dark mode, but light mode deepens the former to `#A16215`
+ * precisely so it reads on warm paper: measured against `--color-bg-root`,
+ * `accent-fill` is 2.12:1 in light and `accent-primary` is 4.58:1, against a
+ * 3.0 floor for non-text UI. The theme doc records the same correction being
+ * made once already, when the community graph's orange hub had to be deepened
+ * from `#F59520` to `#C0641A` for the same reason on the same kind of canvas.
+ *
+ * The neutral tiers do *not* clear that floor on their own (1.25 to 2.45:1),
+ * and they are not asked to: every mark carries a separating stroke, so the
+ * fill only has to distinguish tiers, not to be the thing that makes a mark
+ * visible. That split is the galaxy's device, for the same reason.
+ */
+const SALIENCE_FILLS = [
+ "var(--color-accent-primary)",
+ "var(--color-accent-secondary)",
+ "var(--color-neutral-1)",
+ "var(--color-neutral-2)",
+ "var(--color-neutral-3)",
+];
+
+/**
+ * The outline every mark carries, whatever its fill.
+ *
+ * 3.55:1 against the light page and 3.84:1 against the dark one, so a mark is
+ * locatable before its fill says anything. Without it a receded type in
+ * `--color-neutral-3` sits at 1.25:1 and is simply not there.
+ */
+export const MARK_STROKE = "var(--color-text-tertiary)";
+
+export function salienceFill(type: string, order: string[]): string {
+ const at = order.indexOf(type);
+ const index = at === -1 ? order.length : at;
+ return SALIENCE_FILLS[Math.min(index, SALIENCE_FILLS.length - 1)]!;
+}
+
+/** True once a type has fallen past the two hues into the neutral tail. */
+export function isRecededType(type: string, order: string[]): boolean {
+ const at = order.indexOf(type);
+ return at === -1 || at >= 2;
+}
diff --git a/packages/ui/src/refactoring/plan-rows.tsx b/packages/ui/src/refactoring/plan-rows.tsx
deleted file mode 100644
index 667e95f38..000000000
--- a/packages/ui/src/refactoring/plan-rows.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-"use client";
-
-/**
- * The full plan list, as hairline rows.
- *
- * This replaces a grid of `RefactoringPlanCard`s. Each card carried a
- * type-coloured rail, a tinted type chip, a bordered metric footer and a second
- * bordered strip holding its own AI-prompt button — four borders and two click
- * targets per plan, sixty at a time. Cards also forced three truncations each
- * (filename, directory, synopsis), which is a layout decision reported to the
- * reader as missing content.
- *
- * Two marks that are now conditional rather than universal, per "mark only what
- * needs attention": confidence renders only when it is not high (medium is 66%
- * of plans and high is the rest, so a dot on every row separated nothing), and
- * recovered health renders only when there is any (1,399 of 1,819 plans recover
- * under half a point).
- */
-
-import * as React from "react";
-
-import { formatNumber } from "../lib/format";
-import { typeMeta } from "./meta";
-import { blastCount, planSynopsis } from "./types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
-
-export interface PlanRowsProps {
- plans: RefactoringPlan[];
- onOpen?: ((plan: RefactoringPlan) => void) | undefined;
- /** The overflow verb: hand this plan to a coding agent. */
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- /** Link to the file, used by the overflow menu. */
- fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
- /** Lit from the map above, when a row is also plotted. */
- highlightedId?: string | null | undefined;
-}
-
-const EFFORT_WORD: Record<string, string> = {
- S: "Small",
- M: "Medium",
- L: "Large",
- XL: "Extra large",
-};
-
-export function PlanRows({ plans, onOpen, onAiPrompt, fileHref, highlightedId }: PlanRowsProps) {
- return (
- <div className="flex flex-col">
- {plans.map((plan) => (
- <PlanRow
- key={plan.id}
- plan={plan}
- onOpen={onOpen}
- onAiPrompt={onAiPrompt}
- fileHref={fileHref}
- lit={plan.id === highlightedId}
- />
- ))}
- </div>
- );
-}
-
-function PlanRow({
- plan,
- onOpen,
- onAiPrompt,
- fileHref,
- lit,
-}: {
- plan: RefactoringPlan;
- onOpen?: ((plan: RefactoringPlan) => void) | undefined;
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
- lit: boolean;
-}) {
- const meta = typeMeta(plan.refactoring_type);
- const effort = EFFORT_WORD[plan.effort_bucket || "M"] ?? plan.effort_bucket;
- const blast = blastCount(plan);
- const gain = plan.impact_delta;
- const href = fileHref?.(plan.file_path, plan.line_start);
-
- return (
- <div
- data-refactoring-plan={plan.id}
- className={`grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-5 gap-y-2 border-t border-[var(--color-border-default)] px-3 py-3 lg:grid-cols-[128px_minmax(0,1fr)_170px_120px_32px] lg:items-center ${
- lit ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]"
- }`}
- >
- <div className="order-2 text-xs text-[var(--color-text-secondary)] lg:order-none">
- {meta.label}
- </div>
-
- <button
- type="button"
- onClick={onOpen ? () => onOpen(plan) : undefined}
- disabled={!onOpen}
- className="group order-1 col-span-2 min-w-0 text-left lg:order-none lg:col-span-1"
- >
- <span className="block break-words font-mono text-[13.5px] font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
- {plan.target_symbol || planSynopsis(plan) || meta.label}
- </span>
- <span className="mt-0.5 block break-all font-mono text-[11.5px] text-[var(--color-text-tertiary)]">
- {plan.file_path}
- </span>
- </button>
-
- <div className="order-3 text-[12.5px] text-[var(--color-text-secondary)] lg:order-none">
- {effort}
- {blast > 0 ? `, ${formatNumber(blast)} file${blast === 1 ? "" : "s"}` : ""}
- {plan.confidence !== "high" ? (
- <span className="ml-2 inline-flex items-center gap-1.5 text-[11.5px] text-[var(--color-caution)]">
- <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-current" />
- {plan.confidence === "low" ? "low" : "medium"} confidence
- </span>
- ) : null}
- </div>
-
- <div className="order-4 text-[12.5px] tabular-nums lg:order-none">
- {plan.refactoring_type === "performance_fix" && (plan.benefit ?? 0) > 0 ? (
- <span className="font-medium text-[var(--color-success)]">
- {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>
- )}
- </div>
-
- <div className="order-5 justify-self-end lg:order-none">
- <RowOverflow plan={plan} onAiPrompt={onAiPrompt} href={href} />
- </div>
- </div>
- );
-}
-
-/**
- * The row's second-order verbs.
- *
- * Opening the plan is the row itself. Everything else lives here so a 1,819-row
- * list is not 1,819 clusters of controls the reader has to parse before they can
- * read a row — and so each verb can have its real name rather than an
- * abbreviation that only expands for someone who already knows the model.
- */
-function RowOverflow({
- plan,
- onAiPrompt,
- href,
-}: {
- plan: RefactoringPlan;
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- href?: string | undefined;
-}) {
- const [open, setOpen] = React.useState(false);
- const ref = React.useRef<HTMLDivElement | null>(null);
-
- React.useEffect(() => {
- if (!open) return;
- const onDown = (e: MouseEvent) => {
- if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
- };
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") setOpen(false);
- };
- document.addEventListener("mousedown", onDown);
- document.addEventListener("keydown", onKey);
- return () => {
- document.removeEventListener("mousedown", onDown);
- document.removeEventListener("keydown", onKey);
- };
- }, [open]);
-
- if (!onAiPrompt && !href) return null;
-
- return (
- <div className="relative" ref={ref}>
- <button
- type="button"
- aria-haspopup="menu"
- aria-expanded={open}
- aria-label={`More actions for ${plan.file_path}`}
- onClick={() => setOpen((v) => !v)}
- className="rounded-md px-1.5 py-1 leading-none text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-primary)]"
- >
- <span aria-hidden>&#183;&#183;&#183;</span>
- </button>
- {open ? (
- <div
- role="menu"
- className="absolute right-0 top-full z-20 mt-1 w-56 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-md"
- >
- {onAiPrompt ? (
- <button
- type="button"
- role="menuitem"
- onClick={() => {
- setOpen(false);
- onAiPrompt(plan);
- }}
- className="block w-full px-3 py-2 text-left text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- Copy prompt for an agent
- </button>
- ) : null}
- {href ? (
- <a
- href={href}
- role="menuitem"
- className="block px-3 py-2 text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- Open file
- </a>
- ) : null}
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index b29be9058..99a7b8ca5 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -3,40 +3,53 @@
/**
* The Refactoring surface.
*
- * Lede, then the structural plans as a field with the top few ranked under it,
- * then every plan as hairline rows. What used to be here was a priority-by-
- * effort quadrant over a grid of cards; both were replaced for reasons recorded
- * in `structural-map.tsx` and `plan-rows.tsx`.
+ * Lede, then the structural opportunities as a field with the top few ranked
+ * under it, then every opportunity as hairline rows. What used to be here was a
+ * priority-by-effort quadrant over a grid of cards; both were replaced for
+ * reasons recorded in `structural-map.tsx` and `opportunity-rows.tsx`.
*
- * The list controls survive largely intact — search, sort, effort — with one
- * removal: the confidence filter no longer offers "low", because no detector
- * has ever emitted a low-confidence plan and the chip filtered to zero every
- * time it was clicked. It is built from the confidences actually present rather
- * than from the type, so it disappears entirely on a repo whose plans are all
- * one confidence.
+ * **The list's default order is the diversified queue, not worst-files-first.**
+ * Both are indexed columns, so the choice costs nothing either way and is
+ * purely about the question the page answers. This page answers "what should I
+ * do next", and the honest rank order puts eight interchangeable rows at the
+ * head: single high-confidence extractions recovering the same quantised
+ * `complex_method` deduction, tied to four decimal places and separated only by
+ * file path. Diversification breaks that tie by rotating lead cause, lead type
+ * and area, so the head reads as a set of choices rather than one choice typed
+ * out eight times. "Worst files first" is a different question - where is the
+ * damage, not what is cheap to fix - and Code Health's galaxy already answers
+ * it, so it stays available here as a named order rather than becoming the
+ * default and quietly making this a second, worse copy of that page.
+ *
+ * Filters are server-owned and single-valued, which is what the queue endpoint
+ * admits: one effort, one confidence. Chips toggle rather than accumulate, and
+ * the confidence row is built from the confidences actually present, so it
+ * disappears on a repo whose opportunities are all one confidence.
*/
import * as React from "react";
import { Search } from "lucide-react";
import { Input } from "../ui/input";
+import { FilterSelect } from "../health/code-health-controls";
import { PaginationControls } from "../shared/pagination-controls";
-import { PlanRows } from "./plan-rows";
+import { OpportunityRows } from "./opportunity-rows";
import { RefactoringLede } from "./refactoring-lede";
import { StartHere } from "./start-here";
import { CONFIDENCE_LABEL } from "./meta";
-import { blastCount, isStructural } from "./types";
+import { STATUS_LABEL, TRIAGE_STATUSES } from "./opportunity";
import type {
Confidence,
EffortBucket,
- RefactoringPlan,
- RefactoringSummary,
+ OpportunityStatus,
+ RefactoringOpportunity,
+ RefactoringOpportunityRollup,
+ RefactoringOrder,
} from "@repowise-dev/types/refactoring";
const PAGE_SIZE = 60;
const EFFORTS: EffortBucket[] = ["S", "M", "L", "XL"];
-const EFFORT_RANK: Record<EffortBucket, number> = { S: 0, M: 1, L: 2, XL: 3 };
const EFFORT_LABEL_LONG: Record<EffortBucket, string> = {
S: "Small",
M: "Medium",
@@ -45,58 +58,49 @@ const EFFORT_LABEL_LONG: Record<EffortBucket, string> = {
};
const CONFIDENCE_ORDER: Confidence[] = ["high", "medium", "low"];
-export type RefactoringSortKey = "canonical" | "health" | "effort" | "blast" | "file";
-
-const SORT_OPTIONS: { value: RefactoringSortKey; label: string }[] = [
- { value: "canonical", label: "Canonical priority" },
- { value: "health", label: "Health recovered" },
+const SORT_OPTIONS: { value: RefactoringOrder; label: string }[] = [
+ { value: "queue", label: "Recommended" },
+ { value: "rank", label: "Highest value" },
+ { value: "health", label: "Worst files first" },
{ value: "effort", label: "Effort, small first" },
- { value: "blast", label: "Files touched" },
{ value: "file", label: "File, A to Z" },
];
+export interface RefactoringBoardServerState {
+ query: string;
+ order: RefactoringOrder;
+ /** Which triage state the list is showing. The server defaults to `open`. */
+ status: OpportunityStatus;
+ effort: EffortBucket | null;
+ confidence: Confidence | null;
+ mechanicalOnly: boolean;
+ total: number;
+ offset: number;
+ nextOffset: number | null;
+}
+
export interface RefactoringBoardProps {
- /** Plans for the active type filter. */
- plans: RefactoringPlan[];
- /** Every plan, unfiltered — the lede and Start here describe the whole repo,
- * not the tab you happen to be on. This is also where the per-type counts
- * come from, which is why the board no longer takes a `summary`: the
- * 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?:
+ /** Opportunities for the active type filter, in the server's order. */
+ opportunities: RefactoringOpportunity[];
+ /** The repository rollup the endpoint returns. Feeds the lede. */
+ summary?: RefactoringOpportunityRollup | null | undefined;
+ /** Bounded structural head for Start here, already filtered to lead types. */
+ structuralOpportunities?: RefactoringOpportunity[] | undefined;
+ serverState: RefactoringBoardServerState;
+ onServerStateChange: (change: Partial<RefactoringBoardServerState>) => void;
+ indexedFileCount?: number | undefined;
+ onOpen?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ onAiPrompt?: ((opportunity: RefactoringOpportunity) => void) | undefined;
+ onStatusChange?:
| ((
- change: Partial<
- Pick<
- NonNullable<RefactoringBoardProps["serverState"]>,
- "query" | "sort" | "efforts" | "confidences" | "offset"
- >
- >,
- ) => void)
+ opportunity: RefactoringOpportunity,
+ status: OpportunityStatus,
+ ) => Promise<void> | void)
| undefined;
- indexedFileCount?: number | undefined;
- onOpen?: ((plan: RefactoringPlan) => void) | undefined;
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
/** Jump the type filter to the structural set. */
onSeeStructural?: (() => void) | undefined;
- /** Hide the lede and Start here — for hosts that render their own header. */
+ /** Hide the lede and Start here - for hosts that render their own header. */
showLede?: boolean;
sectionTitle?: string;
emptyTitle?: string;
@@ -104,105 +108,35 @@ export interface RefactoringBoardProps {
}
export function RefactoringBoard({
- plans,
- allPlans,
+ opportunities,
summary,
- structuralPlans,
+ structuralOpportunities,
serverState,
onServerStateChange,
indexedFileCount,
onOpen,
onAiPrompt,
+ onStatusChange,
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.",
+ sectionTitle = "All opportunities",
+ emptyTitle = "No refactoring opportunities",
+ emptyHint = "Opportunities appear here when a file is worth splitting, a cycle worth cutting, a class worth extracting, or a long function worth breaking up.",
}: RefactoringBoardProps) {
- const [query, setQuery] = React.useState("");
- 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(
- () => 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;
+ const [highlighted, setHighlighted] = React.useState<string | null>(null);
// 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));
- }, [controlled, every]);
-
- const toggle = React.useCallback(
- <T,>(setter: React.Dispatch<React.SetStateAction<Set<T>>>, value: T) => {
- setter((cur) => {
- const next = new Set(cur);
- if (next.has(value)) next.delete(value);
- else next.add(value);
- return next;
- });
- },
- [],
- );
+ const present = new Set(opportunities.map((o) => o.confidence));
+ const active = serverState.confidence;
+ return CONFIDENCE_ORDER.filter((c) => present.has(c) || c === active);
+ }, [opportunities, serverState.confidence]);
- 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;
- if (effortSel.size && !effortSel.has((p.effort_bucket || "M") as EffortBucket)) return false;
- if (confSel.size && !confSel.has((p.confidence || "medium") as Confidence)) return false;
- return true;
- });
- // `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":
- return b.impact_delta - a.impact_delta;
- case "effort":
- return (
- EFFORT_RANK[(a.effort_bucket || "M") as EffortBucket] -
- EFFORT_RANK[(b.effort_bucket || "M") as EffortBucket]
- );
- case "blast":
- return blastCount(b) - blastCount(a);
- case "file":
- return a.file_path.localeCompare(b.file_path);
- default:
- return 0;
- }
- });
- }
- return out;
- }, [controlled, plans, query, sortKey, effortSel, confSel]);
-
- React.useEffect(() => {
- setVisibleCount(PAGE_SIZE);
- }, [processed]);
-
- if ((summary?.total ?? every.length) === 0) {
+ const rollupTotal =
+ summary && summary.status === "available" ? summary.opportunities_total : null;
+ if ((rollupTotal ?? opportunities.length) === 0 && serverState.status === "open") {
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>
@@ -214,26 +148,36 @@ export function RefactoringBoard({
}
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;
+ serverState.query.trim() !== "" ||
+ serverState.effort !== null ||
+ serverState.confidence !== null ||
+ serverState.mechanicalOnly ||
+ serverState.status !== "open";
+ const resultTotal = serverState.total;
return (
<div className="space-y-10">
{showLede ? (
- <RefactoringLede plans={every} summary={summary} indexedFileCount={indexedFileCount} />
+ <RefactoringLede summary={summary} indexedFileCount={indexedFileCount} />
) : null}
- {showLede && structural.length > 0 ? (
- <StartHere plans={structural} onOpen={onOpen} onSeeAll={onSeeStructural} />
+ {showLede && (structuralOpportunities?.length ?? 0) > 0 ? (
+ <StartHere
+ opportunities={structuralOpportunities ?? []}
+ onOpen={onOpen}
+ onSeeAll={onSeeStructural}
+ highlightedId={highlighted}
+ onHighlight={setHighlighted}
+ />
) : null}
<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)]">{sectionTitle}</h2>
<p className="mt-1 max-w-[68ch] text-sm text-[var(--color-text-secondary)]">
- Canonical priority balances benefit and leverage against cost and risk. Every plan opens
- the same inspector with the full explanation.
+ One row is one file&apos;s work, with its steps in dependency-safe order. The
+ recommended order rotates cause and area so the head is a set of choices; every row
+ opens the same inspector with the full explanation.
</p>
</div>
@@ -241,15 +185,11 @@ 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={activeQuery}
- onChange={(e) =>
- controlled
- ? onServerStateChange?.({ query: e.target.value, offset: 0 })
- : setQuery(e.target.value)
- }
- placeholder="Search file or symbol"
+ value={serverState.query}
+ onChange={(e) => onServerStateChange({ query: e.target.value, offset: 0 })}
+ placeholder="Search by file path"
className="pl-9"
- aria-label="Search plans"
+ aria-label="Search opportunities by file path"
/>
</div>
<div className="flex items-center gap-2">
@@ -261,14 +201,9 @@ export function RefactoringBoard({
</label>
<select
id="refactoring-sort"
- value={activeSort}
+ value={serverState.order}
onChange={(e) =>
- controlled
- ? onServerStateChange?.({
- sort: e.target.value as RefactoringSortKey,
- offset: 0,
- })
- : setSortKey(e.target.value as RefactoringSortKey)
+ onServerStateChange({ order: e.target.value as RefactoringOrder, offset: 0 })
}
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)]"
>
@@ -281,58 +216,58 @@ export function RefactoringBoard({
</div>
</div>
- <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
- <div className="flex items-center gap-2">
- <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Effort
- </span>
- {EFFORTS.map((e) => (
- <FilterChip
- key={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]}
- />
- ))}
- </div>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ {/* Selects, not chip rows. Status, effort and confidence are each a
+ single choice over a closed set, which is what a select is for -
+ three rows of chips spent a third of the page saying so, and a
+ chip row implies multi-select to anyone who has used one. The
+ mechanical filter stays a chip because it is a boolean, not a
+ choice among values. */}
+ <FilterSelect
+ label="Status"
+ value={serverState.status}
+ onChange={(v) =>
+ onServerStateChange({ status: v as OpportunityStatus, offset: 0 })
+ }
+ options={TRIAGE_STATUSES.map((o) => ({ value: o.value, label: o.label }))}
+ />
+ <FilterSelect
+ label="Effort"
+ value={serverState.effort ?? ""}
+ onChange={(v) =>
+ onServerStateChange({ effort: (v || null) as EffortBucket | null, offset: 0 })
+ }
+ options={[
+ { value: "", label: "Any" },
+ ...EFFORTS.map((e) => ({ value: e, label: EFFORT_LABEL_LONG[e] })),
+ ]}
+ />
{confidencesPresent.length > 1 ? (
- <div className="flex items-center gap-2">
- <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Confidence
- </span>
- {confidencesPresent.map((c) => (
- <FilterChip
- key={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]}
- />
- ))}
- </div>
+ <FilterSelect
+ label="Confidence"
+ value={serverState.confidence ?? ""}
+ onChange={(v) =>
+ onServerStateChange({ confidence: (v || null) as Confidence | null, offset: 0 })
+ }
+ options={[
+ { value: "", label: "Any" },
+ ...confidencesPresent.map((c) => ({ value: c, label: CONFIDENCE_LABEL[c] })),
+ ]}
+ />
) : null}
+ <FilterChip
+ active={serverState.mechanicalOnly}
+ onClick={() =>
+ onServerStateChange({ mechanicalOnly: !serverState.mechanicalOnly, offset: 0 })
+ }
+ label="Has a mechanical step"
+ />
</div>
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">
- {resultTotal.toLocaleString()} plan{resultTotal === 1 ? "" : "s"}
+ {resultTotal.toLocaleString()} {STATUS_LABEL[serverState.status].toLowerCase()}{" "}
+ opportunit{resultTotal === 1 ? "y" : "ies"}
{filtersActive ? (
<span className="font-normal text-[var(--color-text-tertiary)]"> matching</span>
) : null}
@@ -340,20 +275,16 @@ export function RefactoringBoard({
{filtersActive ? (
<button
type="button"
- onClick={() => {
- if (controlled)
- onServerStateChange?.({
- query: "",
- efforts: [],
- confidences: [],
- offset: 0,
- });
- else {
- setQuery("");
- setEffortSel(new Set());
- setConfSel(new Set());
- }
- }}
+ onClick={() =>
+ onServerStateChange({
+ query: "",
+ status: "open",
+ effort: null,
+ confidence: null,
+ mechanicalOnly: false,
+ offset: 0,
+ })
+ }
className="text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline"
>
Clear filters
@@ -361,53 +292,42 @@ export function RefactoringBoard({
) : null}
</div>
- {processed.length === 0 ? (
+ {opportunities.length === 0 ? (
<p className="border-t border-[var(--color-border-default)] py-10 text-center text-sm text-[var(--color-text-tertiary)]">
- No plans match these filters.
+ {serverState.status === "open"
+ ? "No opportunities match these filters."
+ : `Nothing has been marked ${STATUS_LABEL[serverState.status].toLowerCase()} yet.`}
</p>
) : (
<>
- <PlanRows
- plans={displayed}
+ <OpportunityRows
+ opportunities={opportunities}
onOpen={onOpen}
onAiPrompt={onAiPrompt}
+ onStatusChange={onStatusChange}
fileHref={fileHref}
+ highlightedId={highlighted}
+ onHighlight={setHighlighted}
+ />
+ <PaginationControls
+ offset={serverState.offset}
+ shown={opportunities.length}
+ total={serverState.total}
+ label="opportunities"
+ onPrevious={
+ serverState.offset > 0
+ ? () =>
+ onServerStateChange({
+ offset: Math.max(0, serverState.offset - PAGE_SIZE),
+ })
+ : undefined
+ }
+ onNext={
+ serverState.nextOffset != null
+ ? () => onServerStateChange({ offset: serverState.nextOffset! })
+ : undefined
+ }
/>
- {!controlled && processed.length > visibleCount ? (
- <div className="flex justify-center border-t border-[var(--color-border-default)] pt-5">
- <button
- type="button"
- onClick={() => setVisibleCount((n) => n + PAGE_SIZE)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-4 py-2 text-sm font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]"
- >
- Show {Math.min(PAGE_SIZE, processed.length - visibleCount)} more
- <span className="tabular-nums text-[var(--color-text-tertiary)]">
- · {(processed.length - visibleCount).toLocaleString()} left
- </span>
- </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-lede.tsx b/packages/ui/src/refactoring/refactoring-lede.tsx
index 1cc00d1e6..4aa50e920 100644
--- a/packages/ui/src/refactoring/refactoring-lede.tsx
+++ b/packages/ui/src/refactoring/refactoring-lede.tsx
@@ -3,13 +3,22 @@
*
* The surface used to open on a priority-by-effort scatter with no sentence
* anywhere above it, which made it the only ported page with no lede. The
- * figure alone is also actively misleading here: "1,819 plans" reads as a
- * backlog you are failing at, when 96% of it is small local tidy-ups you do
- * while already in the file.
+ * figure alone is also actively misleading: "1,819 plans" reads as a backlog you
+ * are failing at, when most of it is small local tidy-ups you do while already
+ * in the file.
*
- * So the prose carries the split, and the split is what the rest of the page is
- * organised around. It is measured, not asserted — every number below is
- * counted off the plans passed in.
+ * It counted plans until the page's unit became the opportunity, and then it
+ * counted nothing at all: the page stopped fetching the plan list, so every
+ * figure here silently read zero while the board below it showed 581 rows. The
+ * fix is not to re-fetch plans - it is to say the thing the composed unit
+ * actually knows, which is a better story anyway. Every number comes off the
+ * repository rollup the board already loads, so the lede and the list cannot
+ * disagree.
+ *
+ * The fact worth leading with changed too. It is no longer "most of this is
+ * small" - it is how much of the work is *mechanical*, and how much of it
+ * addresses what is actually wrong with the file. Both are honest and both were
+ * unsayable before composition.
*/
import type { ReactNode } from "react";
@@ -18,21 +27,20 @@ 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, STRUCTURAL_TYPES } from "./types";
-import type { RefactoringPlan, RefactoringSummary } from "@repowise-dev/types/refactoring";
+import { STRUCTURAL_TYPES } from "./types";
+import type { RefactoringOpportunityRollup } 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 repository rollup. Absent or unavailable and the lede does not render. */
+ summary?: RefactoringOpportunityRollup | null | undefined;
+ /** Files in the repo, for the "581 of 4,952 indexed" denominator. Omit and
* the ribbon drops the comparison rather than inventing one. */
indexedFileCount?: number | undefined;
/** Rendered under the prose. */
action?: ReactNode;
}
-/** "46 files to split, 13 cycles to cut and 6 classes doing two jobs" — built
+/** "46 files to split, 13 cycles to cut and 6 classes doing two jobs" - built
* rather than interpolated so a repo with one kind does not read "and". */
function joinPhrases(parts: string[]): string {
if (parts.length <= 1) return parts[0] ?? "";
@@ -47,115 +55,109 @@ 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,
- summary,
- indexedFileCount,
- action,
-}: RefactoringLedeProps) {
- const total = summary?.total ?? plans.length;
- const structural = plans.filter(isStructural);
- 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);
+export function RefactoringLede({ summary, indexedFileCount, action }: RefactoringLedeProps) {
+ // No analysis is a different state from no work, and the board says which.
+ // The lede has nothing to open with either way.
+ if (!summary || summary.status !== "available") return null;
+
+ const total = summary.opportunities_total;
+ const files = summary.files_total;
+ const steps = summary.steps_total;
+ const mechanical = summary.mechanical_steps_total;
+ const judgment = summary.judgment_steps_total;
+
+ const byLead = summary.by_lead_type ?? {};
+ const structuralByType = (STRUCTURAL_TYPES as readonly string[])
+ .map((type) => [type, byLead[type] ?? 0] as const)
+ .filter(([, n]) => n > 0)
+ .sort((a, b) => b[1] - a[1]);
+ const structuralTotal = structuralByType.reduce((n, [, count]) => n + count, 0);
+ const local = Math.max(0, total - structuralTotal);
+
+ const small = summary.by_effort?.S ?? 0;
+ const smallPct = total ? Math.round((small / total) * 100) : 0;
+ const mechanicalPct = steps ? Math.round((mechanical / steps) * 100) : 0;
- 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 primary = summary.addresses_primary_problem;
+ const addressesLead = primary?.yes ?? 0;
+ const addressesSide = primary?.no ?? 0;
+ const addressesUnknown = primary?.unknown ?? 0;
- const byType = new Map<string, number>();
- 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()}`,
- ),
+ structuralByType.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 =
- 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[] = [
{
- label: "Files with a plan",
+ label: "Files with work",
value: formatNumber(files),
- sub: indexedFileCount ? `of ${formatNumber(indexedFileCount)} indexed` : undefined,
+ sub: indexedFileCount ? `of ${formatNumber(indexedFileCount)} indexed` : "one each",
},
{
- label: "Rated small effort",
- value: total ? `${Math.round((small / total) * 100)}%` : "0%",
- sub: `${formatNumber(small)} plan${small === 1 ? "" : "s"}`,
+ label: "Steps to apply",
+ value: formatNumber(steps),
+ sub: `${formatNumber(mechanical)} mechanical, ${formatNumber(judgment)} judgment`,
},
{
- label: "Recover health",
- value: formatNumber(recovers),
- sub: "+0.1 or better",
+ label: "Rated small effort",
+ value: total ? `${smallPct}%` : "0%",
+ sub: `${formatNumber(small)} opportunit${small === 1 ? "y" : "ies"}`,
},
{
label: "Change a file's shape",
value: formatNumber(structuralTotal),
- sub:
- plottable < structural.length
- ? `${formatNumber(plottable)} measured among displayed leads`
- : `${formatNumber(structural.length)} displayed leads`,
+ sub: structuralTotal ? "structural, and they lead the page" : "none in this repo",
},
];
return (
<div className="space-y-6">
<PageLede
- label="Open plans"
+ label="Open opportunities"
value={formatNumber(total)}
- unit={files ? `across ${formatNumber(files)} file${files === 1 ? "" : "s"}` : undefined}
+ unit={files ? `one per file, across ${formatNumber(files)} file${files === 1 ? "" : "s"}` : undefined}
layout="beside"
action={action}
figureFooter={
- structuralTotal > 0 ? (
+ steps > 0 ? (
<p className="text-caption text-[var(--color-text-tertiary)]">
- {formatNumber(structuralTotal)} change a file&apos;s shape
- {performanceTotal
- ? `; ${formatNumber(performanceTotal)} address a causal performance opportunity.`
- : ". The rest are local."}
+ {formatNumber(steps)} step{steps === 1 ? "" : "s"} in total, so most files carry more
+ than one.
</p>
) : undefined
}
>
<p>
<span className="font-medium text-[var(--color-text-primary)]">
- Most of this list is small.
+ {mechanicalPct}% of the steps are mechanical.
</span>{" "}
- {formatNumber(local)} plan{local === 1 ? "" : "s"} lift a slice of a long function or
- dedupe a repeated block, and {total ? Math.round((small / total) * 100) : 0}% are rated
- small effort. They are worth doing when you are already in the file, and they are not
- worth a planning meeting.
+ {formatNumber(mechanical)} of {formatNumber(steps)} have every proof obligation met, so
+ they are safe to hand to an agent as written. The other {formatNumber(judgment)} change
+ where something lives or what it is called, and want a person&apos;s judgment first.
</p>
- {performanceTotal > 0 ? (
+ {addressesSide > 0 || addressesLead > 0 ? (
<p>
<span className="font-medium text-[var(--color-text-primary)]">
- {formatNumber(performanceTotal)} performance plan
- {performanceTotal === 1 ? "" : "s"}.
+ {formatNumber(addressesLead)} address the file&apos;s main problem.
</span>{" "}
- These preserve detector-native benefit even when defect-health recovery is zero.
+ {formatNumber(addressesSide)} do not - they are real work, but not the biggest cost in
+ that file
+ {addressesUnknown > 0
+ ? `, and for ${formatNumber(addressesUnknown)} no dominant problem was recorded to compare against`
+ : ""}
+ . Each row says which, so nothing here claims to fix more than it does.
+ </p>
+ ) : null}
+ {local > 0 ? (
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ Most of this list is local.
+ </span>{" "}
+ {formatNumber(local)} opportunit{local === 1 ? "y lifts" : "ies lift"} a slice of a long
+ function or tidy a repeated block, and {smallPct}% are rated small effort. They are
+ worth doing when you are already in the file, and they are not worth a planning meeting.
</p>
) : null}
{structuralTotal > 0 ? (
@@ -167,13 +169,6 @@ export function RefactoringLede({
{structuralPhrase}. These change how the codebase is shaped, so they lead the page.
</p>
) : null}
- {bestGain > 0 ? (
- <p>
- Health recovered tops out at +{bestGain.toFixed(1)} per plan and{" "}
- {formatNumber(negligible)} recover under half a point, so it ranks poorly on its own.
- The order below weighs how depended-upon the file is and how much rides along with it.
- </p>
- ) : null}
</PageLede>
<StatRibbon stats={stats} />
diff --git a/packages/ui/src/refactoring/refactoring-plan-card.tsx b/packages/ui/src/refactoring/refactoring-plan-card.tsx
deleted file mode 100644
index c337e5b6e..000000000
--- a/packages/ui/src/refactoring/refactoring-plan-card.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-"use client";
-
-import { Layers, Sparkles } from "lucide-react";
-import { CONFIDENCE_DOT, CONFIDENCE_LABEL, EFFORT_LABEL, typeAccent, typeMeta } from "./meta";
-import {
- blastCount,
- planSynopsis,
-} from "./types";
-import type {
- Confidence,
- EffortBucket,
- RefactoringPlan,
-} from "@repowise-dev/types/refactoring";
-
-export interface RefactoringPlanCardProps {
- plan: RefactoringPlan;
- /** Open the visual plan inspector for this plan. */
- onOpen?: ((plan: RefactoringPlan) => void) | undefined;
- /** Open the AI-prompt modal for this plan. */
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- /** Flash-highlight (e.g. after a quadrant dot click scrolled to it). */
- highlighted?: boolean;
-}
-
-function fileParts(path: string): { name: string; dir: string } {
- const parts = path.split("/");
- const name = parts[parts.length - 1] ?? path;
- const dirParts = parts.slice(0, -1);
- const dir = dirParts.length <= 3 ? dirParts.join("/") : `…/${dirParts.slice(-3).join("/")}`;
- return { name, dir };
-}
-
-/**
- * A compact, clickable plan card — file first, with a type-colored rail so the
- * grid reads at a glance. Deliberately light: the heavy visual lives in the
- * modal that opens on click, so a long grid stays performant.
- */
-export function RefactoringPlanCard({
- plan,
- onOpen,
- onAiPrompt,
- highlighted = false,
-}: RefactoringPlanCardProps) {
- const meta = typeMeta(plan.refactoring_type);
- const accent = typeAccent(plan.refactoring_type);
- const { Icon } = meta;
- const blast = blastCount(plan);
- const effort = (plan.effort_bucket || "M") as EffortBucket;
- const confidence = (plan.confidence || "medium") as Confidence;
- const { name, dir } = fileParts(plan.file_path);
-
- return (
- <article
- data-refactoring-plan={plan.id}
- className={`group relative flex flex-col overflow-hidden rounded-2xl border bg-[var(--color-bg-surface)] transition-all ${
- highlighted
- ? "border-[var(--color-accent-primary)] ring-1 ring-[var(--color-accent-primary)]/30"
- : "border-[var(--color-border-default)] hover:border-[var(--color-border-hover)] hover:shadow-sm"
- }`}
- >
- {/* type-colored rail — the at-a-glance differentiator */}
- <span aria-hidden className="absolute inset-y-0 left-0 w-1" style={{ backgroundColor: accent }} />
-
- <button
- type="button"
- onClick={onOpen ? () => onOpen(plan) : undefined}
- className="flex flex-1 flex-col gap-2.5 py-4 pl-5 pr-4 text-left"
- disabled={!onOpen}
- aria-label={`Open ${meta.label} plan for ${plan.file_path}`}
- >
- {/* file first */}
- <div className="min-w-0">
- <h3
- className="truncate text-sm font-semibold text-[var(--color-text-primary)]"
- title={plan.file_path}
- >
- {name}
- </h3>
- {dir ? (
- <p className="truncate font-mono text-[11px] text-[var(--color-text-tertiary)]">{dir}</p>
- ) : null}
- </div>
-
- {/* type + one-line synopsis */}
- <div className="flex items-center gap-2">
- <span
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-semibold"
- style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}
- >
- <Icon className="h-3.5 w-3.5" />
- {meta.label}
- </span>
- <span className="min-w-0 flex-1 truncate text-xs text-[var(--color-text-secondary)]">
- {planSynopsis(plan)}
- </span>
- </div>
-
- {/* metric footer */}
- <div className="mt-auto flex items-center gap-x-3 gap-y-1.5 border-t border-[var(--color-border-default)] pt-3 text-[11px] text-[var(--color-text-tertiary)]">
- <span title={`Effort: ${EFFORT_LABEL[effort]}`} className="inline-flex items-center gap-1">
- <span className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 font-medium tabular-nums text-[var(--color-text-secondary)]">
- {effort}
- </span>
- </span>
- {blast > 0 ? (
- <span className="inline-flex items-center gap-1" title="Files this refactoring touches">
- <Layers className="h-3.5 w-3.5" />
- {blast}
- </span>
- ) : null}
- <span
- className="inline-flex items-center gap-1"
- title={`Detector confidence: ${CONFIDENCE_LABEL[confidence]}`}
- >
- <span className={`h-1.5 w-1.5 rounded-full ${CONFIDENCE_DOT[confidence]}`} />
- {CONFIDENCE_LABEL[confidence]}
- </span>
- {plan.impact_delta > 0 ? (
- <span
- className="ml-auto inline-flex items-center gap-1 rounded-full bg-[var(--color-success)]/10 px-2 py-0.5 font-semibold tabular-nums text-[var(--color-success)]"
- title="Health recovered if applied"
- >
- +{plan.impact_delta.toFixed(1)}
- </span>
- ) : null}
- </div>
- </button>
-
- {onAiPrompt ? (
- <div className="border-t border-[var(--color-border-default)] py-2 pl-5 pr-4">
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onAiPrompt(plan);
- }}
- className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-semibold text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-muted)]"
- title="Open a ready-to-paste prompt for your AI coding agent"
- >
- <Sparkles className="h-3.5 w-3.5" />
- AI prompt
- </button>
- </div>
- ) : null}
- </article>
- );
-}
diff --git a/packages/ui/src/refactoring/start-here.tsx b/packages/ui/src/refactoring/start-here.tsx
index f02e15575..bda548fbe 100644
--- a/packages/ui/src/refactoring/start-here.tsx
+++ b/packages/ui/src/refactoring/start-here.tsx
@@ -1,24 +1,24 @@
"use client";
/**
- * The top of the Refactoring page: the structural plans as a field, and the
- * handful worth doing first as ranked rows underneath.
+ * The top of the Refactoring page: the structural opportunities as a field, and
+ * the handful worth doing first as ranked rows underneath.
*
* These are one section rather than two because they answer different halves of
- * the same question and neither is sufficient alone. The map says which plans
- * are expensive and far-reaching, which is a shape a sorted column cannot carry
- * — a 1,417-line file with 11 dependents and a 1,052-line file with 195 are
+ * the same question and neither is sufficient alone. The field says which work
+ * is expensive and far-reaching, which is a shape a sorted column cannot carry
+ * - a 1,417-line file with 11 dependents and a 1,052-line file with 195 are
* neighbours in a list and opposite corners here. The rows say what to do
- * first, and carry the evidence sentence a dot has no room for.
+ * first, and carry the step count and the lead cause a mark has no room for.
*
* They share hover state in both directions, so the two halves read as one
* object: pointing at a mark lights its row, and pointing at a row lights its
* mark.
*
- * Below `MAP_MIN_POINTS` plottable plans the map does not render. A scatter
- * with four dots asks a reader to decode two axes to learn less than four rows
- * already told them, and a repo with no large files would otherwise get an
- * empty centrepiece with a confident heading over it.
+ * Below `MAP_MIN_POINTS` plottable opportunities the field does not render. A
+ * scatter with four marks asks a reader to decode two axes to learn less than
+ * four rows already told them, and a repo with no large files would otherwise
+ * get an empty centrepiece with a confident heading over it.
*/
import * as React from "react";
@@ -26,22 +26,25 @@ import * as React from "react";
import { formatNumber } from "../lib/format";
import { StructuralMap } from "./structural-map";
import { typeMeta } from "./meta";
+import { MAP_MIN_POINTS } from "./types";
import {
- MAP_MIN_POINTS,
- planPoint,
- planReason,
- planSynopsis,
-} from "./types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+ addressesPrimaryShort,
+ stepSummary,
+ structuralMarks,
+ type StructuralMark,
+} from "./opportunity";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
export interface StartHereProps {
- /** Structural plans, already in rank order. */
- plans: RefactoringPlan[];
- onOpen?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Structural opportunities, already in rank order. */
+ opportunities: RefactoringOpportunity[];
+ onOpen?: ((opportunity: RefactoringOpportunity) => void) | undefined;
/** Jump to the full list filtered to structural types. */
onSeeAll?: (() => void) | undefined;
- /** How many ranked rows to show under the map. */
+ /** How many ranked rows to show under the field. */
leadCount?: number;
+ highlightedId?: string | null | undefined;
+ onHighlight?: ((id: string | null) => void) | undefined;
}
const EFFORT_WORD: Record<string, string> = {
@@ -51,14 +54,38 @@ const EFFORT_WORD: Record<string, string> = {
XL: "Extra large",
};
-export function StartHere({ plans, onOpen, onSeeAll, leadCount = 5 }: StartHereProps) {
- const [highlighted, setHighlighted] = React.useState<string | null>(null);
+export function StartHere({
+ opportunities,
+ onOpen,
+ onSeeAll,
+ leadCount = 5,
+ highlightedId,
+ onHighlight,
+}: StartHereProps) {
+ const [localHighlight, setLocalHighlight] = React.useState<string | null>(null);
+ const highlighted = highlightedId !== undefined ? highlightedId : localHighlight;
+ const setHighlighted = onHighlight ?? setLocalHighlight;
- const plottable = React.useMemo(() => plans.filter((p) => planPoint(p) !== null), [plans]);
- const showMap = plottable.length >= MAP_MIN_POINTS;
- const lead = plans.slice(0, leadCount);
+ const marks = React.useMemo(() => structuralMarks(opportunities), [opportunities]);
+ const showMap = marks.length >= MAP_MIN_POINTS;
+ const lead = opportunities.slice(0, leadCount);
+ const dropped = opportunities.length - marks.length;
- if (plans.length === 0) return null;
+ const byId = React.useMemo(() => {
+ const map = new Map<string, RefactoringOpportunity>();
+ for (const item of opportunities) map.set(item.opportunity_id, item);
+ return map;
+ }, [opportunities]);
+
+ const onSelectMark = React.useCallback(
+ (mark: StructuralMark) => {
+ const item = byId.get(mark.opportunityId);
+ if (item && onOpen) onOpen(item);
+ },
+ [byId, onOpen],
+ );
+
+ if (opportunities.length === 0) return null;
return (
<section className="space-y-5 border-t border-[var(--color-border-default)] pt-8">
@@ -67,8 +94,8 @@ export function StartHere({ plans, onOpen, onSeeAll, leadCount = 5 }: StartHereP
<h2 className="text-lg font-semibold text-[var(--color-text-primary)]">Start here</h2>
<p className="mt-1 max-w-[68ch] text-sm text-[var(--color-text-secondary)]">
{showMap
- ? "Up the page is a bigger file to work through; right is more code that imports it. Top right is where a morning changes the most, and where the back-compat shim matters."
- : "The plans that change how the codebase is laid out, ranked by how depended-upon the file is and how much rides along with it."}
+ ? "Up the page is a bigger file to work through; right is more code that imports it. Top right is where a morning changes the most, and where the back-compat shim matters. One mark is one file."
+ : "The work that changes how the codebase is laid out, ranked by how depended-upon the file is and how much rides along with it."}
</p>
</div>
{onSeeAll ? (
@@ -77,37 +104,37 @@ export function StartHere({ plans, onOpen, onSeeAll, leadCount = 5 }: StartHereP
onClick={onSeeAll}
className="shrink-0 text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline"
>
- See all {formatNumber(plans.length)} structural
+ See all {formatNumber(opportunities.length)} structural
</button>
) : null}
</div>
{showMap ? (
<StructuralMap
- plans={plans}
- onSelect={onOpen}
+ marks={marks}
+ dropped={dropped}
+ onSelect={onOpen ? onSelectMark : undefined}
highlightedId={highlighted}
onHighlight={setHighlighted}
/>
) : null}
<div>
- {lead.map((plan, i) => {
- const meta = typeMeta(plan.refactoring_type);
- const reason = planReason(plan);
- const effort = EFFORT_WORD[plan.effort_bucket || "M"] ?? plan.effort_bucket;
- const lit = plan.id === highlighted;
+ {lead.map((item, i) => {
+ const meta = typeMeta(item.lead_refactoring_type || "");
+ const effort = EFFORT_WORD[item.effort_bucket] ?? item.effort_bucket;
+ const lit = item.opportunity_id === highlighted;
return (
<button
- key={plan.id}
+ key={item.opportunity_id}
type="button"
- onClick={onOpen ? () => onOpen(plan) : undefined}
+ onClick={onOpen ? () => onOpen(item) : undefined}
disabled={!onOpen}
- onMouseEnter={() => setHighlighted(plan.id)}
+ onMouseEnter={() => setHighlighted(item.opportunity_id)}
onMouseLeave={() => setHighlighted(null)}
- onFocus={() => setHighlighted(plan.id)}
+ onFocus={() => setHighlighted(item.opportunity_id)}
onBlur={() => setHighlighted(null)}
- className={`group grid w-full grid-cols-[28px_minmax(0,1fr)] items-start gap-4 border-t border-[var(--color-border-default)] px-3 py-4 text-left transition-colors first:border-t-0 md:grid-cols-[28px_minmax(0,1fr)_150px] md:items-center ${
+ className={`group grid w-full grid-cols-[28px_minmax(0,1fr)] items-start gap-4 border-t border-[var(--color-border-default)] px-3 py-4 text-left transition-colors first:border-t-0 md:grid-cols-[28px_minmax(0,1fr)_170px] md:items-center ${
lit ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]"
}`}
>
@@ -116,23 +143,26 @@ export function StartHere({ plans, onOpen, onSeeAll, leadCount = 5 }: StartHereP
</span>
<span className="min-w-0">
<span className="block text-[15px] font-semibold text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
- {planSynopsis(plan) || meta.label}
+ {meta.label} · {item.file_path.split("/").pop()}
</span>
{/* Full path, no ellipsis: a truncated title reports a layout
decision to the reader as missing content. */}
<span className="mt-0.5 block break-all font-mono text-[11px] text-[var(--color-text-tertiary)]">
- {plan.file_path}
+ {item.file_path}
+ </span>
+ <span className="mt-1.5 block max-w-[70ch] text-[13px] text-[var(--color-text-secondary)]">
+ {stepSummary(item)} ·{" "}
+ {addressesPrimaryShort(item.addresses_primary_problem).toLowerCase()}
</span>
- {reason ? (
- <span className="mt-1.5 block max-w-[70ch] text-[13px] text-[var(--color-text-secondary)]">
- {reason}
- </span>
- ) : null}
</span>
<span className="mt-2 block text-xs text-[var(--color-text-tertiary)] md:mt-0 md:text-right">
{effort} effort
<br />
- {plan.confidence === "high" ? "High" : plan.confidence === "low" ? "Low" : "Medium"}{" "}
+ {item.confidence === "high"
+ ? "High"
+ : item.confidence === "low"
+ ? "Low"
+ : "Medium"}{" "}
confidence
</span>
</button>
diff --git a/packages/ui/src/refactoring/structural-map.tsx b/packages/ui/src/refactoring/structural-map.tsx
index 88855bce0..15422933e 100644
--- a/packages/ui/src/refactoring/structural-map.tsx
+++ b/packages/ui/src/refactoring/structural-map.tsx
@@ -1,41 +1,68 @@
"use client";
/**
- * The structural plans as a field: file size against how much imports the file.
+ * The structural opportunities as a field: file size against how much imports
+ * the file. One mark per file, because one opportunity is one file's work.
*
* This replaces a priority-by-effort quadrant that failed its own test. On a
* real index 89% of plans are rated small effort, so the effort axis put almost
* everything in one column and three of the four quadrant labels annotated
* empty space; it also plotted 120 dots of 1,819 and said so only in a caption
- * inside the canvas. Restricting the field to the structural plans is what
- * makes a scatter honest here — those spread across both axes (dependents 1 to
- * 195, sizes 19 to 1,417 lines on this repo), and there are few enough to draw
- * every one.
+ * inside the canvas. Restricting the field to the structural set is what makes
+ * a scatter honest here - those spread across both axes (dependents 1 to 195,
+ * sizes 19 to 1,417 lines on this repo), and there are few enough to draw every
+ * one.
*
* Three things it does that the quadrant did not, all from the design language:
*
- * - **Type is a shape, not a hue.** Six `--color-refactor-*` accents separated
- * categories where two types are 96% of the data, and one of them was the
- * same green as the health badge beside it.
* - **The viewBox tracks the container.** A fixed `0 0 1100 400` at
* `width:100%` scales its own text: 12px labels render at 4px on a phone and
* at 14px on a wide desktop. One unit is one CSS pixel at every width here.
* - **Chrome goes around it.** The key, the counts and the bound live in a
* hairline row underneath; only the hover card tracks the pointer, and no
* `<title>` child fights it for the tooltip.
+ * - **Shape carries type; hue only ranks attention.** Four structural types,
+ * four distinct marks - circle, diamond, triangle, square - so type survives
+ * with no colour at all. On top of that the two most common types take the
+ * accent pair (orange, then plum) and the rest recede into neutrals, which is
+ * the salience pattern `code-evolution-chart.tsx` already uses.
+ *
+ * Which type gets which hue is *derived from the data in hand*, never fixed:
+ * split_file is 74% of this repo's structural work, but a codebase whose
+ * cycles outnumber its oversized files would otherwise get its dominant
+ * category painted as the rare one. The earlier objection to colour here -
+ * six `--color-refactor-*` accents separating categories where two types were
+ * 96% of the data, one of them the same green as the health badge beside it -
+ * was against six hues over the whole plan list, and does not reach a two-hue
+ * pair over the four structural types. The sequential `--color-ramp-*` steps
+ * stay out of it: globals.css reserves them for magnitude, and they would add
+ * orange rather than reduce it.
+ *
+ * Every mark also carries a separating stroke, which is what actually makes
+ * it visible: the neutral tiers sit under 2.5:1 against the page in both
+ * themes, and a fill alone would draw the common types and quietly omit the
+ * rare ones. The legend names every shape, and says out loud when a type has
+ * receded into grey, so nothing depends on hue to be identified.
*/
import * as React from "react";
import { formatNumber } from "../lib/format";
import { typeMeta } from "./meta";
-import { planPoint } from "./types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+import {
+ MARK_STROKE,
+ isRecededType,
+ salienceFill,
+ salienceOrder,
+ type StructuralMark,
+} from "./opportunity";
export interface StructuralMapProps {
- /** Structural plans. Those without both figures are dropped and counted. */
- plans: RefactoringPlan[];
- onSelect?: ((plan: RefactoringPlan) => void) | undefined;
+ /** One per file. Build with `structuralMarks`. */
+ marks: StructuralMark[];
+ /** Opportunities that had no size or dependency figures to plot. */
+ dropped?: number;
+ onSelect?: ((mark: StructuralMark) => void) | undefined;
/** Lit from the row list, so hovering either half highlights the other. */
highlightedId?: string | null | undefined;
onHighlight?: ((id: string | null) => void) | undefined;
@@ -49,22 +76,33 @@ const PAD_B = 46;
/** Marks are ~11px across, so the pointer needs a target bigger than the ink. */
const HIT_RADIUS = 12;
-/** A deterministic sub-pixel offset, so two plans on one file do not stack into
- * a single mark. Two detectors firing on the same file is common: a file big
- * enough to split is often also in a cycle. */
+/** A deterministic sub-pixel offset, so two files of the same size and reach do
+ * not stack into a single mark. */
function jitter(seed: string): number {
let h = 0;
for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
return ((h % 9) - 4) * 1.1;
}
+/**
+ * One shape per structural type.
+ *
+ * Four types, four marks. `extract_class` and `move_method` used to share the
+ * triangle, which made two of the four indistinguishable on the only channel
+ * then carrying type at all. Circle / diamond / triangle / square is the
+ * conventional scatter set and stays legible down to a 5px radius.
+ */
function markPath(type: string, cx: number, cy: number, r: number): string | null {
if (type === "break_cycle") {
return `M${cx} ${cy - r * 1.15}L${cx + r * 1.15} ${cy}L${cx} ${cy + r * 1.15}L${cx - r * 1.15} ${cy}Z`;
}
- if (type === "extract_class" || type === "move_method") {
+ if (type === "extract_class") {
return `M${cx} ${cy - r * 1.25}L${cx + r * 1.2} ${cy + r * 0.95}L${cx - r * 1.2} ${cy + r * 0.95}Z`;
}
+ if (type === "move_method") {
+ const h = r * 0.95;
+ return `M${cx - h} ${cy - h}L${cx + h} ${cy - h}L${cx + h} ${cy + h}L${cx - h} ${cy + h}Z`;
+ }
return null; // split_file draws as a circle
}
@@ -81,7 +119,8 @@ function median(values: number[]): number {
}
export function StructuralMap({
- plans,
+ marks,
+ dropped = 0,
onSelect,
highlightedId,
onHighlight,
@@ -103,30 +142,19 @@ export function StructuralMap({
return () => ro.disconnect();
}, []);
- const points = React.useMemo(
- () =>
- plans
- .map((plan) => {
- const point = planPoint(plan);
- return point ? { plan, ...point } : null;
- })
- .filter((p): p is { plan: RefactoringPlan; x: number; y: number } => p !== null),
- [plans],
- );
-
- const dropped = plans.length - points.length;
+ const order = React.useMemo(() => salienceOrder(marks), [marks]);
const geometry = React.useMemo(() => {
- if (points.length === 0 || width === 0) return null;
+ if (marks.length === 0 || width === 0) return null;
const W = width;
const H = Math.max(320, Math.min(460, Math.round(W * 0.44)));
const plotW = W - PAD_L - PAD_R;
const plotH = H - PAD_T - PAD_B;
- const xMax = Math.max(...points.map((p) => p.x));
- const yMax = axisCeiling(Math.max(...points.map((p) => p.y)));
- // Dependents are heavily right-skewed — a median of 8 against a max of 195
- // on this repo — so a linear axis crushes most of the field into the left
+ const xMax = Math.max(...marks.map((p) => p.x));
+ const yMax = axisCeiling(Math.max(...marks.map((p) => p.y)));
+ // Dependents are heavily right-skewed - a median of 8 against a max of 195
+ // on this repo - so a linear axis crushes most of the field into the left
// fifth. Log spreads it without hiding the outlier.
const logMax = Math.log(Math.max(xMax, 2));
const xScale = (v: number) => PAD_L + (Math.log(Math.max(v, 1)) / logMax) * plotW;
@@ -144,15 +172,16 @@ export function StructuralMap({
yScale,
xTicks,
yTicks,
- medianX: median(points.map((p) => p.x)),
- medianY: median(points.map((p) => p.y)),
+ medianX: median(marks.map((p) => p.x)),
+ medianY: median(marks.map((p) => p.y)),
};
- }, [points, width]);
+ }, [marks, width]);
- const hovered = points.find((p) => p.plan.id === highlightedId) ?? null;
+ const hovered = marks.find((p) => p.opportunityId === highlightedId) ?? null;
const byType = new Map<string, number>();
- for (const p of points) byType.set(p.plan.refactoring_type, (byType.get(p.plan.refactoring_type) ?? 0) + 1);
+ for (const p of marks) byType.set(p.leadType, (byType.get(p.leadType) ?? 0) + 1);
+ const anyReceded = [...byType.keys()].some((type) => isRecededType(type, order));
return (
<div>
@@ -162,8 +191,11 @@ export function StructuralMap({
viewBox={`0 0 ${geometry.W} ${geometry.H}`}
height={geometry.H}
className="block w-full text-[var(--color-text-primary)]"
- role="img"
- aria-label={`${points.length} structural refactoring plans plotted on file size against the number of files that import them. The ranked list below carries the same plans.`}
+ // A group, not an image. `role="img"` tells assistive technology to
+ // treat the subtree as one flattened graphic, which would hide the
+ // marks - and every mark here is a button.
+ role="group"
+ aria-label={`${marks.length} structural refactoring opportunities, one per file, plotted on file size against the number of files that import them. The ranked list below carries the same opportunities.`}
>
{geometry.yTicks.map((t) => (
<g key={`y-${t}`}>
@@ -236,49 +268,63 @@ export function StructuralMap({
Lines in the file
</text>
- {points.map(({ plan, x, y }) => {
- const cx = geometry.xScale(x) + jitter(plan.id);
- const cy = geometry.yScale(y);
- const lit = plan.id === highlightedId;
+ {marks.map((mark) => {
+ const cx = geometry.xScale(mark.x) + jitter(mark.opportunityId);
+ const cy = geometry.yScale(mark.y);
+ const lit = mark.opportunityId === highlightedId;
const r = lit ? 7 : 5.2;
- const path = markPath(plan.refactoring_type, cx, cy, r);
- const meta = typeMeta(plan.refactoring_type);
+ const path = markPath(mark.leadType, cx, cy, r);
+ const meta = typeMeta(mark.leadType);
+ const fill = salienceFill(mark.leadType, order);
+ const steps = `${mark.stepCount} step${mark.stepCount === 1 ? "" : "s"}`;
return (
<g
- key={plan.id}
+ key={mark.opportunityId}
role={onSelect ? "button" : undefined}
tabIndex={onSelect ? 0 : undefined}
- aria-label={`${meta.label}, ${plan.file_path}, ${formatNumber(x)} dependent files, ${formatNumber(y)} lines`}
- className={onSelect ? "cursor-pointer outline-none" : "outline-none"}
- onMouseEnter={() => onHighlight?.(plan.id)}
+ aria-label={`${meta.label}, ${mark.filePath}, ${steps}, ${formatNumber(mark.x)} dependent files, ${formatNumber(mark.y)} lines`}
+ className={
+ onSelect
+ ? "cursor-pointer outline-none [&:focus-visible_.focus-ring]:opacity-100"
+ : "outline-none"
+ }
+ onMouseEnter={() => onHighlight?.(mark.opportunityId)}
onMouseLeave={() => onHighlight?.(null)}
- onFocus={() => onHighlight?.(plan.id)}
+ onFocus={() => onHighlight?.(mark.opportunityId)}
onBlur={() => onHighlight?.(null)}
- onClick={onSelect ? () => onSelect(plan) : undefined}
+ onClick={onSelect ? () => onSelect(mark) : undefined}
onKeyDown={
onSelect
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
- onSelect(plan);
+ onSelect(mark);
}
}
: undefined
}
>
+ {/* Fill ranks attention; the stroke is what makes the mark
+ exist. A receded type's fill is under 2:1 against the page
+ in both themes, so without an outline the tail of the
+ distribution would simply not be drawn. */}
{path ? (
<path
d={path}
- fill="var(--color-accent-fill)"
- fillOpacity={lit ? 0.95 : 0.72}
+ fill={fill}
+ fillOpacity={lit ? 1 : 0.9}
+ stroke={MARK_STROKE}
+ strokeWidth={1}
/>
) : (
<circle
cx={cx}
cy={cy}
r={r}
- fill="var(--color-accent-fill)"
- fillOpacity={lit ? 0.95 : 0.72}
+ fill={fill}
+ fillOpacity={lit ? 1 : 0.9}
+ stroke={MARK_STROKE}
+ strokeWidth={1}
/>
)}
{lit ? (
@@ -287,10 +333,22 @@ export function StructuralMap({
cy={cy}
r={r + 4}
fill="none"
- stroke="var(--color-accent-fill)"
+ stroke={fill}
strokeOpacity={0.5}
/>
) : null}
+ {/* Keyboard focus needs its own ring: the lit halo is shared
+ with hover, and on a neutral-filled mark it is too faint
+ to read as "this is where the keyboard is". */}
+ <circle
+ className="focus-ring opacity-0"
+ cx={cx}
+ cy={cy}
+ r={r + 6}
+ fill="none"
+ stroke="var(--color-accent-primary)"
+ strokeWidth={2}
+ />
<circle cx={cx} cy={cy} r={HIT_RADIUS} fill="transparent" />
</g>
);
@@ -302,7 +360,7 @@ export function StructuralMap({
{hovered && geometry ? (
<MapCard
- plan={hovered.plan}
+ mark={hovered}
x={geometry.xScale(hovered.x)}
y={geometry.yScale(hovered.y)}
width={geometry.W}
@@ -313,51 +371,72 @@ export function StructuralMap({
<div className="mt-2.5 flex flex-wrap items-center gap-x-5 gap-y-2 border-t border-[var(--color-border-default)] pt-3">
{[...byType.entries()]
.sort((a, b) => b[1] - a[1])
- .map(([type, count]) => (
- <span
- key={type}
- className="inline-flex items-center gap-2 text-xs text-[var(--color-text-secondary)]"
- >
- <svg width="13" height="13" aria-hidden className="shrink-0">
- {markPath(type, 6.5, 6.5, 4.6) ? (
- <path d={markPath(type, 6.5, 6.5, 4.6)!} fill="var(--color-accent-fill)" fillOpacity={0.8} />
- ) : (
- <circle cx="6.5" cy="6.5" r="4.6" fill="var(--color-accent-fill)" fillOpacity={0.8} />
- )}
- </svg>
- {typeMeta(type).label}
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- {count}
+ .map(([type, count]) => {
+ const fill = salienceFill(type, order);
+ const path = markPath(type, 6.5, 6.5, 4.6);
+ return (
+ <span
+ key={type}
+ className="inline-flex items-center gap-2 text-xs text-[var(--color-text-secondary)]"
+ >
+ <svg width="13" height="13" aria-hidden className="shrink-0">
+ {path ? (
+ <path d={path} fill={fill} fillOpacity={0.9} stroke={MARK_STROKE} />
+ ) : (
+ <circle
+ cx="6.5"
+ cy="6.5"
+ r="4.6"
+ fill={fill}
+ fillOpacity={0.9}
+ stroke={MARK_STROKE}
+ />
+ )}
+ </svg>
+ {typeMeta(type).label}
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {count}
+ </span>
</span>
- </span>
- ))}
+ );
+ })}
{/* Say the bound. A view that quietly covers part of its subject reads
as covering all of it. */}
{dropped > 0 ? (
<span className="ml-auto text-xs text-[var(--color-text-tertiary)]">
- {formatNumber(dropped)} not plotted — no size or dependency figures yet
+ {formatNumber(dropped)} not plotted - no size or dependency figures yet
</span>
) : null}
</div>
+
+ {anyReceded ? (
+ // The badges below give every type its own hue. Without this a reader
+ // sees Split File orange here and blue two inches down and reasonably
+ // concludes they are different things.
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ Shape is the type, and the key above names every shape. Colour ranks how much of this
+ repo&apos;s structural work each type is, so the rarer types sit in grey.
+ </p>
+ ) : null}
</div>
);
}
-/** The hover card, placed from the point's own coordinates. Flips to the other
+/** The hover card, placed from the mark's own coordinates. Flips to the other
* side near the right edge so it never leaves the plot. */
function MapCard({
- plan,
+ mark,
x,
y,
width,
}: {
- plan: RefactoringPlan;
+ mark: StructuralMark;
x: number;
y: number;
width: number;
}) {
const flip = x > width - 240;
- const meta = typeMeta(plan.refactoring_type);
+ const meta = typeMeta(mark.leadType);
return (
<div
className="pointer-events-none absolute z-10 w-[220px] rounded-lg border border-[var(--color-border-hover)] bg-[var(--color-bg-surface)] px-3 py-2 shadow-md"
@@ -367,13 +446,15 @@ function MapCard({
top: Math.max(0, y - 62),
}}
>
- <div className="text-[11px] text-[var(--color-text-secondary)]">{meta.label}</div>
+ <div className="text-[11px] text-[var(--color-text-secondary)]">
+ {meta.label} · {mark.stepCount} step{mark.stepCount === 1 ? "" : "s"}
+ </div>
<div className="mt-0.5 break-all font-mono text-xs font-semibold text-[var(--color-text-primary)]">
- {plan.file_path.split("/").pop()}
+ {mark.filePath.split("/").pop()}
</div>
<div className="mt-1.5 border-t border-[var(--color-border-default)] pt-1.5 text-[11px] tabular-nums text-[var(--color-text-secondary)]">
- {formatNumber(plan.file_nloc ?? 0)} lines · {formatNumber(plan.dependents ?? 0)} dependent
- {(plan.dependents ?? 0) === 1 ? "" : "s"}
+ {formatNumber(mark.y)} lines · {formatNumber(mark.x)} dependent
+ {mark.x === 1 ? "" : "s"}
</div>
</div>
);
diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.ts
index 16ce78fbf..34edd5c60 100644
--- a/packages/vscode/src/core/webviewApi.ts
+++ b/packages/vscode/src/core/webviewApi.ts
@@ -22,13 +22,18 @@ import {
searchNodes,
} from "@repowise-dev/api-client/graph";
import {
+ getRefactoringOpportunities,
+ getRefactoringOpportunity,
getRefactoringPlan,
getRefactoringTargets,
} from "@repowise-dev/api-client/refactoring";
import { listDecisions } from "@repowise-dev/api-client/decisions";
import { getPageById, listAllPages } from "@repowise-dev/api-client/pages";
import { getRiskRange } from "@repowise-dev/api-client/risk";
-import { buildRefactoringPlanPrompt } from "@repowise-dev/ui/health/ai-prompt-builder";
+import {
+ buildRefactoringOpportunityPrompt,
+ buildRefactoringPlanPrompt,
+} from "@repowise-dev/ui/health/ai-prompt-builder";
import { CONFIG_SECTION } from "../constants";
import {
SETTING_KEYS,
@@ -283,10 +288,33 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostAp
executionFlows: () => cached("graph:flows", (id) => getExecutionFlows(id)),
// Refactoring
- refactoringTargets: (filePath) =>
- cached(`refactor:targets:${filePath ?? ""}`, (id) =>
- getRefactoringTargets(id, filePath ? { filePath } : {}),
+ refactoringOpportunities: (filePath) =>
+ cached(`refactor:opps:${filePath ?? ""}`, (id) =>
+ getRefactoringOpportunities(id, {
+ ...(filePath ? { filePath } : {}),
+ // The row renders counts, not steps; the detail call carries those.
+ stepPreview: 0,
+ limit: 100,
+ }),
+ ),
+ refactoringOpportunity: (opportunityId) =>
+ cached(`refactor:opp:${opportunityId}`, (id) =>
+ getRefactoringOpportunity(id, opportunityId, { stepLimit: 50, evidenceLimit: 20 }),
),
+ refactoringOpportunityPrompt: async (opportunityId, flavor) => {
+ const detail = await cached(`refactor:opp:${opportunityId}`, (id) =>
+ getRefactoringOpportunity(id, opportunityId, { stepLimit: 50, evidenceLimit: 20 }),
+ );
+ if (!detail.resolved) {
+ throw new Error(`No refactoring opportunity resolves for ${opportunityId}.`);
+ }
+ const repoName = ctx.repo?.name;
+ return buildRefactoringOpportunityPrompt({
+ opportunity: detail,
+ flavor,
+ ...(repoName ? { repoName } : {}),
+ });
+ },
refactoringPlan: (suggestionId) =>
cached(`refactor:plan:${suggestionId}`, (id) => getRefactoringPlan(id, suggestionId)),
refactoringPrompt: async (suggestionId, flavor) => {
diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.ts
index b5c9b9ba9..1d702f055 100644
--- a/packages/vscode/src/shared/webviewMessages.ts
+++ b/packages/vscode/src/shared/webviewMessages.ts
@@ -37,7 +37,11 @@ import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";
import type { ReviewerSuggestion } from "@repowise-dev/api-client/types";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
import type { ArchitectureView } from "@repowise-dev/ui/c4";
-import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/types/refactoring";
+import type {
+ RefactoringOpportunityDetail,
+ RefactoringOpportunityPage,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
/** Every editor-tab webview panel the extension can open. */
@@ -148,7 +152,13 @@ export interface HostApi {
hotFilesGraph(): Promise<HotFilesGraphResponse>;
executionFlows(): Promise<ExecutionFlowsResponse>;
// Refactoring
- refactoringTargets(filePath?: string): Promise<RefactoringTargets>;
+ /** The composed unit the web board and the agent contract both speak. */
+ refactoringOpportunities(filePath?: string): Promise<RefactoringOpportunityPage>;
+ refactoringOpportunity(opportunityId: string): Promise<RefactoringOpportunityDetail>;
+ refactoringOpportunityPrompt(
+ opportunityId: string,
+ flavor: AiPromptFlavor,
+ ): Promise<string>;
refactoringPlan(suggestionId: string): Promise<RefactoringPlan>;
/** Built host-side so the prompt matches the CodeLens copy path exactly. */
refactoringPrompt(suggestionId: string, flavor: AiPromptFlavor): Promise<string>;
diff --git a/packages/vscode/webview/src/views/refactoring/App.tsx b/packages/vscode/webview/src/views/refactoring/App.tsx
index f3e2c9230..90c137271 100644
--- a/packages/vscode/webview/src/views/refactoring/App.tsx
+++ b/packages/vscode/webview/src/views/refactoring/App.tsx
@@ -10,13 +10,13 @@ import {
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 { OpportunityRows } from "@repowise-dev/ui/refactoring/opportunity-rows";
import { blastCount, blastFiles, evidenceRows, planWins } from "@repowise-dev/ui/refactoring/types";
import type {
Confidence,
EffortBucket,
+ RefactoringOpportunity,
RefactoringPlan,
- RefactoringTargets,
} from "@repowise-dev/types/refactoring";
import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
import type { ViewProps } from "../../runtime/mount";
@@ -37,6 +37,10 @@ export function App({ host, params, refreshToken }: ViewProps<"refactoring">) {
// lens or tree is never a dead end: the list is the file's plans when a
// filePath came along, otherwise every ranked plan.
const [selectedId, setSelectedId] = useState<string | null>(params.planId ?? null);
+ // The composed unit the list shows. A CodeLens or a tree item still arrives
+ // as one plan, so both selections exist and the step view is reachable from
+ // either route.
+ const [selectedOpportunityId, setSelectedOpportunityId] = useState<string | null>(null);
// The host can push new params into an already-open panel; honor them.
useEffect(() => {
@@ -54,16 +58,115 @@ export function App({ host, params, refreshToken }: ViewProps<"refactoring">) {
);
}
+ if (selectedOpportunityId != null) {
+ return (
+ <OpportunityDetailView
+ host={host}
+ opportunityId={selectedOpportunityId}
+ refreshToken={refreshToken}
+ onBack={() => setSelectedOpportunityId(null)}
+ onOpenStep={(planId) => setSelectedId(planId)}
+ />
+ );
+ }
+
return (
<PlanListView
host={host}
filePath={params.filePath}
refreshToken={refreshToken}
- onOpen={(plan) => setSelectedId(plan.id)}
+ onOpen={(opportunity) => setSelectedOpportunityId(opportunity.opportunity_id)}
/>
);
}
+/** One opportunity's ordered steps. Each opens the existing step detail. */
+function OpportunityDetailView({
+ host,
+ opportunityId,
+ refreshToken,
+ onBack,
+ onOpenStep,
+}: {
+ host: WebviewHost;
+ opportunityId: string;
+ refreshToken: number;
+ onBack: () => void;
+ onOpenStep: (planId: string) => void;
+}) {
+ const state = useAsync(
+ () => host.api.refactoringOpportunity(opportunityId),
+ [opportunityId, refreshToken],
+ );
+
+ if (state.status === "loading") return <CenteredNote>Loading opportunity…</CenteredNote>;
+ if (state.status === "error") {
+ return <ErrorNote title="Could not load the opportunity.">{state.message}</ErrorNote>;
+ }
+ const detail = state.data;
+ if (!detail.resolved) {
+ return (
+ <ErrorNote title="Opportunity unavailable.">
+ {detail.model_state?.state === "stale_model"
+ ? "It was written by an older analysis model. Re-index and open it again."
+ : "It may have been resolved by a later analysis."}
+ </ErrorNote>
+ );
+ }
+
+ const anyRelocated = detail.steps.some((step) => Boolean(step.relocated_by));
+ return (
+ <div className="mx-auto max-w-4xl px-6 py-6">
+ <button
+ type="button"
+ onClick={onBack}
+ className="inline-flex items-center gap-1.5 text-sm text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ArrowLeft className="h-4 w-4" aria-hidden />
+ All opportunities
+ </button>
+ <h1 className="mt-4 break-all font-mono text-lg font-semibold text-[var(--color-text-primary)]">
+ {detail.file_path}
+ </h1>
+ <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
+ {detail.step_count} step{detail.step_count === 1 ? "" : "s"}, {detail.mechanical_steps}{" "}
+ mechanical · {EFFORT_LABEL[detail.effort_bucket]} effort ·{" "}
+ {CONFIDENCE_LABEL[detail.confidence]} confidence
+ </p>
+ {anyRelocated ? (
+ <p className="mt-3 rounded-md border border-[var(--color-caution)]/40 bg-[var(--color-caution)]/10 px-3 py-2 text-[12.5px] text-[var(--color-text-secondary)]">
+ {detail.ordering_note ??
+ "A step below is moved by an earlier one, so its file and lines say where the symbol was. Find it again before applying it."}
+ </p>
+ ) : null}
+ <ol className="mt-4 space-y-2">
+ {detail.steps.map((step, i) => (
+ <li key={step.plan_id}>
+ <button
+ type="button"
+ onClick={() => onOpenStep(step.plan_id)}
+ className="w-full rounded-lg border border-[var(--color-border-default)] px-3.5 py-3 text-left hover:border-[var(--color-border-hover)]"
+ >
+ <span className="text-[12.5px] text-[var(--color-text-secondary)]">
+ {String(i + 1).padStart(2, "0")} · {typeMeta(step.refactoring_type).label} ·{" "}
+ {step.applicability.classification === "mechanical" ? "Mechanical" : "Judgment"}
+ {step.relocated_by ? " · moved by an earlier step" : ""}
+ </span>
+ <span className="mt-1 block break-all font-mono text-[13px] font-medium text-[var(--color-text-primary)]">
+ {step.target_symbol || typeMeta(step.refactoring_type).label}
+ </span>
+ <span className="mt-0.5 block break-all font-mono text-[11px] text-[var(--color-text-tertiary)]">
+ {step.file_path}
+ {step.line_start ? `:${step.line_start}` : ""}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
// ── Async state helper ─────────────────────────────────────────────────────
type AsyncState<T> =
@@ -363,80 +466,71 @@ interface PlanListViewProps {
host: WebviewHost;
filePath?: string | undefined;
refreshToken: number;
- onOpen: (plan: RefactoringPlan) => void;
+ onOpen: (opportunity: RefactoringOpportunity) => void;
}
function PlanListView({ host, filePath, refreshToken, onOpen }: PlanListViewProps) {
- const state = useAsync(() => host.api.refactoringTargets(filePath), [filePath, refreshToken]);
+ const state = useAsync(
+ () => host.api.refactoringOpportunities(filePath),
+ [filePath, refreshToken],
+ );
- if (state.status === "loading") return <CenteredNote>Loading refactoring plans…</CenteredNote>;
+ if (state.status === "loading") {
+ return <CenteredNote>Loading refactoring opportunities…</CenteredNote>;
+ }
if (state.status === "error") {
- return <ErrorNote title="Could not load refactoring plans.">{state.message}</ErrorNote>;
+ return <ErrorNote title="Could not load refactoring opportunities.">{state.message}</ErrorNote>;
}
- const targets: RefactoringTargets = state.data;
- if (targets.plans.length === 0) {
+ const page = state.data;
+ if (page.items.length === 0) {
return (
<CenteredNote>
- {filePath ? `No refactoring plans for ${filePath}.` : "No refactoring plans found."}
+ {filePath
+ ? `No refactoring opportunities for ${filePath}.`
+ : "No refactoring opportunities found."}
</CenteredNote>
);
}
return (
<div className="mx-auto max-w-5xl px-6 py-6">
- <SummaryStrip summary={targets.summary} filePath={filePath} />
- <div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {targets.plans.map((plan) => (
- <RefactoringPlanCard key={plan.id} plan={plan} onOpen={onOpen} />
- ))}
+ <OpportunitySummaryStrip page={page} filePath={filePath} />
+ {/* The same rows the web board renders, over the same DTO. This was a
+ three-column grid of cards, each with a type-coloured rail and a
+ tinted type chip: six hues separating categories where two types are
+ most of the data. The web surface retired that treatment, and this
+ was the last thing mounting it. */}
+ <div className="mt-5 border-t border-[var(--color-border-default)]">
+ <OpportunityRows opportunities={page.items} onOpen={onOpen} />
</div>
</div>
);
}
-function SummaryStrip({
- summary,
+function OpportunitySummaryStrip({
+ page,
filePath,
}: {
- summary: RefactoringTargets["summary"];
+ page: { items: RefactoringOpportunity[]; total: number };
filePath?: string | undefined;
}) {
+ const steps = page.items.reduce((n, o) => n + o.step_count, 0);
+ const mechanical = page.items.reduce((n, o) => n + o.mechanical_steps, 0);
return (
- <div className="rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-5 py-4">
- <div className="flex flex-wrap items-baseline gap-x-2">
- <span className="text-2xl font-semibold tabular-nums text-[var(--color-text-primary)]">
- {summary.total}
- </span>
- <span className="text-[15px] text-[var(--color-text-secondary)]">
- refactoring plan{summary.total === 1 ? "" : "s"}
- {filePath ? (
- <>
- {" in "}
- <span className="font-mono text-xs text-[var(--color-text-tertiary)]">{filePath}</span>
- </>
- ) : null}
- </span>
- </div>
- {summary.by_type.length > 0 ? (
- <div className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">
- {summary.by_type.map((row) => (
- <span key={row.type} className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
- <span
- className="h-2 w-2 rounded-full"
- style={{ backgroundColor: typeAccent(row.type) }}
- aria-hidden
- />
- {typeMeta(row.type).label}
- <span className="tabular-nums text-[var(--color-text-tertiary)]">{row.count}</span>
- </span>
- ))}
- </div>
- ) : null}
- </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ <span className="font-semibold text-[var(--color-text-primary)] tabular-nums">
+ {page.total.toLocaleString()}
+ </span>{" "}
+ opportunit{page.total === 1 ? "y" : "ies"}
+ {filePath ? ` in ${filePath}` : ""} ·{" "}
+ <span className="tabular-nums">{steps.toLocaleString()}</span> step
+ {steps === 1 ? "" : "s"}, <span className="tabular-nums">{mechanical}</span> mechanical
+ </p>
);
}
+
// ── Shared bits ────────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: ReactNode }) {
diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
index 3e071f353..8306baa22 100644
--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
@@ -184,6 +184,7 @@ export default async function FileEntityPage({ params, searchParams }: Props) {
healthPanel: (
<FileHealthPanel
repoId={id}
+ filePath={detail.file_path}
health={detail.health}
functionBlame={detail.function_blame}
/>
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index dfcae8991..ea93028df 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -3,13 +3,14 @@
/**
* Refactoring — `/repos/[id]/refactoring`.
*
- * The deterministic refactoring plans the health pass writes. The page leads
- * with what the pile actually is (mostly small, local extractions), then the
+ * The composed opportunities the health pass writes: one per file, each a set
+ * of ordered steps. The page leads with what the pile actually is, then the
* handful that change the codebase's shape, then everything as rows.
*
- * Two URL params, both shareable: `?type=` filters the list, `?plan=` opens one
- * plan's drawer. The plan param is what the old centred modal could not have —
- * a plan you can send to someone.
+ * Three URL params, all shareable: `?type=` filters the list, `?opportunity=`
+ * opens one opportunity's drawer, and `?plan=` opens a single step in the plan
+ * inspector. The plan param is kept because the performance queue deep-links
+ * into it by plan id, and because a step is still a thing worth linking to.
*/
import { use, useCallback, useDeferredValue, useMemo, useState } from "react";
@@ -21,32 +22,52 @@ import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";
import {
+ OpportunityDrawer,
RefactoringBoard,
RefactoringDrawer,
STRUCTURAL_TYPES,
TYPE_ORDER,
typeMeta,
- type RefactoringSortKey,
+ type RefactoringBoardServerState,
} from "@repowise-dev/ui/refactoring";
import type {
Confidence,
EffortBucket,
+ OpportunityStatus,
+ RefactoringOpportunity,
+ RefactoringOpportunityDetail,
+ RefactoringOpportunityDetailResolved,
+ RefactoringOpportunityPage,
+ RefactoringOrder,
RefactoringPlan,
- RefactoringPlanPage,
} from "@repowise-dev/types/refactoring";
-import { AiPromptModal, buildRefactoringPlanPrompt } from "@repowise-dev/ui/health";
+import {
+ AiPromptModal,
+ buildRefactoringOpportunityPrompt,
+ buildRefactoringPlanPrompt,
+} from "@repowise-dev/ui/health";
import {
generateRefactoringCode,
- getRefactoringSettings,
+ getRefactoringOpportunities,
+ getRefactoringOpportunity,
getRefactoringPlan,
- getRefactoringPlansPage,
- getRefactoringTargets,
+ getRefactoringSettings,
+ updateRefactoringOpportunityStatus,
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 };
+
+const PAGE_SIZE = 60;
+const STRUCTURAL_CSV = (STRUCTURAL_TYPES as readonly string[]).join(",");
+
+/** The list's type tab, as the one lead type or the structural set. */
+function leadTypeFor(type: TypeFilter): string | undefined {
+ if (type === "all") return undefined;
+ if (type === "structural") return STRUCTURAL_CSV;
+ return type;
+}
export default function RefactoringPage({ params }: { params: Promise<{ id: string }> }) {
const { id: repoId } = use(params);
@@ -54,95 +75,116 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
"type",
parseAsStringLiteral(TYPE_VALUES).withDefault("all"),
);
+ const [openId, setOpenId] = useQueryState("opportunity", parseAsString);
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 [order, setOrder] = useState<RefactoringOrder>("queue");
+ const [status, setStatus] = useState<OpportunityStatus>("open");
+ const [effort, setEffort] = useState<EffortBucket | null>(null);
+ const [confidence, setConfidence] = useState<Confidence | null>(null);
+ const [mechanicalOnly, setMechanicalOnly] = useState(false);
const [offset, setOffset] = useState(0);
- const { data, error, isLoading, mutate } = useSWR<RefactoringPageData>(
+ const { data, error, isLoading, mutate } = useSWR<RefactoringOpportunityPage>(
[
- "refactoring-page",
+ "refactoring-opportunities",
repoId,
type,
deferredQuery,
- sort,
- efforts.join(","),
- confidences.join(","),
+ order,
+ status,
+ effort,
+ confidence,
+ mechanicalOnly,
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,
- };
- }
- },
+ () =>
+ getRefactoringOpportunities(repoId, {
+ refactoringType: leadTypeFor(type),
+ status,
+ search: deferredQuery || undefined,
+ effort: effort ?? undefined,
+ confidence: confidence ?? undefined,
+ mechanical: mechanicalOnly,
+ order,
+ // The row renders step counts, not steps. Asking for the steps would
+ // roughly double the page for pixels nothing draws.
+ stepPreview: 0,
+ limit: PAGE_SIZE,
+ offset,
+ }),
{ revalidateOnFocus: false, keepPreviousData: true },
);
- const plans = useMemo(() => data?.items ?? [], [data?.items]);
+ // The structural head for "Start here". A separate bounded call rather than a
+ // slice of the list above: the list is under whatever filter the reader chose,
+ // and Start here describes the whole repository.
+ const { data: structural } = useSWR<RefactoringOpportunityPage>(
+ type === "all" ? ["refactoring-structural", repoId] : null,
+ () =>
+ getRefactoringOpportunities(repoId, {
+ refactoringType: STRUCTURAL_CSV,
+ order: "rank",
+ stepPreview: 0,
+ limit: 100,
+ }),
+ { revalidateOnFocus: false },
+ );
+ const opportunities = useMemo(() => data?.items ?? [], [data?.items]);
const prefix = `/repos/${repoId}`;
- // `PlanRows` offers a second `line` argument and this deliberately ignores
- // it: the file page renders no line anchors, so appending `#L<n>` would be a
- // fragment that resolves to nothing and leaves the reader at the top of the
- // page wondering what they missed. Honour it here when the page grows them.
const fileHref = useCallback((path: string) => fileEntityPath(prefix, path), [prefix]);
- // 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 openPlanOnPage = useMemo(
- () => plans.find((p) => p.id === openPlanId) ?? null,
- [plans, openPlanId],
+ // The open opportunity comes from the URL, so a reload or a shared link lands
+ // on the same drawer rather than the top of the list.
+ const { data: openDetail, isLoading: detailLoading } = useSWR<RefactoringOpportunityDetail>(
+ openId ? ["refactoring-opportunity", repoId, openId] : null,
+ () => getRefactoringOpportunity(repoId, openId!, { stepLimit: 50, evidenceLimit: 20 }),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
);
- const { data: linkedPlan } = useSWR<RefactoringPlan>(
- openPlanId && !openPlanOnPage ? ["refactoring-plan", repoId, openPlanId] : null,
+
+ const { data: openPlan } = useSWR<RefactoringPlan>(
+ openPlanId ? ["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), []);
+ const [promptFor, setPromptFor] = useState<
+ | { kind: "opportunity"; value: RefactoringOpportunityDetailResolved }
+ | { kind: "plan"; value: RefactoringPlan }
+ | null
+ >(null);
- // Opt-in code generation. Enabled only when the repo's config turns it on
- // (a local-`serve` capability); the settings call 404s on hosted backends,
- // which simply leaves the action hidden.
+ // A row hands over its whole opportunity, which means fetching the detail the
+ // list deliberately does not carry. One call, on demand, rather than steps on
+ // every row of every page.
+ const onRowAiPrompt = useCallback(
+ async (opportunity: RefactoringOpportunity) => {
+ const detail = await getRefactoringOpportunity(repoId, opportunity.opportunity_id, {
+ stepLimit: 50,
+ evidenceLimit: 20,
+ });
+ if (detail.resolved) setPromptFor({ kind: "opportunity", value: detail });
+ },
+ [repoId],
+ );
+
+ const onStatusChange = useCallback(
+ async (opportunity: { opportunity_id: string }, status: OpportunityStatus) => {
+ await updateRefactoringOpportunityStatus(repoId, opportunity.opportunity_id, status);
+ // The row's optimistic state stands until this lands; refetching is what
+ // makes the server the authority on what the state actually became, since
+ // an opportunity's status is a rollup and not simply what was asked for.
+ await mutate();
+ },
+ [repoId, mutate],
+ );
+
+ // Opt-in code generation. Enabled only when the repo's config turns it on (a
+ // local-`serve` capability); the settings call 404s on hosted backends, which
+ // simply leaves the action hidden.
const { data: settings } = useSWR<RefactoringSettings>(
`refactoring-settings:${repoId}`,
() => getRefactoringSettings(repoId),
@@ -156,26 +198,43 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
[settings?.enabled, repoId],
);
- const counts = new Map((data?.summary.by_type ?? []).map((c) => [c.type, c.count]));
+ const facetCounts = data?.facets?.lead_type ?? {};
+ const summary = data?.summary ?? null;
+ const facetTotal = Object.values(facetCounts).reduce((n, c) => n + c, 0);
const structuralCount = (STRUCTURAL_TYPES as readonly string[]).reduce(
- (n, t) => n + (counts.get(t) ?? 0),
+ (n, t) => n + (facetCounts[t] ?? 0),
0,
);
const tabs = [
- { id: "all" as const, label: "All", badge: data?.summary.total },
+ // Summed from the facets, not from the rollup: the facets follow the status
+ // filter and the rollup does not, so under "Resolved" the rollup would put
+ // the open total on a tab that lists resolved rows.
+ { id: "all" as const, label: "All", badge: facetTotal },
{ id: "structural" as const, label: "Structural", badge: structuralCount },
- ...TYPE_ORDER.map((t) => ({
+ ...TYPE_ORDER.filter((t) => t !== "performance_fix").map((t) => ({
id: t,
label: typeMeta(t).label,
- badge: counts.get(t) ?? 0,
+ badge: facetCounts[t] ?? 0,
})),
].filter((t) => t.id === "all" || (t.badge ?? 0) > 0);
+ const serverState: RefactoringBoardServerState = {
+ query,
+ order,
+ status,
+ effort,
+ confidence,
+ mechanicalOnly,
+ total: data?.total ?? 0,
+ offset,
+ nextOffset: data?.next_offset ?? null,
+ };
+
return (
<PageShell
title="Refactoring"
icon={<Wrench className="h-5 w-5 text-[var(--color-accent-primary)]" />}
- description="Concrete, ranked plans the health pass wrote from your code. Open one to see the change, or hand it to a coding agent."
+ description="One opportunity per file: the ordered steps the health pass wrote from your code. Open one to see the change, or hand it to a coding agent."
actions={
<button
type="button"
@@ -199,95 +258,102 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
{error ? (
<div className="rounded-2xl border border-[var(--color-error)]/30 bg-[var(--color-error)]/5 p-6 text-sm text-[var(--color-text-secondary)]">
- Couldn&apos;t load refactoring plans. The repo may not be indexed yet, or the API is
- unreachable.
+ Couldn&apos;t load refactoring opportunities. The repo may not be indexed yet, or the
+ API is unreachable.
+ </div>
+ ) : data?.summary?.status === "unavailable" ? (
+ <div className="rounded-2xl border border-[var(--color-border-default)] p-6 text-sm text-[var(--color-text-secondary)]">
+ {data.summary.detail}
</div>
) : isLoading ? (
// Matches the real layout's shapes: a lede block, a ribbon, a field.
- <SkeletonRegion className="space-y-8" label="Loading refactoring plans">
+ <SkeletonRegion className="space-y-8" label="Loading refactoring opportunities">
<Skeleton className="h-32 rounded-xl" />
<Skeleton className="h-16 rounded-xl" />
<Skeleton className="h-72 rounded-xl" />
</SkeletonRegion>
) : (
<RefactoringBoard
- 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,
- }
- }
+ opportunities={opportunities}
+ summary={summary}
+ structuralOpportunities={structural?.items}
+ serverState={serverState}
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.order !== undefined) setOrder(change.order);
+ if (change.status !== undefined) setStatus(change.status);
+ if (change.effort !== undefined) setEffort(change.effort);
+ if (change.confidence !== undefined) setConfidence(change.confidence);
+ if (change.mechanicalOnly !== undefined) setMechanicalOnly(change.mechanicalOnly);
if (change.offset !== undefined) setOffset(change.offset);
}}
- onOpen={(plan) => void setOpenPlanId(plan.id)}
- onAiPrompt={onAiPrompt}
+ onOpen={(o) => void setOpenId(o.opportunity_id)}
+ onAiPrompt={(o) => void onRowAiPrompt(o)}
+ onStatusChange={onStatusChange}
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.
+ // 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"
+ ? "All opportunities"
: type === "structural"
- ? "Structural plans"
- : `${typeMeta(type).label} plans`
+ ? "Structural opportunities"
+ : `${typeMeta(type).label} opportunities`
}
/>
)}
</div>
+ <OpportunityDrawer
+ detail={openDetail ?? null}
+ open={openId !== null}
+ loading={detailLoading}
+ onOpenChange={(open) => {
+ if (!open) void setOpenId(null);
+ }}
+ onAiPrompt={(detail) => setPromptFor({ kind: "opportunity", value: detail })}
+ onStatusChange={onStatusChange}
+ onOpenStep={(planId) => void setOpenPlanId(planId)}
+ fileHref={fileHref}
+ />
+
<RefactoringDrawer
- plan={openPlan}
- open={openPlan !== null}
+ plan={openPlan ?? null}
+ open={openPlanId !== null}
onOpenChange={(open) => {
if (!open) void setOpenPlanId(null);
}}
- onAiPrompt={onAiPrompt}
+ onAiPrompt={(plan) => setPromptFor({ kind: "plan", value: plan })}
onGenerateCode={onGenerateCode}
settingsHref={`${prefix}/settings`}
fileHref={fileHref}
/>
<AiPromptModal
- open={promptPlan !== null}
+ open={promptFor !== null}
onOpenChange={(open) => {
- if (!open) setPromptPlan(null);
+ if (!open) setPromptFor(null);
}}
getPrompt={
- promptPlan
- ? (flavor) => buildRefactoringPlanPrompt({ plan: promptPlan, flavor })
+ promptFor
+ ? (flavor) =>
+ promptFor.kind === "opportunity"
+ ? buildRefactoringOpportunityPrompt({
+ opportunity: promptFor.value,
+ flavor,
+ })
+ : buildRefactoringPlanPrompt({ plan: promptFor.value, flavor })
: null
}
- filePath={promptPlan?.file_path ?? null}
+ filePath={promptFor?.value.file_path ?? null}
title="AI refactoring prompt"
- description="A ready-to-paste plan that hands your AI coding agent the exact steps, the blast radius to keep consistent, and a completion contract."
+ description="A ready-to-paste plan that hands your AI coding agent the ordered steps, which of them are mechanical, the evidence behind the diagnosis, and the id to query it back."
/>
</PageShell>
);
diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsx
index 8cb15fe32..e3527835b 100644
--- a/packages/web/src/components/code-health/findings-tab.tsx
+++ b/packages/web/src/components/code-health/findings-tab.tsx
@@ -20,6 +20,10 @@ import {
updateFindingStatus,
} from "@/lib/api/code-health";
import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
+import {
+ getFileOpportunity,
+ refactoringOpportunityHref,
+} from "@/lib/api/file-opportunity";
export function FindingsTab({ repoId: id }: { repoId: string }) {
const router = useRouter();
@@ -29,6 +33,9 @@ export function FindingsTab({ repoId: id }: { repoId: string }) {
cacheKey: id,
getOverview: (limit) => getHealthOverview(id, limit),
listFindings: (opts) => listHealthFindings(id, opts),
+ getFileOpportunity: (filePath) => getFileOpportunity(id, filePath),
+ refactoringOpportunityHref: (opportunityId) =>
+ refactoringOpportunityHref(id, opportunityId),
listFiles: (opts) => listHealthFiles(id, opts),
getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
updateFindingStatus: (findingId, status) =>
diff --git a/packages/web/src/components/files/file-health-panel.tsx b/packages/web/src/components/files/file-health-panel.tsx
index c62b327db..941531265 100644
--- a/packages/web/src/components/files/file-health-panel.tsx
+++ b/packages/web/src/components/files/file-health-panel.tsx
@@ -1,13 +1,19 @@
"use client";
+import useSWR from "swr";
import { toast } from "sonner";
import { FileHealthTab, type FindingStatus } from "@repowise-dev/ui/files";
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import { updateFindingStatus } from "@/lib/api/code-health";
+import {
+ getFileOpportunity,
+ refactoringOpportunityHref,
+} from "@/lib/api/file-opportunity";
import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";
interface FileHealthPanelProps {
repoId: string;
+ filePath: string;
health: FileDetailHealth;
functionBlame: FunctionBlameRow[];
}
@@ -21,7 +27,12 @@ interface FileHealthPanelProps {
* cross a server boundary as props. Wrapping it here keeps that boundary at one
* component instead of at the top of the page.
*/
-export function FileHealthPanel({ repoId, health, functionBlame }: FileHealthPanelProps) {
+export function FileHealthPanel({
+ repoId,
+ filePath,
+ health,
+ functionBlame,
+}: FileHealthPanelProps) {
const prefix = `/repos/${repoId}`;
const onFindingStatusChange = async (findingId: string, status: FindingStatus) => {
@@ -34,6 +45,15 @@ export function FileHealthPanel({ repoId, health, functionBlame }: FileHealthPan
}
};
+ // One indexed lookup for the file's composed opportunity. This page is where
+ // a reader has already chosen the file, so it is the most natural place to
+ // hand them the plan - and it was the one surface with no route to it at all.
+ const { data: opportunity } = useSWR(
+ `file-opportunity:${repoId}:${filePath}`,
+ () => getFileOpportunity(repoId, filePath),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
return (
<FileHealthTab
health={health}
@@ -41,6 +61,8 @@ export function FileHealthPanel({ repoId, health, functionBlame }: FileHealthPan
onFindingStatusChange={onFindingStatusChange}
partnerHref={(p) => fileEntityPath(prefix, p)}
symbolHref={(s) => symbolEntityPath(prefix, s)}
+ opportunity={opportunity}
+ refactoringOpportunityHref={(id) => refactoringOpportunityHref(repoId, id)}
/>
);
}
diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsx
index 55add4723..d291e8ed2 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -9,6 +9,10 @@ import {
getPerformanceOpportunities,
updateFindingStatus,
} from "@/lib/api/code-health";
+import {
+ getFileOpportunity,
+ refactoringOpportunityHref,
+} from "@/lib/api/file-opportunity";
import { useFileBreakdown } from "./use-file-breakdown";
/** Causes listed for one file. A file with more than this is its own queue. */
@@ -44,9 +48,21 @@ export function HealthFileDrawerHost({
{ revalidateOnFocus: false },
);
+ // The file's one refactoring opportunity, so a finding in this drawer can
+ // reach the plan the same analysis wrote for it. Unconditional, unlike the
+ // performance causes above: this is one indexed lookup, and the link is the
+ // drawer's only route out to the plan.
+ const { data: opportunity } = useSWR(
+ filePath ? `file-opportunity:${repoId}:${filePath}` : null,
+ () => getFileOpportunity(repoId, filePath as string),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
return (
<HealthFileDrawer
open={filePath !== null}
+ opportunity={opportunity}
+ refactoringOpportunityHref={(id) => refactoringOpportunityHref(repoId, id)}
onClose={onClose}
loading={isLoading}
metric={data?.metric ?? null}
diff --git a/packages/web/src/lib/api/file-opportunity.ts b/packages/web/src/lib/api/file-opportunity.ts
new file mode 100644
index 000000000..0f351632b
--- /dev/null
+++ b/packages/web/src/lib/api/file-opportunity.ts
@@ -0,0 +1,32 @@
+import { getRefactoringOpportunities } from "@repowise-dev/api-client/refactoring";
+import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+
+/**
+ * The one composed refactoring opportunity for a file, or null.
+ *
+ * "One" is a measured fact, not an assumption the caller has to defend: on the
+ * dogfood index there are 581 open opportunities over 581 distinct files,
+ * because an opportunity *is* a file's plans folded together. The endpoint still
+ * returns a page, so this takes the first row and lets the shape stay honest if
+ * that ever stops being true.
+ *
+ * Steps are requested because the finding link only appears where a step
+ * actually addresses that finding's cause, and the maximum step count on a real
+ * index is 11.
+ */
+export async function getFileOpportunity(
+ repoId: string,
+ filePath: string,
+): Promise<RefactoringOpportunity | null> {
+ const page = await getRefactoringOpportunities(repoId, {
+ filePath,
+ stepPreview: 20,
+ limit: 1,
+ });
+ return page.items[0] ?? null;
+}
+
+/** Deep link into the refactoring surface for one opportunity. */
+export function refactoringOpportunityHref(repoId: string, opportunityId: string): string {
+ return `/repos/${repoId}/refactoring?opportunity=${encodeURIComponent(opportunityId)}`;
+}
diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.py
index 304dfbcd5..3d6a8499a 100644
--- a/tests/unit/cli/test_refactoring_targets_render.py
+++ b/tests/unit/cli/test_refactoring_targets_render.py
@@ -59,13 +59,43 @@ def test_json_includes_move_and_break_plans(capsys):
]
-def test_markdown_renders_both_sections(capsys):
+def test_markdown_renders_both_plans_as_opportunity_steps(capsys):
+ """The organizing principle is the file, not the refactoring type.
+
+ Type-grouped sections meant a file needing a split and two extractions
+ appeared three times in three places. The per-type detail is unchanged and
+ now renders under the step it belongs to.
+ """
_render_refactoring_targets([], [], [_move_method(), _break_cycle()], fmt="md")
text = capsys.readouterr().out
- assert "## Move Method plans" in text
- assert "C.envious" in text and "`T (t.py)`" in text
- assert "## Break Cycle plans" in text
+ assert "## Refactoring opportunities" in text
+ assert "## Move Method plans" not in text
+ assert "## Break Cycle plans" not in text
+ # Every step says which kind of change it is, and keeps its own detail.
+ assert "move_method **C.envious**" in text and "`T (t.py)`" in text
+ assert "break_cycle **cycle[2]: b.py->a.py**" in text
assert "invert b.py -> a.py" in text
+ assert "judgment" in text
+
+
+def test_markdown_states_the_unknown_primary_problem_rather_than_denying_it(capsys):
+ """Tri-state. With no findings supplied the answer is unknown, not "no"."""
+ _render_refactoring_targets([], [], [_move_method()], fmt="md")
+ text = capsys.readouterr().out
+ assert "no dominant problem recorded" in text
+ assert "does not address" not in text
+
+
+def test_json_carries_the_opportunities_beside_the_plans(capsys):
+ _render_refactoring_targets([], [], [_move_method(), _break_cycle()], fmt="json")
+ out = json.loads(capsys.readouterr().out)
+ opportunities = out["refactoring_opportunities"]
+ assert {o["file_path"] for o in opportunities} == {"a.py", "c.py"}
+ assert all(o["opportunity_id"].startswith("refop") for o in opportunities)
+ # The step ids are the plan ids, so the CLI and the server address one thing.
+ step_ids = [s["plan_id"] for o in opportunities for s in o["steps"]]
+ assert all(pid.startswith("refac") for pid in step_ids)
+ assert all(o["addresses_primary_problem"] is None for o in opportunities)
def _extract_helper(suggested_site: dict) -> RefactoringSuggestion:
diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.py
index 007e375fa..425c74287 100644
--- a/tests/unit/server/test_refactoring_opportunities.py
+++ b/tests/unit/server/test_refactoring_opportunities.py
@@ -8,6 +8,7 @@ than by wall clock.
from __future__ import annotations
+import json
import tempfile
from pathlib import Path
from typing import Any
@@ -627,3 +628,278 @@ async def test_a_capped_queue_says_why_it_was_capped(client, app):
assert result["refactoring_opportunities_reduced_reason"] == "limit"
assert result["recovery"]["refactoring_opportunities"]["remaining"] == 17
del repo_id
+
+
+# ---------------------------------------------------------------------------
+# Triage: the opportunity transition
+# ---------------------------------------------------------------------------
+
+
+async def test_one_request_triages_every_step_of_an_opportunity(client, app):
+ """An opportunity has no lifecycle of its own, so the transition writes the
+ steps and reads the rollup back. One request, not one per step."""
+ repo_id = await _seed(client, app, files=3)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+ detail = (
+ await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{oid}")
+ ).json()
+ step_ids = [s["plan_id"] for s in detail["steps"]]
+
+ res = await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "acknowledged"},
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["status"] == "acknowledged"
+ assert body["steps_updated"] == len(step_ids)
+
+ async with app.state.session_factory() as session:
+ for plan_id in step_ids:
+ row = await crud.get_refactoring_suggestion(session, repo_id, plan_id)
+ assert row is not None and row.status == "acknowledged"
+
+ # And the stored column moved with it, so the indexed read agrees without
+ # waiting for the next index.
+ refreshed = (
+ await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{oid}")
+ ).json()
+ assert refreshed["status"] == "acknowledged"
+
+
+async def test_a_dismissed_opportunity_reads_back_as_dismissed_not_resolved(client, app):
+ """``false_positive`` and ``resolved`` are different claims - the work was
+ never real against the work is done - so a person who chooses one must not
+ be shown the other."""
+ repo_id = await _seed(client, app, files=3)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+
+ res = await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "false_positive"},
+ )
+ assert res.status_code == 200
+ assert res.json()["status"] == "false_positive"
+
+
+async def test_a_triaged_opportunity_leaves_the_open_queue(client, app):
+ repo_id = await _seed(client, app, files=4)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ before = page["total"]
+ oid = page["items"][0]["opportunity_id"]
+
+ await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "resolved"},
+ )
+ after = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ assert after["total"] == before - 1
+ assert oid not in {item["opportunity_id"] for item in after["items"]}
+
+
+async def test_an_unknown_status_is_refused_rather_than_stored(client, app):
+ repo_id = await _seed(client, app, files=2)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+ res = await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "wontfix"},
+ )
+ assert res.status_code == 400
+
+
+async def test_an_unknown_opportunity_id_is_a_404(client, app):
+ repo_id = await _seed(client, app, files=2)
+ res = await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/refop2_nope/status",
+ json={"status": "resolved"},
+ )
+ assert res.status_code == 404
+
+
+def test_the_rollup_rule_separates_dismissed_from_done():
+ """The pure rule, over member states alone. One step someone called a false
+ positive must not resolve the work the others still describe."""
+ from repowise.core.analysis.health.refactoring.opportunity import roll_up_status
+
+ assert roll_up_status([]) == "open"
+ assert roll_up_status(["open", "resolved"]) == "open"
+ assert roll_up_status(["acknowledged", "resolved"]) == "acknowledged"
+ assert roll_up_status(["resolved", "resolved"]) == "resolved"
+ # Mixed: some done, one wrong. The work as a whole is done.
+ assert roll_up_status(["resolved", "false_positive"]) == "resolved"
+ # All wrong: the opportunity itself was the false positive.
+ assert roll_up_status(["false_positive", "false_positive"]) == "false_positive"
+
+
+async def test_the_board_can_search_by_path_fragment(client, app):
+ """The board's search box. A residual filter over the open set, which is
+ what makes it a substring rather than an index seek."""
+ repo_id = await _seed(client, app, files=6)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ sample = page["items"][0]["file_path"]
+ fragment = sample.rsplit("/", 1)[-1][:4]
+
+ hit = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/opportunities", params={"search": fragment}
+ )
+ ).json()
+ assert hit["total"] >= 1
+ assert all(fragment in item["file_path"] for item in hit["items"])
+
+ miss = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/opportunities",
+ params={"search": "zzz_no_such_path"},
+ )
+ ).json()
+ assert miss["total"] == 0
+
+
+async def test_several_lead_types_come_back_in_one_request(client, app):
+ """The board's Structural tab is four types, and it must not cost four
+ round trips."""
+ repo_id = await _seed(client, app, files=8)
+ body = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/opportunities",
+ params={"refactoring_type": "split_file,break_cycle"},
+ )
+ ).json()
+ assert body.get("ignored_arguments", {}) == {}
+ assert all(
+ item["lead_refactoring_type"] in {"split_file", "break_cycle"} for item in body["items"]
+ )
+
+ # A misspelling inside the list is still named rather than narrowing the
+ # result to the members that happened to be spelled right.
+ noisy = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/opportunities",
+ params={"refactoring_type": "split_file,nonsense"},
+ )
+ ).json()
+ assert noisy["ignored_arguments"]["refactoring_type"] == "nonsense"
+
+
+async def test_a_row_can_be_asked_for_without_its_steps(client, app):
+ """The product list renders step counts, not steps. Asking for the steps is
+ most of the page's bytes and none of its pixels."""
+ repo_id = await _seed(client, app, files=6)
+ with_steps = (
+ await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")
+ ).json()
+ without = (
+ await client.get(
+ f"/api/repos/{repo_id}/refactoring/opportunities", params={"step_preview": 0}
+ )
+ ).json()
+
+ assert any("steps" in item for item in with_steps["items"])
+ assert all("steps" not in item for item in without["items"])
+ # The counts a row actually renders survive.
+ assert all("step_count" in item for item in without["items"])
+ assert len(json.dumps(without)) < len(json.dumps(with_steps))
+
+
+async def test_the_field_can_place_every_structural_opportunity(client, app):
+ """The structural field plots file size against reach, and those are file
+ facts the opportunity row has to carry: without them it could only plot the
+ handful of files the bounded plan head happened to include."""
+ repo_id = await _seed(client, app, files=6)
+ body = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ figured = [
+ item
+ for item in body["items"]
+ if isinstance(item.get("file_nloc"), int) and isinstance(item.get("dependents"), int)
+ ]
+ assert figured, "the finalizer records the file's size and reach onto the row"
+
+
+async def test_a_dismissal_survives_the_next_index(client, app):
+ """A person's decision is not restated by the writer.
+
+ Both terminal states mean "nobody composes this again", so the reconciler
+ sees a dismissed opportunity exactly as it sees a completed one: absent.
+ Reading that absence as "resolved" would quietly turn "this was never real"
+ into "this got done", and the next index would do it silently.
+ """
+ repo_id = await _seed(client, app, files=3)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+
+ await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "false_positive"},
+ )
+ async with app.state.session_factory() as session:
+ await crud.finalize_refactoring_opportunities(session, repo_id)
+ await session.commit()
+ row = await crud.get_refactoring_opportunity(session, repo_id, oid)
+ assert row is not None
+ assert row.status == "false_positive"
+
+
+async def test_an_acknowledgement_survives_the_next_index(client, app):
+ """Acknowledged is outstanding work someone picked up, so it stays composed
+ and the rollup keeps saying so."""
+ repo_id = await _seed(client, app, files=3)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+
+ await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "acknowledged"},
+ )
+ async with app.state.session_factory() as session:
+ await crud.finalize_refactoring_opportunities(session, repo_id)
+ await session.commit()
+ row = await crud.get_refactoring_opportunity(session, repo_id, oid)
+ assert row is not None
+ assert row.status == "acknowledged"
+
+
+async def test_a_transition_that_writes_nothing_is_not_reported_as_success(client, app):
+ """The rollup of an empty set is ``open``.
+
+ So an opportunity whose steps are missing or whose plan ids no longer
+ resolve would otherwise answer "dismiss this" with a stored ``open`` and an
+ HTTP 200 - the caller's own request handed back as the state, with the one
+ thing they asked for the one thing that did not happen.
+ """
+ repo_id = await _seed(client, app, files=3)
+ page = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()
+ oid = page["items"][0]["opportunity_id"]
+
+ async with app.state.session_factory() as session:
+ row = await crud.get_refactoring_opportunity(session, repo_id, oid)
+ assert row is not None
+ row.details_json = json.dumps({"steps": []})
+ await session.commit()
+
+ res = await client.patch(
+ f"/api/repos/{repo_id}/refactoring/opportunities/{oid}/status",
+ json={"status": "false_positive"},
+ )
+ assert res.status_code == 409
+
+ async with app.state.session_factory() as session:
+ row = await crud.get_refactoring_opportunity(session, repo_id, oid)
+ assert row is not None
+ # Untouched, rather than silently reset to open.
+ assert row.status == "open"