Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ui): plot the whole filtered set on the Findings impact and effort graph (#2832)
Raghav Chamadiya953f880fe96f
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex 5d69ad849..7da846306 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -21,6 +21,8 @@ import type {PerformanceOpportunityQuery,HealthWorkQueueQuery,HealthWorkQueueResponse,+ ImpactEffortQuery,+ ImpactEffortResponse,HealthScope,HealthCounts,} from "@repowise-dev/types/health";@@ -59,6 +61,9 @@ export type {HealthWorkItem,HealthWorkQueueQuery,HealthWorkQueueResponse,+ ImpactEffortPoint,+ ImpactEffortQuery,+ ImpactEffortResponse,ModuleCoverageRow,PerformanceActionabilityState,PerformanceExecutionContext,@@ -248,6 +253,20 @@ export async function getHealthWorkQueue();}+/**+ * Every file the work queue's filters keep, placed by effort and recoverable+ * health. Takes the queue's own filters so the plane and the list agree.+ */+export async function getHealthImpactEffort(+ repoId: string,+ opts?: ImpactEffortQuery,+): Promise<ImpactEffortResponse> {+ return apiGet<ImpactEffortResponse>(+ `/api/repos/${repoId}/health/impact-effort`,+ opts as Record<string, string | number | boolean | undefined>,+ );+}+/** @deprecated Use getHealthWorkQueue; the response is file triage, not plans. */export const getRefactoringTargets = getHealthWorkQueue;diff --git a/packages/core/src/repowise/core/analysis/health/impact_effort.py b/packages/core/src/repowise/core/analysis/health/impact_effort.pynew file mode 100644index 000000000..46659654c--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/impact_effort.py@@ -0,0 +1,177 @@+"""The impact / effort plane over a whole filtered set of files.++One point per file: how many lines the fix touches (x) against how much health+it recovers (y). A file with a refactoring plan that recovers something is+placed by the plan, so both coordinates describe the same change: the lines its+steps span and the health it credits. A file with no such plan is placed by its+own size in code lines (NLOC) and the deduction its open findings carry, since+fixing those findings is the only change on offer. ``effort_basis`` says which.++The quadrant midlines are fixed constants, not the data's halfway points, so a+filter or a new index never moves a file from one quadrant to another unless+the file itself changed.++Pure over plain rows (``health.rows.field``); the server reads and filters the+rows, this module only places them.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from dataclasses import asdict, dataclass+from typing import Any, Literal++from repowise.core.analysis.health.fix_first.build import MIN_WORTH+from repowise.core.analysis.health.fix_first.model import TIER_RANK+from repowise.core.analysis.health.rows import detail_map, field++#: The vertical midline, in lines to change. The work queue's Medium effort+#: ceiling (150 NLOC), which is also the median size of a file with findings on+#: this repository's own index (2026-10-01).+EFFORT_MIDLINE_LINES = 150+#: The horizontal midline, in health points: the least a refactoring must+#: recover to be worth a Fix-first item.+GAIN_MIDLINE_POINTS = MIN_WORTH+#: The most points one response carries. Past it, the files recovering the+#: most health are kept and ``plotted < total`` says so. Ceiling: a repository+#: with more files than this loses its lowest-gain points; the upgrade is+#: server-side binning of the tail.+PLOT_CAP = 5000++EffortBasis = Literal["plan", "file"]+++@dataclass(frozen=True, slots=True)+class ImpactEffortPoint:+ file_path: str+ #: Lines the planned change spans, or the file's NLOC (``effort_basis``).+ effort_lines: int+ effort_basis: EffortBasis+ #: Health points the plan credits, or the open findings' deduction.+ recoverable_health: float+ #: The tier of the file's first Fix-first item, when it holds one.+ tier: str | None+ #: That item's place in the Fix-first list, from 1.+ fix_rank: int | None = None+++@dataclass(frozen=True, slots=True)+class ImpactEffortPlane:+ points: tuple[ImpactEffortPoint, ...]+ plotted: int+ total: int+ cap: int+ effort_midline_lines: int+ gain_midline_points: float++ def as_dict(self) -> dict[str, Any]:+ return {+ "points": [asdict(p) for p in self.points],+ "plotted": self.plotted,+ "total": self.total,+ "cap": self.cap,+ "effort_midline_lines": self.effort_midline_lines,+ "gain_midline_points": self.gain_midline_points,+ }+++def plan_lines(details: Mapping[str, Any]) -> int:+ """Lines spanned by a plan's steps; 0 when no step names a span."""+ total = 0+ for step in details.get("steps") or ():+ start, end = step.get("line_start"), step.get("line_end")+ if isinstance(start, int) and isinstance(end, int) and end >= start:+ total += end - start + 1+ return total+++def fix_first_marks(items: Iterable[Any]) -> dict[str, tuple[str, int]]:+ """Each file's first Fix-first item among *items*: its tier and 1-based rank.++ *items* are ``FixItem`` objects or their dicts, ``rank`` 0-based as the+ queue writes it. A file holding several items is marked by the highest.+ """+ out: dict[str, tuple[str, int]] = {}+ for item in items:+ target = field(item, "target")+ path = field(target, "file_path") if target is not None else None+ tier = field(item, "tier")+ rank = field(item, "rank")+ if not path or tier not in TIER_RANK or not isinstance(rank, int):+ continue+ if path not in out or rank + 1 < out[path][1]:+ out[path] = (tier, rank + 1)+ return out+++def build_impact_effort(+ files: Iterable[Any],+ opportunities: Iterable[Any] = (),+ marks: Mapping[str, tuple[str, int]] | None = None,+ *,+ cap: int = PLOT_CAP,+) -> ImpactEffortPlane:+ """Place every file in *files* on the plane.++ *files* rows carry ``file_path``, ``nloc`` and ``total_impact`` (the open+ deduction under the caller's filters); the caller has already left out+ history-only files. *opportunities* are open refactoring opportunity rows+ (``file_path``, ``recoverable_health``, ``details``/``details_json``).+ *marks* maps a path to its Fix-first ``(tier, rank)`` where it holds an item+ (:func:`fix_first_marks`).+ """+ plans: dict[str, tuple[int, float]] = {}+ for row in opportunities:+ gain = float(field(row, "recoverable_health") or 0.0)+ lines = plan_lines(detail_map(row))+ # A plan that recovers nothing, or names no span, is not the change+ # that fixes this file's findings; the file speaks for itself.+ if gain > 0 and lines > 0:+ plans[field(row, "file_path")] = (lines, gain)++ marks = marks or {}+ points: list[ImpactEffortPoint] = []+ for row in files:+ path = field(row, "file_path")+ plan = plans.get(path)+ mark = marks.get(path)+ if plan is not None:+ lines, gain = plan+ basis: EffortBasis = "plan"+ else:+ lines = int(field(row, "nloc") or 0)+ gain = float(field(row, "total_impact") or 0.0)+ basis = "file"+ points.append(+ ImpactEffortPoint(+ file_path=path,+ effort_lines=max(1, lines),+ effort_basis=basis,+ recoverable_health=round(gain, 3),+ tier=mark[0] if mark else None,+ fix_rank=mark[1] if mark else None,+ )+ )++ points.sort(key=lambda p: (-p.recoverable_health, p.file_path))+ kept = points[: max(cap, 0)]+ return ImpactEffortPlane(+ points=tuple(kept),+ plotted=len(kept),+ total=len(points),+ cap=cap,+ effort_midline_lines=EFFORT_MIDLINE_LINES,+ gain_midline_points=GAIN_MIDLINE_POINTS,+ )+++__all__ = [+ "EFFORT_MIDLINE_LINES",+ "GAIN_MIDLINE_POINTS",+ "PLOT_CAP",+ "ImpactEffortPlane",+ "ImpactEffortPoint",+ "build_impact_effort",+ "fix_first_marks",+ "plan_lines",+]diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.pyindex 75eb22dd2..685e544f4 100644--- a/packages/core/src/repowise/core/analysis/health/suggestions.py+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py@@ -191,6 +191,125 @@ _TEMPLATES: dict[str, str] = {"(`repowise decision supersede`) or by adding a 'relates_to' edge ""with a clarifying rationale."),+ # Test quality, advisory.+ "assertion_free_test": (+ "Assert on the result. This test runs the code and checks nothing, so it "+ "passes whatever the code does; add an assertion on the value or the side "+ "effect the test exists to protect."+ ),+ "mock_saturated_test": (+ "Test behaviour, not wiring. Replace mocks of the code's own collaborators "+ "with real objects or a fake, and keep mocks for the slow or external "+ "boundaries."+ ),+ # Performance: per-iteration work.+ "io_in_loop": (+ "Batch the I/O. Fetch or write everything the loop needs in one call "+ "before or after it (a bulk query, an IN clause, a batch request) and "+ "look the results up in memory inside the loop."+ ),+ "nested_loop_with_io": (+ "Lift the I/O out of the inner loop. Batch the inner call across the "+ "outer loop's items, or load the data once and index it by key."+ ),+ "lazy_load_in_loop": (+ "Load the relationship with the parent rows. Add selectinload or "+ "joinedload (prefetch_related or select_related in Django) to the query "+ "the loop iterates."+ ),+ "serial_await_in_loop": (+ "Run independent awaits together. When the iterations do not depend on "+ "each other, gather them (asyncio.gather, Promise.all, Task.WhenAll) "+ "with a bound on concurrency."+ ),+ "string_concat_in_loop": (+ "Build the string once. Collect the pieces in a list or buffer inside the "+ "loop and join them after it."+ ),+ "regex_compile_in_loop": (+ "Compile the pattern once. Move the compile call out of the loop into a "+ "constant or a field and reuse it."+ ),+ "resource_construction_in_loop": (+ "Create the client once. Construct the connection or client before the "+ "loop and reuse it for every iteration."+ ),+ "lock_in_loop": (+ "Take the lock once. Acquire it around the whole loop, or collect the "+ "changes and apply them in one critical section."+ ),+ "defer_in_loop": (+ "Release the resource each iteration. Close it at the end of the loop "+ "body, or move the body into its own function so the defer runs per "+ "iteration."+ ),+ "json_parse_in_loop": (+ "Parse once. Hoist the parse or stringify out of the loop, and replace a "+ "JSON round-trip clone with structuredClone."+ ),+ "membership_test_against_list_in_loop": (+ "Look up in a set. Build a set from the list once before the loop and "+ "test membership against it."+ ),+ "list_insert_zero_in_loop": (+ "Stop inserting at the front. Use collections.deque with appendleft, or "+ "append and reverse once after the loop."+ ),+ "pandas_iterrows_in_loop": (+ "Vectorize the loop. Express the per-row work as a column operation, or "+ "use itertuples when row access is unavoidable."+ ),+ "pd_concat_in_loop": (+ "Concatenate once. Append each frame to a list inside the loop and call "+ "pd.concat on the list after it."+ ),+ "array_spread_in_reduce": (+ "Mutate the accumulator. Push into it and return it, so each step does "+ "not copy everything gathered so far."+ ),+ "goroutine_in_unbounded_loop": (+ "Bound the fan-out. Use a worker pool, a semaphore channel or an errgroup "+ "with a limit so the goroutine count does not grow with the input."+ ),+ "nested_loop_quadratic": (+ "Remove the inner scan. If the inner loop searches for a match, index the "+ "inner collection by key in a map or set once."+ ),+ # Performance: blocking work.+ "blocking_sync_in_async": (+ "Use the async form of the call (asyncio.sleep, an async HTTP client, "+ "asyncio subprocess), or run the blocking call in a thread executor."+ ),+ "hot_path_sync_io": (+ "Take the I/O off the hot path. Cache the result, move the call to "+ "startup, or make it asynchronous."+ ),+ "blocking_io_under_lock": (+ "Do the I/O outside the lock. Read or write first, then take the lock "+ "only to update the shared state."+ ),+ "unbounded_read_reduced_in_memory": (+ "Select in the query. Move the per-key reduction into SQL (DISTINCT ON, "+ "a window function, a view) so only the rows you keep are read."+ ),+ # SQL.+ "sql_cartesian_join": (+ "Add the join predicate. Rewrite the comma join as JOIN ... ON the "+ "columns that relate the tables, or as CROSS JOIN if the product is "+ "intended."+ ),+ "sql_high_complexity": (+ "Split the routine. Move branching business logic into the application "+ "or into smaller routines, each with one job."+ ),+ "sql_select_star": (+ "Name the columns. Replace * with the column list the view's consumers "+ "read, so a new source column does not change the view's shape."+ ),+ "sql_update_delete_without_where": (+ "Confirm the statement should touch every row. Add the WHERE clause it "+ "needs, or a comment stating that the full-table change is intended."+ ),}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.pyindex 4151421b5..89959f10a 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@@ -6,17 +6,21 @@ not structured refactoring plans.from __future__ import annotations+from dataclasses import dataclassfrom typing import Anyfrom fastapi import Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.impact_effort import build_impact_effort, fix_first_marksfrom repowise.core.analysis.health.models import primary_finding, split_by_origin+from repowise.core.analysis.health.scope import parse_scopefrom repowise.core.analysis.health.scoring import ZERO_IMPACT_DIMENSIONSfrom repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_forfrom repowise.core.persistence import crud+from repowise.core.persistence.crud.analysis.fix_first import load_fix_firstfrom repowise.server.deps import get_db_session-from repowise.server.schemas import HealthWorkQueueResponse+from repowise.server.schemas import HealthWorkQueueResponse, ImpactEffortResponsefrom ._router import routerfrom .counts import CountsQuery, project@@ -57,14 +61,26 @@ def _effort_for_nloc(nloc: int) -> str:return "XL"- "/api/repos/{repo_id}/health/refactoring-targets",- response_model=HealthWorkQueueResponse,-)-async def health_work_queue(- repo_id: str,- limit: int = Query(200, ge=1, le=500),- offset: int = Query(0, ge=0),+@dataclass(frozen=True, slots=True)+class QueueFilters:+ """The narrowing the work queue and its impact / effort plane share."""++ module: str | None+ biomarker: str | None+ min_severity: str | None+ severity: str | None+ dimension: str | None+ status: str+ search: str | None+ only_hotspots: bool+ only_untested: bool+ only_failing: bool+ max_effort: str | None+ scope: str+ counts: str+++def queue_filters(module: str | None = Query(None, description="Filter to files in this module path"),biomarker: str | None = Query(None, description="Filter to one biomarker type"),min_severity: str | None = Query(None, description="Severity floor"),@@ -80,31 +96,30 @@ async def health_work_queue(only_untested: bool = Query(False),only_failing: bool = Query(False, description=FAILING_DESCRIPTION),max_effort: str | None = Query(None, description="S | M | L | XL"),- sort: str = Query(- "impact_per_effort", pattern="^(impact_per_effort|total_impact|score|finding_count)$"- ),- history: str = Query(- "exclude",- pattern="^(exclude|include)$",- description=(- "exclude (default) leaves out files whose only findings are history "- "markers: context, not work an edit can do. include keeps them."- ),- ),scope: str = ScopeQuery,counts: str = CountsQuery,- session: AsyncSession = Depends(get_db_session),-) -> dict:- """Health work items ranked by impact / effort.+) -> QueueFilters:+ return QueueFilters(+ module=module,+ biomarker=biomarker,+ min_severity=min_severity,+ severity=severity,+ dimension=dimension,+ status=status,+ search=search,+ only_hotspots=only_hotspots,+ only_untested=only_untested,+ only_failing=only_failing,+ max_effort=max_effort,+ scope=scope,+ counts=counts,+ )- A target carries its *primary* finding plus ``finding_count``, not the- findings themselves. Serializing every file's full finding list here cost- 1.8 MB at the default ``limit=200`` (2.9 MB at 500) to render a list that- shows none of it — the work was done for all ~2,400 files with findings,- before the ``[:limit]`` slice, and ~90% was then discarded. The two- consumers both sit behind a click and fetch what they need from- ``GET /health/findings?file_path=``.- """++async def _queue_targets(+ session: AsyncSession, repo_id: str, q: QueueFilters, *, history: str+) -> tuple[list[dict], int]:+ """Every work item the filters keep, unsorted, and the history-only count."""repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")@@ -118,46 +133,46 @@ async def health_work_queue(findings = await crud.get_health_findings(session,repo_id,- dimension=dimension,- status=parse_status_filter(status),+ dimension=q.dimension,+ status=parse_status_filter(q.status),exclude_dimensions=(- tuple(sorted(ZERO_IMPACT_DIMENSIONS)) if biomarker is None else None+ tuple(sorted(ZERO_IMPACT_DIMENSIONS)) if q.biomarker is None else None),)- metrics, findings = narrow(scope, metrics, findings)- metrics, findings, _unscored = project(counts, metrics, findings)+ metrics, findings = narrow(q.scope, metrics, findings)+ metrics, findings, _unscored = project(q.counts, metrics, findings)keep_metric = metric_filter(- search=search,- module=module,- only_hotspots=only_hotspots,- only_untested=only_untested,- only_failing=only_failing,- hotspots=await hotspot_paths(session, repo_id) if only_hotspots else None,+ search=q.search,+ module=q.module,+ only_hotspots=q.only_hotspots,+ only_untested=q.only_untested,+ only_failing=q.only_failing,+ hotspots=await hotspot_paths(session, repo_id) if q.only_hotspots else None,)metric_by_path = {m.file_path: m for m in metrics if keep_metric(m)}# An all-empty list (","; " ") means the caller selected nothing, not that# nothing matches — falling through to ``min_severity`` keeps a stray# serialization from silently emptying the queue behind a 200.- picked = {v.strip().lower() for v in (severity or "").split(",") if v.strip()}+ picked = {v.strip().lower() for v in (q.severity or "").split(",") if v.strip()}exact_severities = picked or Noneby_file: dict[str, list[Any]] = {}for f in findings:- if biomarker and f.biomarker_type != biomarker:+ if q.biomarker and f.biomarker_type != q.biomarker:continueif exact_severities is not None:if (f.severity or "").lower() not in exact_severities:continue- elif min_severity:+ elif q.min_severity:order = _SEVERITY_ORDER- if order.get(f.severity, 0) < order.get(min_severity, 0):+ if order.get(f.severity, 0) < order.get(q.min_severity, 0):continueby_file.setdefault(f.file_path, []).append(f)effort_rank = {"S": 1, "M": 2, "L": 3, "XL": 5}- max_effort_rank = effort_rank.get(max_effort or "", 99)+ max_effort_rank = effort_rank.get(q.max_effort or "", 99)targets: list[dict] = []history_only = 0@@ -171,7 +186,7 @@ async def health_work_queue(continue# Naming a marker reaches it whatever its origin, as with the# zero-impact dimensions above.- if history == "exclude" and biomarker is None and not split_by_origin(fs)[0]:+ if history == "exclude" and q.biomarker is None and not split_by_origin(fs)[0]:history_only += 1continuenloc = m.nloc@@ -201,6 +216,7 @@ async def health_work_queue("score": round(score, 2),"nloc": nloc,"module": m.module if (m and m.module) else None,+ "is_test": bool(getattr(m, "is_test", False)),"primary_biomarker": primary.biomarker_type,"primary_severity": primary.severity,"primary_reason": primary.reason,@@ -217,7 +233,45 @@ async def health_work_queue("impact_per_effort": ratio,})+ return targets, history_only++_HISTORY_QUERY = Query(+ "exclude",+ pattern="^(exclude|include)$",+ description=(+ "exclude (default) leaves out files whose only findings are history "+ "markers: context, not work an edit can do. include keeps them."+ ),+)+++ "/api/repos/{repo_id}/health/refactoring-targets",+ response_model=HealthWorkQueueResponse,+)+async def health_work_queue(+ repo_id: str,+ limit: int = Query(200, ge=1, le=500),+ offset: int = Query(0, ge=0),+ sort: str = Query(+ "impact_per_effort", pattern="^(impact_per_effort|total_impact|score|finding_count)$"+ ),+ history: str = _HISTORY_QUERY,+ filters: QueueFilters = Depends(queue_filters),+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Health work items ranked by impact / effort.++ A target carries its *primary* finding plus ``finding_count``, not the+ findings themselves. Serializing every file's full finding list here cost+ 1.8 MB at the default ``limit=200`` (2.9 MB at 500) to render a list that+ shows none of it — the work was done for all ~2,400 files with findings,+ before the ``[:limit]`` slice, and ~90% was then discarded. The two+ consumers both sit behind a click and fetch what they need from+ ``GET /health/findings?file_path=``.+ """+ targets, history_only = await _queue_targets(session, repo_id, filters, history=history)targets.sort(key=_SORT_KEYS[sort])# Both counts, because the view lists files but triages findings: "50 of# 812 files" alone leaves the size of the work unsaid.@@ -229,3 +283,36 @@ async def health_work_queue("offset": offset,"limit": limit,}+++ "/api/repos/{repo_id}/health/impact-effort",+ response_model=ImpactEffortResponse,+)+async def health_impact_effort(+ repo_id: str,+ filters: QueueFilters = Depends(queue_filters),+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Every file the work queue's filters keep, placed by effort and gain.++ The whole filtered set, not a page, so the plane and the queue's header+ count describe the same files. History-only files are always left out:+ nothing in their code can be changed to recover the health they cost.+ """+ targets, history_only = await _queue_targets(session, repo_id, filters, history="exclude")+ paths = [t["file_path"] for t in targets]+ opportunities: list[Any] = []+ if paths:+ opportunities, _n = await crud.list_refactoring_opportunities(+ session, repo_id, file_paths=paths, limit=len(paths)+ )+ # The Fix-first card on the same page builds this queue too, so this is+ # normally a cache hit. Only the items it shows are marked on the plane.+ queue = await load_fix_first(+ session,+ repo_id,+ scope="production" if parse_scope(filters.scope) == "production" else "all",+ )+ plane = build_impact_effort(targets, opportunities, fix_first_marks(queue.items))+ return {**plane.as_dict(), "history_only_excluded": history_only}diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex d1ec42a27..2a9871c4e 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -66,6 +66,8 @@ if TYPE_CHECKING:HealthTrendSummary,HealthWorkItem,HealthWorkQueueResponse,+ ImpactEffortPoint,+ ImpactEffortResponse,)from .code_quality import (DeadCodeAnalyzeResponse,@@ -370,6 +372,8 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"HealthTrendSummary","HealthWorkItem","HealthWorkQueueResponse",+ "ImpactEffortPoint",+ "ImpactEffortResponse",),"code_quality": ("DeadCodeAnalyzeResponse",@@ -733,6 +737,8 @@ __all__ = ["HotFilesGraphResponse","HotFilesNodeResponse","HotspotResponse",+ "ImpactEffortPoint",+ "ImpactEffortResponse","JobAcceptedResponse","JobResponse","KnowledgeMapOwner",diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.pyindex 742aceddf..a096071a3 100644--- a/packages/server/src/repowise/server/schemas/code_health.py+++ b/packages/server/src/repowise/server/schemas/code_health.py@@ -179,6 +179,8 @@ class HealthWorkItem(BaseModel):score: floatnloc: intmodule: str | None = None+ #: A test file, labelled on the row; ``scope=production`` leaves these out.+ is_test: bool = Falseprimary_biomarker: strprimary_severity: strprimary_reason: str | None = None@@ -211,3 +213,35 @@ class HealthWorkQueueResponse(BaseModel):history_only_excluded: int = 0offset: int = 0limit: int = 0+++class ImpactEffortPoint(BaseModel):+ """One file on the impact / effort plane."""++ file_path: str+ #: Lines the planned change spans (``effort_basis="plan"``) or the file's+ #: code lines (``"file"``, when no plan recovers anything).+ effort_lines: int+ effort_basis: str+ #: Health points the plan credits, or the open findings' deduction.+ recoverable_health: float+ #: The tier of the file's first Fix-first item, when it holds one.+ tier: str | None = None+ #: That item's place in the Fix-first list, from 1.+ fix_rank: int | None = None+++class ImpactEffortResponse(BaseModel):+ """Every file the work queue's filters keep, up to ``cap``."""++ points: list[ImpactEffortPoint] = []+ #: Points in this response; less than ``total`` only past ``cap``.+ plotted: int = 0+ #: Files the filters keep, history-only files excluded.+ total: int = 0+ cap: int = 0+ #: Fixed quadrant midlines from core, never derived from the data.+ effort_midline_lines: int = 0+ gain_midline_points: float = 0.0+ #: Files left out because every finding on them is a history marker.+ history_only_excluded: int = 0diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 7353122b6..d3ce2dc23 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -1956,6 +1956,7 @@ export interface HealthWorkItem {score: number;nloc: number;module?: string | null;+ is_test?: boolean;primary_biomarker: string;primary_severity: string;primary_reason?: string | null;@@ -2037,6 +2038,27 @@ export interface HotspotResponse {original_path?: string | null;}+/** One file on the impact / effort plane. */+export interface ImpactEffortPoint {+ file_path: string;+ effort_lines: number;+ effort_basis: string;+ recoverable_health: number;+ tier?: string | null;+ fix_rank?: number | null;+}++/** Every file the work queue's filters keep, up to ``cap``. */+export interface ImpactEffortResponse {+ points?: ImpactEffortPoint[];+ plotted?: number;+ total?: number;+ cap?: number;+ effort_midline_lines?: number;+ gain_midline_points?: number;+ history_only_excluded?: number;+}+/*** The 202 payload every background-job launch returns.*diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex e76ac7e17..8645270b9 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -1201,6 +1201,8 @@ export interface HealthWorkItem {score: number;nloc: number;module?: string | null;+ /** A test file. Optional: an older backend does not send it. */+ is_test?: boolean;primary_biomarker: string;primary_severity: HealthSeverity;primary_reason: string;@@ -1284,6 +1286,44 @@ export interface HealthWorkQueueQuery {scope?: HealthScope;}+/**+ * One file on the impact / effort plane. With a refactoring plan that recovers+ * something, both coordinates describe the plan (`effort_basis: "plan"`: lines+ * its steps span, health it credits); otherwise the file (`"file"`: its code+ * lines, the deduction its open findings carry).+ */+export interface ImpactEffortPoint {+ file_path: string;+ /** Always at least 1, so a log axis can hold it. */+ effort_lines: number;+ effort_basis: "plan" | "file";+ /** Health points. */+ recoverable_health: number;+ /** The tier of the file's first Fix-first item, when it holds one. */+ tier?: "now" | "next" | "later" | null;+ /** That item's place in the Fix-first list, from 1. */+ fix_rank?: number | null;+}++/** Every file the work queue's filters keep, history-only files excluded. */+export interface ImpactEffortResponse {+ /** Largest recoverable health first; at most `cap`. */+ points: ImpactEffortPoint[];+ plotted: number;+ total: number;+ cap: number;+ /** Fixed quadrant midlines from core, never derived from the data. */+ effort_midline_lines: number;+ gain_midline_points: number;+ history_only_excluded?: number;+}++/** The work queue's filters, without its paging, order or history switch. */+export type ImpactEffortQuery = Omit<+ HealthWorkQueueQuery,+ "limit" | "offset" | "sort" | "history"+>;+/** @deprecated Use HealthWorkItem; this is a file triage row, not a plan. */export type RefactoringTarget = HealthWorkItem;/** @deprecated Use HealthWorkQueueResponse. */diff --git a/packages/ui/__tests__/health/bulk-triage-bar.test.tsx b/packages/ui/__tests__/health/bulk-triage-bar.test.tsxnew file mode 100644index 000000000..daa4753a7--- /dev/null+++ b/packages/ui/__tests__/health/bulk-triage-bar.test.tsx@@ -0,0 +1,93 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { BulkTriageBar, runCapped } from "../../src/health/bulk-triage-bar.js";++describe("runCapped", () => {+ it("never has more than the cap in flight and reports failures", async () => {+ let inFlight = 0;+ let peak = 0;+ const { ok, failed } = await runCapped([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, async (n) => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await new Promise((r) => setTimeout(r, 1));+ inFlight -= 1;+ if (n % 4 === 0) throw new Error("nope");+ });+ expect(peak).toBe(3);+ expect(failed.sort()).toEqual([4, 8]);+ expect(ok).toHaveLength(7);+ });+});++describe("BulkTriageBar", () => {+ const selection = new Map([+ ["a.py", "f-a"],+ ["b.py", "f-b"],+ ]);++ it("renders nothing with nothing selected", () => {+ const { container } = render(+ <BulkTriageBar+ selection={new Map()}+ selectablePaths={[]}+ onSelectAll={() => {}}+ onClear={() => {}}+ updateStatus={async () => {}}+ onDone={() => {}}+ />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("sets the status of each selected row's finding and keeps the failures", async () => {+ const updateStatus = vi.fn(async (id: string) => {+ if (id === "f-b") throw new Error("409");+ });+ const onDone = vi.fn();+ render(+ <BulkTriageBar+ selection={selection}+ selectablePaths={[+ { path: "a.py", findingId: "f-a" },+ { path: "b.py", findingId: "f-b" },+ ]}+ onSelectAll={() => {}}+ onClear={() => {}}+ updateStatus={updateStatus}+ onDone={onDone}+ />,+ );+ expect(screen.getByRole("region", { name: "Bulk triage" }).textContent).toMatch(+ /2 rows selected\. Sets the status of the finding each row names\./,+ );+ // Every row on the page is already selected, so the bar does not offer it.+ expect(screen.queryByRole("button", { name: "Select all on this page" })).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "False positive" }));+ await waitFor(() => expect(onDone).toHaveBeenCalledWith(["b.py"]));+ expect(updateStatus.mock.calls.map((c) => c)).toEqual([+ ["f-a", "false_positive"],+ ["f-b", "false_positive"],+ ]);+ expect(screen.getByRole("status").textContent).toMatch(/1 could not be updated and stays selected/);+ });++ it("offers the rest of the page when only part of it is selected", () => {+ const onSelectAll = vi.fn();+ render(+ <BulkTriageBar+ selection={new Map([["a.py", "f-a"]])}+ selectablePaths={[+ { path: "a.py", findingId: "f-a" },+ { path: "c.py", findingId: "f-c" },+ ]}+ onSelectAll={onSelectAll}+ onClear={() => {}}+ updateStatus={async () => {}}+ onDone={() => {}}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Select all on this page" }));+ expect(onSelectAll).toHaveBeenCalled();+ });+});diff --git a/packages/ui/__tests__/health/findings-view-queue.test.tsx b/packages/ui/__tests__/health/findings-view-queue.test.tsxnew file mode 100644index 000000000..2a18c1d68--- /dev/null+++ b/packages/ui/__tests__/health/findings-view-queue.test.tsx@@ -0,0 +1,205 @@+/**+ * The Findings queue around its rows: the history switch, Watch kept apart in+ * every grouping, the whole-set graph and its link back to the list, and bulk+ * triage.+ */+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import type {+ HealthWorkItem,+ HealthWorkQueueQuery,+ HealthWorkQueueResponse,+ ImpactEffortQuery,+ ImpactEffortResponse,+} from "@repowise-dev/types/health";++import type { CodeHealthAdapter } from "../../src/health/code-health-adapter";+import { FindingsView } from "../../src/health/findings-view";++function row(path: string, partial: Partial<HealthWorkItem> = {}): HealthWorkItem {+ return {+ file_path: path,+ score: 4,+ nloc: 120,+ primary_biomarker: "complex_method",+ primary_severity: "high",+ primary_reason: `complex in ${path}`,+ primary_function: null,+ primary_line_start: 1,+ primary_line_end: 9,+ primary_suggestion: "Reduce cyclomatic complexity.",+ primary_finding_id: `f-${path}`,+ total_impact: 1,+ finding_count: 1,+ biomarkers: ["complex_method"],+ effort_bucket: "M",+ impact_per_effort: 0.5,+ ...partial,+ };+}++function plane(paths: string[]): ImpactEffortResponse {+ return {+ points: paths.map((p, i) => ({+ file_path: p,+ effort_lines: 10 * (i + 1),+ effort_basis: "file" as const,+ recoverable_health: 1 + i,+ tier: null,+ })),+ plotted: paths.length,+ total: paths.length,+ cap: 5000,+ effort_midline_lines: 150,+ gain_midline_points: 0.5,+ };+}++function adapter(over: Partial<CodeHealthAdapter>): CodeHealthAdapter {+ return {+ cacheKey: `queue-${Math.random()}`,+ getOverview: async () => ({ files: [], biomarkers: [], summary: {} }) as never,+ listFindings: async () => [],+ updateFindingStatus: async () => undefined,+ renderFileDrawer: () => null,+ ...over,+ } as unknown as CodeHealthAdapter;+}++const page = (targets: HealthWorkItem[], extra: Partial<HealthWorkQueueResponse> = {}) => ({+ targets,+ total: targets.length,+ ...extra,+});++describe("FindingsView history signals", () => {+ it("counts the hidden history-only files and asks for them on the toggle", async () => {+ const load = vi.fn(async (_q?: HealthWorkQueueQuery) =>+ page([row("a.py")], { history_only_excluded: 3 }),+ );+ render(<FindingsView adapter={adapter({ getHealthWorkQueue: load })} />);++ expect(await screen.findByText(/3 files with only history signals hidden/)).toBeInTheDocument();+ expect(load.mock.calls.at(-1)?.[0]?.history).toBeUndefined();++ fireEvent.click(screen.getByRole("button", { name: "Show history signals" }));+ await waitFor(() => expect(load.mock.calls.at(-1)?.[0]).toMatchObject({ history: "include" }));+ expect(screen.getByRole("button", { name: "Hide history signals" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ });++ it("keeps Watch rows apart when grouped by marker", async () => {+ const load = vi.fn(async () =>+ page([+ row("a.py"),+ row("w.py", { primary_biomarker: "change_entropy", biomarkers: ["change_entropy"] }),+ ]),+ );+ render(<FindingsView adapter={adapter({ getHealthWorkQueue: load })} />);+ await screen.findByText("a.py");++ fireEvent.change(screen.getByLabelText("Group"), { target: { value: "biomarker" } });++ const headings = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent ?? "");+ const watchAt = headings.findIndex((h) => h.startsWith("Watch"));+ const markerAt = headings.findIndex((h) => h.startsWith("Complex method"));+ expect(markerAt).toBeGreaterThan(-1);+ expect(watchAt).toBeGreaterThan(markerAt);+ const watchSection = screen.getAllByRole("heading", { level: 3 })[watchAt]!.closest("section")!;+ expect(within(watchSection).getByText("w.py")).toBeInTheDocument();+ });+});++describe("FindingsView graph", () => {+ it("plots the whole filtered set and asks without paging or order", async () => {+ const getImpactEffort = vi.fn(async (_q?: ImpactEffortQuery) => plane(["a.py", "b.py", "c.py"]));+ render(+ <FindingsView+ adapter={adapter({+ getHealthWorkQueue: async () => page([row("a.py")], { total: 3 }),+ getImpactEffort,+ })}+ />,+ );+ expect(await screen.findByText(/plotted of/)).toBeInTheDocument();+ const asked = getImpactEffort.mock.calls.at(-1)?.[0] ?? {};+ expect(Object.keys(asked)).not.toEqual(expect.arrayContaining(["limit"]));+ expect(asked).not.toHaveProperty("offset");+ expect(asked).not.toHaveProperty("sort");+ });++ it("highlights the clicked file's row on this page", async () => {+ render(+ <FindingsView+ adapter={adapter({+ getHealthWorkQueue: async () => page([row("a.py"), row("b.py")]),+ getImpactEffort: async () => plane(["a.py", "b.py"]),+ })}+ />,+ );+ await screen.findByText(/plotted of/);+ fireEvent.click(document.querySelector('[data-file="b.py"]')!);++ const card = document.querySelector('[data-health-work-item="b.py"]')!;+ await waitFor(() => expect(card.className).toContain("border-[var(--color-accent-primary)]"));+ expect(document.querySelector('[data-health-work-item="a.py"]')!.className).not.toContain(+ "border-[var(--color-accent-primary)]",+ );+ });++ it("fetches a clicked file that is not on this page and shows it above the list", async () => {+ const load = vi.fn(async (q?: HealthWorkQueueQuery) =>+ q?.search === "deep/c.py" ? page([row("deep/c.py")]) : page([row("a.py")], { total: 2 }),+ );+ render(+ <FindingsView+ adapter={adapter({+ getHealthWorkQueue: load,+ getImpactEffort: async () => plane(["a.py", "deep/c.py"]),+ })}+ />,+ );+ await screen.findByText(/plotted of/);+ fireEvent.click(document.querySelector('[data-file="deep/c.py"]')!);++ const pinned = await screen.findByRole("region", { name: "Selected in the graph" });+ expect(within(pinned).getByText("deep/c.py")).toBeInTheDocument();+ });++ it("draws no graph when the host cannot serve the whole set", async () => {+ render(<FindingsView adapter={adapter({ getHealthWorkQueue: async () => page([row("a.py")]) })} />);+ await screen.findByText("a.py");+ expect(screen.queryByText(/plotted of/)).not.toBeInTheDocument();+ });+});++describe("FindingsView bulk triage", () => {+ it("sets the status of each checked row's finding", async () => {+ const updateFindingStatus = vi.fn(async (_id: string, _status: string) => ({}) as never);+ render(+ <FindingsView+ adapter={adapter({+ getHealthWorkQueue: async () => page([row("a.py"), row("b.py")]),+ updateFindingStatus,+ })}+ />,+ );+ await screen.findByText("a.py");+ expect(screen.queryByRole("region", { name: "Bulk triage" })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("checkbox", { name: /finding in a.py/ }));+ fireEvent.click(screen.getByRole("checkbox", { name: /finding in b.py/ }));+ const bar = screen.getByRole("region", { name: "Bulk triage" });+ fireEvent.click(within(bar).getByRole("button", { name: "Acknowledge" }));++ await waitFor(() => expect(updateFindingStatus).toHaveBeenCalledTimes(2));+ expect(updateFindingStatus).toHaveBeenCalledWith("f-a.py", "acknowledged");+ expect(updateFindingStatus).toHaveBeenCalledWith("f-b.py", "acknowledged");+ await waitFor(() =>+ expect(screen.queryByRole("region", { name: "Bulk triage" })).not.toBeInTheDocument(),+ );+ });+});diff --git a/packages/ui/__tests__/health/impact-effort-quadrant.test.tsx b/packages/ui/__tests__/health/impact-effort-quadrant.test.tsxnew file mode 100644index 000000000..6b5504166--- /dev/null+++ b/packages/ui/__tests__/health/impact-effort-quadrant.test.tsx@@ -0,0 +1,129 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";+import type { ImpactEffortResponse } from "@repowise-dev/types/health";+import {+ ImpactEffortQuadrant,+ impactEffortQuadrantOf,+} from "../../src/health/impact-effort-quadrant.js";++function plane(partial: Partial<ImpactEffortResponse> = {}): ImpactEffortResponse {+ return {+ points: [+ { file_path: "a.py", effort_lines: 20, effort_basis: "plan", recoverable_health: 1.4, tier: "now", fix_rank: 1 },+ { file_path: "b.py", effort_lines: 900, effort_basis: "file", recoverable_health: 3.0, tier: null },+ { file_path: "c.py", effort_lines: 40, effort_basis: "file", recoverable_health: 0.2, tier: null },+ { file_path: "d.py", effort_lines: 300, effort_basis: "plan", recoverable_health: 0.1, tier: null },+ ],+ plotted: 4,+ total: 4,+ cap: 5000,+ effort_midline_lines: 150,+ gain_midline_points: 0.5,+ history_only_excluded: 7,+ ...partial,+ };+}++function svg(): SVGSVGElement {+ return document.querySelector("svg[viewBox]") as SVGSVGElement;+}++describe("ImpactEffortQuadrant", () => {+ it("places a file by the fixed midlines, not by the data", () => {+ expect(impactEffortQuadrantOf({ effort_lines: 20, recoverable_health: 1.4 }, 150, 0.5)).toBe("quick_wins");+ expect(impactEffortQuadrantOf({ effort_lines: 150, recoverable_health: 0.5 }, 150, 0.5)).toBe("major_projects");+ expect(impactEffortQuadrantOf({ effort_lines: 149, recoverable_health: 0.49 }, 150, 0.5)).toBe("minor_cleanups");+ expect(impactEffortQuadrantOf({ effort_lines: 2000, recoverable_health: 0 }, 150, 0.5)).toBe("time_sinks");+ });++ it("states coverage, quadrant names and the legend outside the drawing", () => {+ render(<ImpactEffortQuadrant data={plane()} />);+ expect(screen.getByText(/plotted of/).textContent).toMatch(/4 plotted of 4 files in this filter\./);+ expect(screen.getByText(/7 files with only history signals are not plotted/)).toBeInTheDocument();++ const quadrants = screen.getByLabelText("Quadrants");+ expect(within(quadrants).getByText("Quick wins").parentElement?.textContent).toMatch(/Quick wins 1 · under 150 lines, at least 0.5 points/);+ expect(within(quadrants).getByText("Time sinks").parentElement?.textContent).toMatch(/Time sinks 1 ·/);+ expect(screen.getByLabelText("Legend")).toBeInTheDocument();++ // None of that text lives inside the SVG: only axes, ticks and marks do.+ expect(svg().textContent).not.toMatch(/Quick wins|plotted|Selected/);+ });++ it("says when the server capped the set", () => {+ render(<ImpactEffortQuadrant data={plane({ plotted: 4, total: 6000, cap: 4 })} />);+ expect(screen.getByText(/plotted of/).textContent).toMatch(/capped at 4: the largest gains are kept/);+ });++ it("draws one mark per file with no colour ramp, a ring when no plan places it", () => {+ render(<ImpactEffortQuadrant data={plane()} />);+ const marks = screen.getByTestId("impact-effort-points").querySelectorAll("circle");+ expect(marks).toHaveLength(4);+ const plan = [...marks].find((c) => c.getAttribute("data-file") === "d.py")!;+ const file = [...marks].find((c) => c.getAttribute("data-file") === "b.py")!;+ expect(plan.getAttribute("class")).toContain("fill-[var(--color-text-tertiary)]");+ expect(file.getAttribute("class")).toContain("fill-transparent");+ for (const c of marks) expect(c.getAttribute("class")).not.toContain("accent");+ });++ it("finds a clicked file and describes the hovered one", () => {+ const onSelect = vi.fn();+ render(<ImpactEffortQuadrant data={plane()} onSelect={onSelect} />);+ const mark = document.querySelector('[data-file="b.py"]')!;++ fireEvent.pointerOver(mark);+ expect(screen.getByText("b.py")).toBeInTheDocument();+ expect(screen.getByText(/No plan recovers health here: 900 code lines, findings deduct 3.00 points/)).toBeInTheDocument();++ fireEvent.click(mark);+ expect(onSelect).toHaveBeenCalledWith("b.py");+ });++ it("marks the selection in the accent colour, outside the memoised field", () => {+ render(<ImpactEffortQuadrant data={plane()} selectedPath="c.py" />);+ const accent = [...svg().querySelectorAll("circle")].filter((c) =>+ (c.getAttribute("class") ?? "").includes("accent-primary"),+ );+ expect(accent).toHaveLength(1);+ expect(accent[0]!.closest("[data-testid=impact-effort-points]")).toBeNull();+ });++ it("walks the points from the keyboard, largest gain first as served", () => {+ const onSelect = vi.fn();+ render(<ImpactEffortQuadrant data={plane()} onSelect={onSelect} />);+ const plot = screen.getByRole("group", { name: /Impact and effort plot of 4 files/ });++ fireEvent.keyDown(plot, { key: "ArrowRight" });+ expect(screen.getByText("a.py")).toBeInTheDocument();+ expect(screen.getByText(/Plan changes 20 lines and recovers 1.40 points · Fix first #1, Now · Quick wins/)).toBeInTheDocument();++ fireEvent.keyDown(plot, { key: "End" });+ fireEvent.keyDown(plot, { key: "Enter" });+ expect(onSelect).toHaveBeenCalledWith("d.py");+ });++ it("numbers Fix-first items in ink over a lighter field, with no orange", () => {+ render(<ImpactEffortQuadrant data={plane()} />);+ const ranked = document.querySelector('[data-rank="1"]')!;+ expect(ranked.textContent).toBe("1");+ const ring = ranked.querySelector("circle")!;+ expect(ring.getAttribute("data-file")).toBe("a.py");+ expect(ring.getAttribute("class")).toContain("stroke-[var(--color-text-primary)]");+ expect(ranked.innerHTML).not.toContain("accent");+ const other = document.querySelector('[data-file="d.py"]')!;+ expect(Number(other.getAttribute("fill-opacity"))).toBeLessThan(0.5);+ expect(screen.getByLabelText("Legend").textContent).toMatch(/numbered by its place in Fix first/);+ });++ it("keeps marks clear of the y-axis tick labels", () => {+ render(<ImpactEffortQuadrant data={plane()} />);+ const leftmost = Math.min(+ ...[...screen.getByTestId("impact-effort-points").querySelectorAll("circle")].map((c) =>+ Number(c.getAttribute("cx")),+ ),+ );+ const yAxis = Number(svg().querySelectorAll("line")[1]!.getAttribute("x1"));+ // A rank marker has radius 7; the inset keeps it off the axis and its labels.+ expect(leftmost - 7).toBeGreaterThan(yAxis);+ });+});diff --git a/packages/ui/__tests__/health/refactoring-card.test.tsx b/packages/ui/__tests__/health/refactoring-card.test.tsxindex 35b60b71a..dfd5c328b 100644--- a/packages/ui/__tests__/health/refactoring-card.test.tsx+++ b/packages/ui/__tests__/health/refactoring-card.test.tsx@@ -131,3 +131,43 @@ describe("a file led by a history marker", () => {expect(screen.queryByText("Watch")).not.toBeInTheDocument();});});++describe("the row's labels and action", () => {+ it("labels a test file, and only a test file", () => {+ const { rerender } = render(<RefactoringCard target={target({ is_test: true })} />);+ expect(screen.getByText("test")).toBeInTheDocument();+ rerender(<RefactoringCard target={target({ is_test: false })} />);+ expect(screen.queryByText("test")).not.toBeInTheDocument();+ });++ it("shows the core action sentence as the row's action line", () => {+ render(+ <RefactoringCard target={target({ primary_suggestion: "Split this function." })} />,+ );+ expect(screen.getByText("Action").parentElement?.textContent).toBe(+ "ActionSplit this function.",+ );+ });++ it("offers a checkbox for the finding the row names", () => {+ const toggle = vi.fn();+ render(+ <RefactoringCard+ target={target({ primary_finding_id: "f1" })}+ onToggleSelect={toggle}+ selected+ />,+ );+ const box = screen.getByRole("checkbox", {+ name: /Select the .* finding in packages\/core\/pipeline\/incremental.py/,+ });+ expect(box).toBeChecked();+ fireEvent.click(box);+ expect(toggle).toHaveBeenCalledWith(expect.objectContaining({ primary_finding_id: "f1" }));+ });++ it("offers no checkbox when the row names no finding", () => {+ render(<RefactoringCard target={target()} onToggleSelect={vi.fn()} />);+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ });+});diff --git a/packages/ui/src/health/bulk-triage-bar.tsx b/packages/ui/src/health/bulk-triage-bar.tsxnew file mode 100644index 000000000..9d0e4da25--- /dev/null+++ b/packages/ui/src/health/bulk-triage-bar.tsx@@ -0,0 +1,141 @@+"use client";++import { useState } from "react";+import type { FindingStatus } from "./refactoring-card";++/**+ * Status writes in flight at once. There is no batch route, so a bulk action+ * is one PATCH per finding; this keeps a large selection from opening dozens+ * of requests against a local server. Ceiling: a selection of hundreds takes+ * hundreds of round trips; a server batch endpoint is the upgrade.+ */+export const BULK_CONCURRENCY = 4;++/** Run *fn* over *items* with at most *cap* in flight; report which failed. */+export async function runCapped<T>(+ items: readonly T[],+ cap: number,+ fn: (item: T) => Promise<unknown>,+): Promise<{ ok: T[]; failed: T[] }> {+ const ok: T[] = [];+ const failed: T[] = [];+ let next = 0;+ const worker = async () => {+ while (next < items.length) {+ const item = items[next++] as T;+ try {+ await fn(item);+ ok.push(item);+ } catch {+ failed.push(item);+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(cap, items.length) }, worker));+ return { ok, failed };+}++const ACTIONS: { status: FindingStatus; label: string }[] = [+ { status: "acknowledged", label: "Acknowledge" },+ { status: "resolved", label: "Resolved" },+ { status: "false_positive", label: "False positive" },+];++export interface BulkTriageBarProps {+ /** Selected rows: file path to the id of the finding the row names. */+ selection: ReadonlyMap<string, string>;+ /** Rows on this page that can be selected, for "Select all on this page". */+ selectablePaths: readonly { path: string; findingId: string }[];+ onSelectAll: () => void;+ onClear: () => void;+ updateStatus: (findingId: string, status: FindingStatus) => Promise<unknown>;+ /** After a run: the paths whose write failed stay selected. */+ onDone: (failedPaths: string[]) => void;+}++/**+ * The bulk triage bar, shown while any row is selected. Each row stands for+ * the finding it names, so the bar sets that finding's status, as the row's+ * own buttons would.+ */+export function BulkTriageBar({+ selection,+ selectablePaths,+ onSelectAll,+ onClear,+ updateStatus,+ onDone,+}: BulkTriageBarProps) {+ const [running, setRunning] = useState<FindingStatus | null>(null);+ const [failedCount, setFailedCount] = useState(0);++ if (selection.size === 0 && failedCount === 0) return null;++ const run = async (status: FindingStatus) => {+ setRunning(status);+ setFailedCount(0);+ const rows = [...selection.entries()];+ const { failed } = await runCapped(rows, BULK_CONCURRENCY, ([, id]) => updateStatus(id, status));+ setRunning(null);+ setFailedCount(failed.length);+ onDone(failed.map(([path]) => path));+ };++ const n = selection.size;+ const allOnPage = selectablePaths.every((r) => selection.has(r.path));++ return (+ <div+ role="region"+ aria-label="Bulk triage"+ className="sticky bottom-0 max-sm:bottom-20 z-10 -mx-1 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-3 py-2 text-xs shadow-md"+ >+ <span className="min-w-0 text-[var(--color-text-secondary)]">+ <span className="font-mono tabular-nums text-[var(--color-text-primary)]">{n}</span>{" "}+ {n === 1 ? "row" : "rows"} selected. Sets the status of the finding each row names.+ {failedCount > 0 ? (+ <span role="status" className="ml-1 text-[var(--color-error)]">+ {failedCount} could not be updated and {failedCount === 1 ? "stays" : "stay"} selected.+ </span>+ ) : null}+ </span>+ {/* Actions sit beside the count, not at the far edge, and the bar rides+ higher on phones: floating page chrome (a chat launcher) sits in the+ bottom corner. */}+ <div className="flex flex-wrap items-center gap-1.5">+ {ACTIONS.map((a) => (+ <button+ key={a.status}+ type="button"+ disabled={running != null || n === 0}+ onClick={() => void run(a.status)}+ className="rounded-md border border-[var(--color-border-default)] px-2 py-1 font-medium text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"+ >+ {running === a.status ? "Updating…" : a.label}+ </button>+ ))}+ {!allOnPage ? (+ <button+ type="button"+ onClick={onSelectAll}+ disabled={running != null}+ className="px-1.5 py-1 text-[var(--color-text-secondary)] underline decoration-dotted underline-offset-2 hover:text-[var(--color-text-primary)] disabled:opacity-50"+ >+ Select all on this page+ </button>+ ) : null}+ <button+ type="button"+ onClick={() => {+ setFailedCount(0);+ onClear();+ }}+ disabled={running != null}+ className="px-1.5 py-1 text-[var(--color-text-secondary)] underline decoration-dotted underline-offset-2 hover:text-[var(--color-text-primary)] disabled:opacity-50"+ >+ Clear+ </button>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex eabd074e1..5a42383be 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -8,6 +8,8 @@ import type {HealthOverviewResponse,HealthWorkQueueQuery,HealthWorkQueueResponse,+ ImpactEffortQuery,+ ImpactEffortResponse,PerformanceOpportunityDetail,PerformanceOpportunityPage,PerformanceOpportunityQuery,@@ -89,6 +91,12 @@ export interface CodeHealthAdapter {getHealthWorkQueue?(opts?: HealthWorkQueueQuery,): Promise<HealthWorkQueueResponse>;+ /**+ * Every file the queue's filters keep, placed by effort and recoverable+ * health. Optional: a host without it shows no impact / effort graph, since+ * a graph of one page would contradict the count above it.+ */+ getImpactEffort?(opts?: ImpactEffortQuery): Promise<ImpactEffortResponse>;/** @deprecated Legacy adapter name; FindingsView accepts it during migration. */getRefactoringTargets?(opts?: HealthWorkQueueQuery,diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsxindex 41f958a85..0d9c0145b 100644--- a/packages/ui/src/health/findings-view.tsx+++ b/packages/ui/src/health/findings-view.tsx@@ -10,7 +10,7 @@* file-detail drawer through a {@link CodeHealthAdapter}.*/-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import useSWR from "swr";import { Search } from "lucide-react";import type {@@ -19,6 +19,8 @@ import type {HealthOverviewResponse,HealthWorkQueueQuery,HealthWorkQueueResponse,+ ImpactEffortQuery,+ ImpactEffortResponse,} from "@repowise-dev/types/health";import { Skeleton } from "../ui/skeleton";@@ -36,8 +38,11 @@ import {import type { HealthWorkItemFinding } from "./refactoring-card";import { FilterSelect, FilterChip } from "./code-health-controls";import { ImpactEffortQuadrant } from "./impact-effort-quadrant";+import { BulkTriageBar } from "./bulk-triage-bar";+import { usePrefersReducedMotion } from "../hooks/use-prefers-reduced-motion";import {biomarkerLabel,+ DIMENSION_LABEL,HISTORY_EXPLAINER,HISTORY_LABEL,isWatchOnlyBiomarker,@@ -128,6 +133,14 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {const [offset, setOffset] = useState(0);const [selectedFile, setSelectedFile] = useState<string | null>(null);const [promptTarget, setPromptTarget] = useState<HealthWorkItem | null>(null);+ // History-only files are context, not work: out of the queue by default,+ // counted beside it, one toggle away.+ const [history, setHistory] = useState<"exclude" | "include">("exclude");+ // The file picked on the graph: highlighted in the list and scrolled to.+ const [highlightedPath, setHighlightedPath] = useState<string | null>(null);+ // Bulk triage: file path to the id of the finding the row names.+ const [selection, setSelection] = useState<ReadonlyMap<string, string>>(new Map());+ const reducedMotion = usePrefersReducedMotion();// Typing a path should not mint a request per keystroke.useEffect(() => {@@ -229,9 +242,11 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {...(onlyUntested && { only_untested: true }),...(onlyFailing && { only_failing: true }),...(sort && { sort }),+ ...(history === "include" && { history }),}),[offset,+ history,search,dimension,severities,@@ -259,11 +274,86 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {{ revalidateOnFocus: false, keepPreviousData: true },);+ // The graph takes the queue's filters without its paging, order or history+ // switch: it is the whole filtered set, and history-only files never plot.+ const planeQuery: ImpactEffortQuery = useMemo(() => {+ const { limit: _l, offset: _o, sort: _s, history: _h, ...rest } = query;+ return rest;+ }, [query]);+ const planeKey = JSON.stringify(planeQuery);+ const { data: plane, mutate: mutatePlane } = useSWR<ImpactEffortResponse>(+ overview && adapter.getImpactEffort ? `code-health-plane:${cacheKey}:${planeKey}` : null,+ () => adapter.getImpactEffort!(planeQuery),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ // A new question clears what was picked under the old one.+ useEffect(() => {+ setHighlightedPath(null);+ }, [planeKey]);+ const queueKey = JSON.stringify(query);+ useEffect(() => {+ setSelection(new Map());+ }, [queueKey]);+const handleStatus = async (findingId: string, next: FindingStatus) => {await adapter.updateFindingStatus(findingId, next);mutateQueue();+ void mutatePlane();};+ // A picked file off this page is fetched on its own and shown above the+ // list, so a click on any point lands on a row.+ const onPage = (queue?.targets ?? []).some((t) => t.file_path === highlightedPath);+ const { data: pinnedQueue } = useSWR<HealthWorkQueueResponse>(+ highlightedPath && queue && !onPage+ ? `code-health-pin:${cacheKey}:${queueKey}:${highlightedPath}`+ : null,+ () => loadHealthWorkQueue({ ...query, offset: 0, limit: 50, search: highlightedPath! }),+ { revalidateOnFocus: false },+ );+ const pinned =+ highlightedPath && !onPage+ ? pinnedQueue?.targets.find((t) => t.file_path === highlightedPath)+ : undefined;++ const onPickPoint = useCallback((path: string) => setHighlightedPath(path), []);++ // Scroll once per pick, after the row exists.+ const scrolledFor = useRef<string | null>(null);+ useEffect(() => {+ if (!highlightedPath) {+ scrolledFor.current = null;+ return;+ }+ if (scrolledFor.current === highlightedPath) return;+ const el = document.querySelector(+ `[data-health-work-item="${CSS.escape(highlightedPath)}"]`,+ );+ if (!el) return;+ scrolledFor.current = highlightedPath;+ el.scrollIntoView?.({ block: "center", behavior: reducedMotion ? "auto" : "smooth" });+ }, [highlightedPath, pinned, queue, reducedMotion]);++ const toggleSelect = useCallback((t: HealthWorkItem) => {+ const id = t.primary_finding_id;+ if (!id) return;+ setSelection((cur) => {+ const next = new Map(cur);+ if (next.has(t.file_path)) next.delete(t.file_path);+ else next.set(t.file_path, id);+ return next;+ });+ }, []);+ const selectable = useMemo(+ () =>+ (queue?.targets ?? []).flatMap((t) =>+ t.primary_finding_id ? [{ path: t.file_path, findingId: t.primary_finding_id }] : [],+ ),+ [queue],+ );+ const selectedPaths = useMemo(() => new Set(selection.keys()), [selection]);+// The repo's whole marker vocabulary, not the loaded rows': a filter must// not erase the option that would have widened it.const biomarkerOptions = useMemo(@@ -275,21 +365,18 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {// not group size, so "Leverage" sorted stays leverage-led inside and out.const grouped = useMemo(() => {const targets = queue?.targets ?? [];+ // A file led by a history marker has nothing in its code to change, so it+ // reads under Watch, after the files an edit can improve, in every+ // grouping. The lead is a history marker only when the file has no+ // code-shape finding at all.+ const fix = targets.filter((t) => !isWatchOnlyBiomarker(t.primary_biomarker));+ const watch = targets.filter((t) => isWatchOnlyBiomarker(t.primary_biomarker));+ const watchGroup = watch.length ? [{ key: HISTORY_LABEL, targets: watch }] : [];if (groupBy === "none") {- // A file led by a history marker has nothing in its code to change, so- // it reads under Watch, after the files an edit can improve. The lead is- // a history marker only when the file has no code-shape finding at all.- const fix = targets.filter((t) => !isWatchOnlyBiomarker(t.primary_biomarker));- const watch = targets.filter((t) => isWatchOnlyBiomarker(t.primary_biomarker));- return watch.length- ? [- { key: "All", targets: fix },- { key: HISTORY_LABEL, targets: watch },- ].filter((g) => g.targets.length > 0)- : [{ key: "All", targets }];+ return [...(fix.length ? [{ key: "All", targets: fix }] : []), ...watchGroup];}const groups = new Map<string, typeof targets>();- for (const t of targets) {+ for (const t of fix) {let key = "—";if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);else if (groupBy === "module") key = t.module ?? "(no module)";@@ -297,13 +384,14 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {if (!groups.has(key)) groups.set(key, []);groups.get(key)!.push(t);}- return [...groups.entries()].map(([key, targets]) => ({ key, targets }));+ return [...[...groups.entries()].map(([key, targets]) => ({ key, targets })), ...watchGroup];}, [queue, groupBy]);const total = queue?.total ?? 0;const findingTotal = queue?.finding_total;const shownFrom = total === 0 ? 0 : offset + 1;const shownTo = Math.min(offset + PAGE_SIZE, total);+ const historyHidden = queue?.history_only_excluded ?? 0;return (<div className="space-y-6">@@ -320,8 +408,26 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {findingTotal === 1 ? "finding" : "findings"}`: ""}+ {history === "exclude" && historyHidden > 0+ ? ` · ${historyHidden.toLocaleString()} ${+ historyHidden === 1 ? "file" : "files"+ } with only history signals hidden`+ : ""}</span>) : null}+ {history === "include" || historyHidden > 0 ? (+ <button+ type="button"+ aria-pressed={history === "include"}+ onClick={() => {+ setHistory((h) => (h === "include" ? "exclude" : "include"));+ setOffset(0);+ }}+ className="text-xs text-[var(--color-text-secondary)] underline decoration-dotted underline-offset-2 hover:text-[var(--color-text-primary)]"+ >+ {history === "include" ? "Hide history signals" : "Show history signals"}+ </button>+ ) : null}{filtered ? (<buttontype="button"@@ -352,10 +458,10 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {)}options={[{ value: "all", label: "All dimensions" },- { value: "defect", label: "Code health" },- { value: "maintainability", label: "Maintainability" },- { value: "performance", label: "Performance" },- { value: "advisory", label: "Advisory" },+ // One name per dimension, shared with every other health surface.+ ...(["defect", "maintainability", "performance", "advisory"] as const).map(+ (d) => ({ value: d, label: DIMENSION_LABEL[d] }),+ ),]}/><FilterSelect@@ -489,18 +595,35 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {}aria-busy={queueValidating}>- {/* Leverage at a glance — impact vs effort, click a dot to open- the file. Describes this page, as the list below does. */}- <ImpactEffortQuadrant- points={(queue?.targets ?? []).map((t) => ({- file_path: t.file_path,- total_impact: t.total_impact,- effort_bucket: t.effort_bucket,- nloc: t.nloc,- score: t.score,- }))}- onSelect={(p) => setSelectedFile(p.file_path)}- />+ {/* The whole filtered set, from one aggregate call. A click finds+ the file in the list below; the row opens the drawer. */}+ {plane && plane.total > 0 ? (+ <ImpactEffortQuadrant+ data={plane}+ selectedPath={highlightedPath}+ onSelect={onPickPoint}+ />+ ) : null}+ {pinned ? (+ <section className="space-y-2" aria-label="Selected in the graph">+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Selected in the graph{" "}+ <span className="normal-case tracking-normal text-[var(--color-text-secondary)]">+ (not on this page)+ </span>+ </h3>+ <HealthWorkQueueList+ targets={[pinned]}+ onSelect={(t) => setSelectedFile(t.file_path)}+ onStatusChange={handleStatus}+ onGeneratePrompt={(t) => void openPrompt(t)}+ onLoadFindings={loadFindings}+ onLoadOpportunity={loadOpportunity}+ refactoringOpportunityHref={adapter.refactoringOpportunityHref}+ highlightedPath={highlightedPath}+ />+ </section>+ ) : null}<div className="space-y-6">{grouped.map((g) => (<section key={g.key} className="space-y-2">@@ -513,7 +636,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {</span></h3>) : null}- {groupBy === "none" && g.key === HISTORY_LABEL ? (+ {g.key === HISTORY_LABEL ? (<p className="max-w-[72ch] text-xs text-[var(--color-text-tertiary)]">{HISTORY_EXPLAINER}</p>@@ -526,6 +649,9 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {onLoadFindings={loadFindings}onLoadOpportunity={loadOpportunity}refactoringOpportunityHref={adapter.refactoringOpportunityHref}+ highlightedPath={highlightedPath}+ selectedPaths={selectedPaths}+ onToggleSelect={toggleSelect}/></section>))}@@ -555,6 +681,27 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {</Button></div></div>+ <BulkTriageBar+ selection={selection}+ selectablePaths={selectable}+ onSelectAll={() =>+ setSelection((cur) => {+ const next = new Map(cur);+ for (const r of selectable) next.set(r.path, r.findingId);+ return next;+ })+ }+ onClear={() => setSelection(new Map())}+ updateStatus={(id, status) => adapter.updateFindingStatus(id, status)}+ onDone={(failed) => {+ setSelection((cur) => {+ const keep = new Set(failed);+ return new Map([...cur].filter(([path]) => keep.has(path)));+ });+ mutateQueue();+ void mutatePlane();+ }}+ /></div>)}</div>diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsxindex a76fd7b20..fd1dd8dc4 100644--- a/packages/ui/src/health/impact-effort-quadrant.tsx+++ b/packages/ui/src/health/impact-effort-quadrant.tsx@@ -1,146 +1,396 @@"use client";-import { useMemo, useState } from "react";-// A dot carries no band word, so it takes the canvas ramp, where Excellent-// and Good are told apart by value rather than by a label beside them.-import { healthNodeFill } from "./tokens";-import type { EffortBucket } from "./refactoring-card";--export interface ImpactEffortPoint {- file_path: string;- total_impact: number;- effort_bucket: EffortBucket;- nloc: number;- score: number;+import {+ memo,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type KeyboardEvent,+ type PointerEvent,+} from "react";+import type { ImpactEffortPoint, ImpactEffortResponse } from "@repowise-dev/types/health";++/**+ * Impact against effort for every file the queue's filters keep.+ *+ * The data is the whole filtered set from one server call, so the figure and+ * the queue's header count the same files. Both axes are continuous: x is the+ * lines a fix touches on a log scale, y the health points it recovers on a+ * square-root scale (most files recover under two points and a few recover+ * ten; a linear axis flattens the many into one line). The midlines come from+ * core constants in the response, never from the data, so a filter does not+ * move a file between quadrants.+ *+ * One mark per file and no colour ramp. A filled dot is placed by a refactoring+ * plan, a ring by the file itself (see `effort_basis`). Files holding a+ * Fix-first item are drawn as numbered ink markers carrying their Fix-first+ * rank, over a lighter field, so the plot points at what to do first. Orange+ * marks only the point under the pointer, the keyboard, or the reader's+ * selection. Legend, quadrant names and the coverage line sit outside the SVG.+ *+ * The dot field is memoised away from the hover state: a large repository+ * brings thousands of points, and hover must redraw one overlay mark, not the+ * field. Keyboard readers step through the points with the arrow keys (largest+ * gain first), which reads the same object a hover does.+ */++export type ImpactEffortQuadrantKey = "quick_wins" | "major_projects" | "minor_cleanups" | "time_sinks";++/** Reading order matches the plane's layout: top row, then bottom row. */+export const IMPACT_EFFORT_QUADRANTS: { key: ImpactEffortQuadrantKey; name: string }[] = [+ { key: "quick_wins", name: "Quick wins" },+ { key: "major_projects", name: "Major projects" },+ { key: "minor_cleanups", name: "Minor cleanups" },+ { key: "time_sinks", name: "Time sinks" },+];++export function impactEffortQuadrantOf(+ p: Pick<ImpactEffortPoint, "effort_lines" | "recoverable_health">,+ effortMid: number,+ gainMid: number,+): ImpactEffortQuadrantKey {+ const small = p.effort_lines < effortMid;+ const worth = p.recoverable_health >= gainMid;+ if (worth) return small ? "quick_wins" : "major_projects";+ return small ? "minor_cleanups" : "time_sinks";}+const TIER_LABEL: Record<string, string> = { now: "Now", next: "Next", later: "Later" };+export interface ImpactEffortQuadrantProps {- points: ImpactEffortPoint[];- onSelect?: (point: ImpactEffortPoint) => void;+ data: ImpactEffortResponse;+ /** The file the reader picked, drawn in the accent colour. */+ selectedPath?: string | null | undefined;+ /** Click or Enter on a point. */+ onSelect?: ((filePath: string) => void) | undefined;height?: number;}-const EFFORT_X: Record<EffortBucket, number> = { S: 12, M: 38, L: 62, XL: 88 };+const PAD = { l: 40, r: 16, t: 20, b: 30 };+/** Clear space inside the axes, so no mark sits on the tick labels. */+const INSET = { l: 14, b: 8 };++/** A round value at or above *v*, so the top tick reads cleanly. */+function niceCeil(v: number): number {+ if (v <= 0) return 1;+ const p = 10 ** Math.floor(Math.log10(v));+ for (const m of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (m * p >= v) return m * p;+ return 10 * p;+}++/** Candidate y ticks, kept clear of the midline label and of each other. */+const Y_TICKS = [0, 1, 2, 5, 10, 20, 50, 100];++function fmt(n: number): string {+ return n.toLocaleString();+}++function describe(p: ImpactEffortPoint): string {+ const gain = p.recoverable_health.toFixed(2);+ return p.effort_basis === "plan"+ ? `Plan changes ${fmt(p.effort_lines)} lines and recovers ${gain} points`+ : `No plan recovers health here: ${fmt(p.effort_lines)} code lines, findings deduct ${gain} points`;+}export function ImpactEffortQuadrant({- points,+ data,+ selectedPath,onSelect,- height = 280,+ height = 300,}: ImpactEffortQuadrantProps) {- const [hovered, setHovered] = useState<ImpactEffortPoint | null>(null);- const data = useMemo(() => points.filter((p) => p.total_impact > 0), [points]);+ const containerRef = useRef<HTMLDivElement | null>(null);+ // Seeded so the first paint is a plausible chart, not a reflow a frame later.+ const [width, setWidth] = useState(900);+ const [active, setActive] = useState<number | null>(null);- if (data.length === 0) {- return (- <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)]">- No health work items to plot yet.- </div>- );- }-- const W = 640;- const H = height;- const padL = 40;- const padR = 12;- const padT = 20;- const padB = 36;- const plotW = W - padL - padR;- const plotH = H - padT - padB;- const maxImpact = Math.max(...data.map((d) => d.total_impact), 1);- const minImpact = Math.min(...data.map((d) => d.total_impact));- // When every impact is identical (or zero) the (max−impact)/max ratio would- // collapse every dot onto the top edge and degenerate the midline. Center the- // dots vertically instead so the plot stays readable.- const flatImpact = maxImpact === minImpact || maxImpact === 0;-- const xScale = (pct: number) => padL + (pct / 100) * plotW;- const yScale = (impact: number) =>- flatImpact ? padT + plotH / 2 : padT + ((maxImpact - impact) / maxImpact) * plotH;-- // Quadrant midpoints — between M (38) and L (62), and at half impact.- const midX = xScale(50);- const midY = flatImpact ? padT + plotH / 2 : yScale(maxImpact / 2);-- // Jitter helper so dots within the same effort bucket don't perfectly stack.- const jitter = (s: string) => {- let h = 0;- for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;- return ((h % 14) - 7) * 1.4;+ useEffect(() => {+ const el = containerRef.current;+ if (!el || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver((entries) => {+ const w = entries[0]?.contentRect.width;+ if (w && w > 0) setWidth(w);+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const points = data.points;+ const effortMid = data.effort_midline_lines;+ const gainMid = data.gain_midline_points;++ // A new dataset invalidates the index the pointer or keyboard was on.+ useEffect(() => setActive(null), [points]);++ const geom = useMemo(() => {+ const W = Math.max(280, Math.round(width));+ const H = W < 480 ? Math.min(height, 240) : height;+ const plotW = W - PAD.l - PAD.r;+ const plotH = H - PAD.t - PAD.b;+ let maxEffort = effortMid * 2;+ let maxGain = gainMid * 2;+ for (const p of points) {+ if (p.effort_lines > maxEffort) maxEffort = p.effort_lines;+ if (p.recoverable_health > maxGain) maxGain = p.recoverable_health;+ }+ const decades = Math.max(1, Math.ceil(Math.log10(maxEffort)));+ const yMax = niceCeil(maxGain);+ const x = (lines: number) =>+ PAD.l + INSET.l + (Math.log10(Math.max(1, lines)) / decades) * (plotW - INSET.l);+ const y = (gain: number) =>+ PAD.t + (1 - Math.sqrt(Math.max(0, gain) / yMax)) * (plotH - INSET.b);+ const xs = new Float64Array(points.length);+ const ys = new Float64Array(points.length);+ points.forEach((p, i) => {+ xs[i] = x(p.effort_lines);+ ys[i] = y(p.recoverable_health);+ });+ const xTicks = Array.from({ length: decades + 1 }, (_, i) => 10 ** i);+ const yTicks: number[] = [];+ for (const t of [...Y_TICKS.filter((v) => v < yMax), yMax]) {+ const clear = [gainMid, ...yTicks].every((u) => Math.abs(y(t) - y(u)) >= 12);+ if (clear) yTicks.push(t);+ }+ return { W, H, plotW, plotH, x, y, xs, ys, xTicks, yTicks };+ }, [width, height, points, effortMid, gainMid]);++ const counts = useMemo(() => {+ const out: Record<ImpactEffortQuadrantKey, number> = {+ quick_wins: 0,+ major_projects: 0,+ minor_cleanups: 0,+ time_sinks: 0,+ };+ for (const p of points) out[impactEffortQuadrantOf(p, effortMid, gainMid)] += 1;+ return out;+ }, [points, effortMid, gainMid]);++ const select = useCallback(+ (i: number) => {+ const p = points[i];+ if (p && onSelect) onSelect(p.file_path);+ },+ [points, onSelect],+ );++ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {+ if (points.length === 0) return;+ const last = points.length - 1;+ let next: number | null = null;+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = active == null ? 0 : Math.min(last, active + 1);+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = active == null ? 0 : Math.max(0, active - 1);+ else if (e.key === "Home") next = 0;+ else if (e.key === "End") next = last;+ else if ((e.key === "Enter" || e.key === " ") && active != null) {+ e.preventDefault();+ select(active);+ return;+ }+ if (next == null) return;+ e.preventDefault();+ setActive(next);};+ const selectedIndex = useMemo(+ () => (selectedPath ? points.findIndex((p) => p.file_path === selectedPath) : -1),+ [points, selectedPath],+ );+ const shown = active != null ? points[active] : selectedIndex >= 0 ? points[selectedIndex] : null;+ const { W, H, plotW, plotH, x, y, xs, ys, xTicks, yTicks } = geom;+ const midX = x(effortMid);+ const midY = y(gainMid);+ const capped = data.plotted < data.total;+ const historyHidden = data.history_only_excluded ?? 0;+return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">- <div className="mb-2 flex items-baseline gap-2">- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- Impact × effort+ <section className="space-y-3" aria-labelledby="impact-effort-title">+ <div className="space-y-1">+ <h3+ id="impact-effort-title"+ className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]"+ >+ Impact and effort</h3>- <span className="text-xs text-[var(--color-text-tertiary)]">- {data.length} on this page · click a dot to open- </span>+ <p className="text-xs text-[var(--color-text-secondary)]">+ <span className="font-mono tabular-nums">{fmt(data.plotted)}</span> plotted of{" "}+ <span className="font-mono tabular-nums">{fmt(data.total)}</span>{" "}+ {data.total === 1 ? "file" : "files"} in this filter+ {capped ? `, capped at ${fmt(data.cap)}: the largest gains are kept` : ""}. Lines+ on a log scale, health points on a square-root scale.+ {historyHidden > 0+ ? ` ${fmt(historyHidden)} ${historyHidden === 1 ? "file" : "files"} with only history signals ${historyHidden === 1 ? "is" : "are"} not plotted: no edit recovers that health.`+ : ""}+ </p></div>- <div className="relative">- <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Impact vs effort scatter plot">- <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/8" />- <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" />- <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />- <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/5" />-- <line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />- <line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />- <line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />- <line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />-- {(["S", "M", "L", "XL"] as EffortBucket[]).map((b) => (- <text key={b} x={xScale(EFFORT_X[b])} y={H - padB + 14} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>- {b}++ <div ref={containerRef} className="min-w-0">+ <div+ tabIndex={0}+ role="group"+ aria-label={`Impact and effort plot of ${fmt(data.plotted)} files. Arrow keys step through them, largest gain first. Enter finds the file in the list.`}+ onKeyDown={onKeyDown}+ onBlur={() => setActive(null)}+ className="rounded-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]"+ >+ <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} aria-hidden="true" className="block">+ {/* Axes */}+ <line x1={PAD.l} y1={PAD.t + plotH} x2={PAD.l + plotW} y2={PAD.t + plotH} className="stroke-[var(--color-border-default)]" />+ <line x1={PAD.l} y1={PAD.t} x2={PAD.l} y2={PAD.t + plotH} className="stroke-[var(--color-border-default)]" />+ {xTicks.map((t, i) => (+ <text key={`x${t}`} x={x(t)} y={PAD.t + plotH + 14} textAnchor={i === xTicks.length - 1 ? "end" : "middle"} fontSize={10} className="fill-[var(--color-text-tertiary)] font-mono">+ {fmt(t)}+ </text>+ ))}+ {yTicks.map((t) => (+ <text key={`y${t}`} x={PAD.l - 6} y={y(t) + 3} textAnchor="end" fontSize={10} className="fill-[var(--color-text-tertiary)] font-mono">+ {t}+ </text>+ ))}+ <text x={PAD.l + plotW / 2} y={H - 4} textAnchor="middle" fontSize={10} className="fill-[var(--color-text-secondary)]">+ Lines to change+ </text>+ <text x={10} y={PAD.t + plotH / 2} textAnchor="middle" fontSize={10} transform={`rotate(-90 10 ${PAD.t + plotH / 2})`} className="fill-[var(--color-text-secondary)]">+ Recoverable health+ </text>+ {/* Fixed midlines from core */}+ <line x1={midX} y1={PAD.t} x2={midX} y2={PAD.t + plotH} strokeDasharray="3 3" className="stroke-[var(--color-border-hover)]" />+ <line x1={PAD.l} y1={midY} x2={PAD.l + plotW} y2={midY} strokeDasharray="3 3" className="stroke-[var(--color-border-hover)]" />+ <text x={midX} y={PAD.t - 6} textAnchor="middle" fontSize={10} className="fill-[var(--color-text-secondary)] font-mono">+ {fmt(effortMid)} lines+ </text>+ <text x={PAD.l - 6} y={midY + 3} textAnchor="end" fontSize={10} className="fill-[var(--color-text-secondary)] font-mono">+ {gainMid}</text>- ))}- <text x={W / 2} y={H - 4} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>- Effort (NLOC bucket)- </text>- <text x={10} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 10 ${H / 2})`}>- Total impact- </text>-- <text x={padL + 6} y={padT + 12} fontSize={10} fill="currentColor" opacity={0.6}>Quick wins</text>- <text x={W - padR - 6} y={padT + 12} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.6}>Major projects</text>- <text x={padL + 6} y={H - padB - 6} fontSize={10} fill="currentColor" opacity={0.5}>Minor cleanups</text>- <text x={W - padR - 6} y={H - padB - 6} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Time sinks</text>-- {data.map((p) => {- const baseX = xScale(EFFORT_X[p.effort_bucket]);- const cx = baseX + jitter(p.file_path);- const cy = yScale(p.total_impact);- const isHovered = hovered?.file_path === p.file_path;- const fillCls = healthNodeFill(p.score);- return (- <circle- key={p.file_path}- cx={cx}- cy={cy}- r={isHovered ? 6 : 4}- className={`${fillCls} ${onSelect ? "cursor-pointer" : ""}`}- fillOpacity={0.75}- stroke={isHovered ? "white" : "none"}- strokeWidth={1.5}- onMouseEnter={() => setHovered(p)}- onMouseLeave={() => setHovered(null)}- onClick={onSelect ? () => onSelect(p) : undefined}- >- <title>{`${p.file_path}\n−${p.total_impact.toFixed(2)} · ${p.effort_bucket} effort · score ${p.score.toFixed(1)}`}</title>- </circle>- );- })}- </svg>- {hovered ? (- <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs shadow-md">- <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>- <span className="ml-2 text-[var(--color-text-tertiary)]">- −{hovered.total_impact.toFixed(2)} · {hovered.effort_bucket} · {hovered.score.toFixed(1)}++ <PointField points={points} xs={xs} ys={ys} onHover={setActive} onPick={select} />++ {selectedIndex >= 0 ? (+ points[selectedIndex]?.fix_rank != null ? (+ // A ring, so the rank number under it stays readable.+ <circle cx={xs[selectedIndex]} cy={ys[selectedIndex]} r={8.5} className="fill-none stroke-[var(--color-accent-primary)]" strokeWidth={2.5} pointerEvents="none" />+ ) : (+ <circle cx={xs[selectedIndex]} cy={ys[selectedIndex]} r={5.5} className="fill-[var(--color-accent-primary)] stroke-[var(--color-bg-root)]" strokeWidth={1.5} pointerEvents="none" />+ )+ ) : null}+ {active != null && active !== selectedIndex ? (+ <circle cx={xs[active]} cy={ys[active]} r={points[active]?.fix_rank != null ? 9 : 5.5} className="fill-none stroke-[var(--color-accent-primary)]" strokeWidth={2} pointerEvents="none" />+ ) : null}+ </svg>+ </div>+ <p aria-live="polite" className="mt-1 min-h-[2.5rem] text-xs text-[var(--color-text-secondary)]">+ {shown ? (+ <>+ <span className="font-mono text-[var(--color-text-primary)] break-all">{shown.file_path}</span>+ <br />+ {describe(shown)}+ {shown.fix_rank != null+ ? ` · Fix first #${shown.fix_rank}${shown.tier ? `, ${TIER_LABEL[shown.tier] ?? shown.tier}` : ""}`+ : ""}+ {" · "}+ {IMPACT_EFFORT_QUADRANTS.find((q) => q.key === impactEffortQuadrantOf(shown, effortMid, gainMid))?.name}+ </>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">+ Point at a file, or focus the plot and use the arrow keys. Click or press Enter to find it in the list.</span>+ )}+ </p>+ </div>++ <dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-2" aria-label="Quadrants">+ {IMPACT_EFFORT_QUADRANTS.map((q) => (+ <div key={q.key} className="min-w-0">+ <dt className="inline font-medium text-[var(--color-text-primary)]">{q.name}</dt>{" "}+ <dd className="inline text-[var(--color-text-secondary)]">+ <span className="font-mono tabular-nums">{fmt(counts[q.key])}</span>+ {" · "}+ {q.key === "quick_wins" || q.key === "minor_cleanups" ? "under" : "at least"} {fmt(effortMid)} lines,{" "}+ {q.key === "quick_wins" || q.key === "major_projects" ? "at least" : "under"} {gainMid} points+ </dd></div>+ ))}+ </dl>++ <ul className="flex flex-wrap gap-x-5 gap-y-1 text-xs text-[var(--color-text-secondary)]" aria-label="Legend">+ <li className="inline-flex items-center gap-1.5">+ <svg width="10" height="10" aria-hidden="true"><circle cx="5" cy="5" r="3.5" className="fill-[var(--color-text-tertiary)]" /></svg>+ Placed by its refactoring plan: lines it changes, health it recovers+ </li>+ <li className="inline-flex items-center gap-1.5">+ <svg width="10" height="10" aria-hidden="true"><circle cx="5" cy="5" r="3" className="fill-none stroke-[var(--color-text-tertiary)]" strokeWidth={1.25} /></svg>+ No plan recovers health: code lines, and what its findings deduct+ </li>+ {points.some((p) => p.fix_rank != null) ? (+ <li className="inline-flex items-center gap-1.5">+ <svg width="16" height="16" aria-hidden="true">+ <circle cx="8" cy="8" r="7" className="fill-[var(--color-bg-root)] stroke-[var(--color-text-primary)]" strokeWidth={1.25} />+ <text x="8" y="11" textAnchor="middle" fontSize={9} fontWeight={600} className="fill-[var(--color-text-primary)] font-mono">1</text>+ </svg>+ A Fix-first item, numbered by its place in Fix first+ </li>) : null}- </div>- </div>+ <li className="inline-flex items-center gap-1.5">+ <svg width="10" height="10" aria-hidden="true"><circle cx="5" cy="5" r="4" className="fill-[var(--color-accent-primary)]" /></svg>+ Selected+ </li>+ </ul>+ </section>);}++interface PointFieldProps {+ points: ImpactEffortPoint[];+ xs: Float64Array;+ ys: Float64Array;+ onHover: (i: number | null) => void;+ onPick: (i: number) => void;+}++function indexOf(e: PointerEvent<SVGGElement>): number | null {+ const raw = (e.target as Element).getAttribute?.("data-i");+ return raw == null ? null : Number(raw);+}++/**+ * Every point, drawn once per dataset. Handlers are delegated to the group so+ * no point carries its own closure, and hover state lives in the parent's+ * overlay marks, never here.+ */+const PointField = memo(function PointField({ points, xs, ys, onHover, onPick }: PointFieldProps) {+ return (+ <g+ data-testid="impact-effort-points"+ className="cursor-pointer"+ onPointerOver={(e) => {+ const i = indexOf(e);+ if (i != null) onHover(i);+ }}+ onPointerLeave={() => onHover(null)}+ onClick={(e) => {+ const i = indexOf(e as unknown as PointerEvent<SVGGElement>);+ if (i != null) onPick(i);+ }}+ >+ {points.map((p, i) =>+ p.fix_rank != null ? null : p.effort_basis === "plan" ? (+ <circle key={p.file_path} data-i={i} data-file={p.file_path} cx={xs[i]} cy={ys[i]} r={3} className="fill-[var(--color-text-tertiary)]" fillOpacity={0.35} />+ ) : (+ <circle key={p.file_path} data-i={i} data-file={p.file_path} cx={xs[i]} cy={ys[i]} r={2.75} className="fill-transparent stroke-[var(--color-text-tertiary)]" strokeOpacity={0.45} strokeWidth={1.25} />+ ),+ )}+ {/* Fix-first items last, so they sit on top of the field. Ink weight,+ not colour: orange stays for selection. */}+ {points.map((p, i) =>+ p.fix_rank == null ? null : (+ <g key={p.file_path} data-rank={p.fix_rank}>+ <circle data-i={i} data-file={p.file_path} cx={xs[i]} cy={ys[i]} r={7} className="fill-[var(--color-bg-root)] stroke-[var(--color-text-primary)]" strokeWidth={1.25} />+ <text x={xs[i]} y={(ys[i] ?? 0) + 3} textAnchor="middle" fontSize={9} fontWeight={600} pointerEvents="none" className="fill-[var(--color-text-primary)] font-mono">+ {p.fix_rank}+ </text>+ </g>+ ),+ )}+ </g>+ );+});diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsxindex ab97d62fa..d4754b1a1 100644--- a/packages/ui/src/health/refactoring-card.tsx+++ b/packages/ui/src/health/refactoring-card.tsx@@ -41,6 +41,8 @@ export interface HealthWorkItem {score: number;nloc: number;module?: string | null;+ /** A test file; labelled on the card. */+ is_test?: boolean;primary_biomarker: string;primary_severity: Severity;primary_reason: string;@@ -89,6 +91,13 @@ export interface HealthWorkItemCardProps {expandable?: boolean;/** Flash-highlight the card (e.g. after a quadrant dot click scrolled to it). */highlighted?: boolean;+ /** Bulk triage: whether this row is in the selection. */+ selected?: boolean;+ /**+ * Toggle this row in the bulk selection. The row stands for the finding it+ * names (`primary_finding_id`), so a row without one offers no checkbox.+ */+ onToggleSelect?: ((target: HealthWorkItem) => void) | undefined;}const effortLabel: Record<EffortBucket, string> = {@@ -109,6 +118,8 @@ export function HealthWorkItemCard({onLoadFindings,expandable = true,highlighted = false,+ selected = false,+ onToggleSelect,}: HealthWorkItemCardProps) {const [expanded, setExpanded] = useState(false);const [loaded, setLoaded] = useState<HealthWorkItemFinding[] | null>(null);@@ -157,6 +168,15 @@ export function HealthWorkItemCard({><div className="p-4 space-y-2"><div className="flex items-center gap-2 flex-wrap">+ {onToggleSelect && target.primary_finding_id ? (+ <input+ type="checkbox"+ checked={selected}+ onChange={() => onToggleSelect(target)}+ aria-label={`Select the ${biomarkerLabel(target.primary_biomarker)} finding in ${target.file_path}`}+ className="h-3.5 w-3.5 rounded border-[var(--color-border-default)] accent-[var(--color-accent-primary)]"+ />+ ) : null}{watch ? (<span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{HISTORY_LABEL}@@ -178,6 +198,11 @@ export function HealthWorkItemCard({{target.module}</span>) : null}+ {target.is_test ? (+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ test+ </span>+ ) : null}<spanclassName={`inline-block rounded px-1.5 py-0.5 text-[10px] uppercase font-semibold ${EFFORT_TINT[target.effort_bucket]}`}title={`Effort: ${effortLabel[target.effort_bucket]} (NLOC ${target.nloc})`}@@ -225,8 +250,12 @@ export function HealthWorkItemCard({) : null}</button><p className="text-xs text-[var(--color-text-secondary)] line-clamp-2">{target.primary_reason}</p>+ {/* The action comes from core, per marker; the card never writes one. */}{target.primary_suggestion ? (- <p className="text-xs text-[var(--color-text-tertiary)] italic line-clamp-3">+ <p className="text-xs text-[var(--color-text-primary)] line-clamp-3">+ <span className="mr-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Action+ </span>{target.primary_suggestion}</p>) : null}diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsxindex 3f5766a92..afd15862e 100644--- a/packages/ui/src/health/refactoring-target-list.tsx+++ b/packages/ui/src/health/refactoring-target-list.tsx@@ -34,6 +34,9 @@ export interface HealthWorkQueueListProps {emptyMessage?: string;/** File path of the card to flash-highlight (quadrant click). */highlightedPath?: string | null | undefined;+ /** Bulk triage selection, by file path. */+ selectedPaths?: ReadonlySet<string> | undefined;+ onToggleSelect?: ((target: HealthWorkItem) => void) | undefined;}export function HealthWorkQueueList({@@ -46,6 +49,8 @@ export function HealthWorkQueueList({refactoringOpportunityHref,emptyMessage = "No health work items match the current filters.",highlightedPath,+ selectedPaths,+ onToggleSelect,}: HealthWorkQueueListProps) {const [visible, setVisible] = useState(CARD_PAGE);@@ -108,6 +113,8 @@ export function HealthWorkQueueList({onLoadOpportunity={onLoadOpportunity}refactoringOpportunityHref={refactoringOpportunityHref}highlighted={highlightedPath === t.file_path}+ selected={selectedPaths?.has(t.file_path) ?? false}+ onToggleSelect={onToggleSelect}/>))}</div>diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsxindex a6180fab2..f0cf5aaca 100644--- a/packages/web/src/components/code-health/findings-tab.tsx+++ b/packages/web/src/components/code-health/findings-tab.tsx@@ -13,6 +13,7 @@ import { FindingsView, type CodeHealthAdapter } from "@repowise-dev/ui/health";import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";import {getHealthOverview,+ getHealthImpactEffort,getHealthWorkQueue,listHealthFindings,getHealthCoverage,@@ -51,6 +52,8 @@ export function FindingsTab({refactoringOpportunityHref(id, opportunityId),getHealthWorkQueue: (opts) =>getHealthWorkQueue(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),+ getImpactEffort: (opts) =>+ getHealthImpactEffort(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),updateFindingStatus: (findingId, status) =>updateFindingStatus(id, findingId, status),getCoverage: (opts) => getHealthCoverage(id, opts),diff --git a/tests/unit/health/test_impact_effort.py b/tests/unit/health/test_impact_effort.pynew file mode 100644index 000000000..968f06e50--- /dev/null+++ b/tests/unit/health/test_impact_effort.py@@ -0,0 +1,100 @@+"""The impact / effort plane: where each file sits, and what it states about itself."""++from __future__ import annotations++import json++from repowise.core.analysis.health.impact_effort import (+ EFFORT_MIDLINE_LINES,+ GAIN_MIDLINE_POINTS,+ build_impact_effort,+ fix_first_marks,+ plan_lines,+)+++def _file(path: str, nloc: int = 200, impact: float = 1.0) -> dict:+ return {"file_path": path, "nloc": nloc, "total_impact": impact}+++def _plan(path: str, gain: float, spans: list[tuple[int, int]]) -> dict:+ steps = [{"line_start": a, "line_end": b} for a, b in spans]+ return {"file_path": path, "recoverable_health": gain, "details_json": json.dumps({"steps": steps})}+++def test_a_planned_file_is_placed_by_its_plan() -> None:+ plane = build_impact_effort([_file("a.py", nloc=900, impact=4.0)], [_plan("a.py", 1.2, [(10, 19), (40, 49)])])++ (point,) = plane.points+ assert point.effort_basis == "plan"+ assert point.effort_lines == 20+ assert point.recoverable_health == 1.2+++def test_a_file_without_a_plan_is_placed_by_its_size_and_deduction() -> None:+ plane = build_impact_effort([_file("b.py", nloc=320, impact=2.5)])++ (point,) = plane.points+ assert (point.effort_basis, point.effort_lines, point.recoverable_health) == ("file", 320, 2.5)+++def test_a_plan_that_recovers_nothing_does_not_speak_for_the_file() -> None:+ plane = build_impact_effort([_file("c.py", nloc=80, impact=3.0)], [_plan("c.py", 0.0, [(1, 5)])])++ assert plane.points[0].effort_basis == "file"+ assert plane.points[0].recoverable_health == 3.0+++def test_a_plan_with_no_span_falls_back_to_the_file() -> None:+ assert plan_lines({"steps": [{"line_start": None, "line_end": None}]}) == 0+ plane = build_impact_effort([_file("d.py", nloc=60)], [_plan("d.py", 1.0, [])])+ assert plane.points[0].effort_basis == "file"+++def test_effort_is_never_below_one_line_so_a_log_axis_can_hold_it() -> None:+ plane = build_impact_effort([_file("empty.py", nloc=0)])+ assert plane.points[0].effort_lines == 1+++def test_the_cap_keeps_the_largest_gains_and_says_how_many_were_left_out() -> None:+ files = [_file(f"f{i}.py", impact=float(i)) for i in range(10)]++ plane = build_impact_effort(files, cap=3)++ assert [p.file_path for p in plane.points] == ["f9.py", "f8.py", "f7.py"]+ assert (plane.plotted, plane.total, plane.cap) == (3, 10, 3)+++def test_midlines_are_fixed_whatever_the_data() -> None:+ small = build_impact_effort([_file("a.py", nloc=5, impact=0.1)])+ large = build_impact_effort([_file("b.py", nloc=5000, impact=40.0)])++ for plane in (small, large):+ assert plane.effort_midline_lines == EFFORT_MIDLINE_LINES+ assert plane.gain_midline_points == GAIN_MIDLINE_POINTS+++def test_a_file_is_marked_by_its_first_fix_first_item() -> None:+ items = [+ {"rank": 0, "tier": "now", "target": {"file_path": "a.py"}},+ {"rank": 1, "tier": "next", "target": {"file_path": "b.py"}},+ {"rank": 4, "tier": "later", "target": {"file_path": "a.py"}},+ ]+ marks = fix_first_marks(items)+ assert marks == {"a.py": ("now", 1), "b.py": ("next", 2)}++ plane = build_impact_effort([_file("a.py"), _file("c.py")], marks=marks)+ got = {p.file_path: (p.tier, p.fix_rank) for p in plane.points}+ assert got == {"a.py": ("now", 1), "c.py": (None, None)}+++def test_as_dict_carries_the_scope_fields() -> None:+ body = build_impact_effort([_file("a.py")]).as_dict()+ assert set(body) == {+ "points",+ "plotted",+ "total",+ "cap",+ "effort_midline_lines",+ "gain_midline_points",+ }diff --git a/tests/unit/health/test_suggestions.py b/tests/unit/health/test_suggestions.pyindex 1f5fedac4..157f93d97 100644--- a/tests/unit/health/test_suggestions.py+++ b/tests/unit/health/test_suggestions.py@@ -19,6 +19,17 @@ def test_suggestion_unknown_biomarker_falls_back():assert "health-rules.json" in text # fallback hints at suppression+def test_every_registered_biomarker_has_its_own_action():+ # The Findings tab shows this sentence as each row's action line, so a+ # marker without one would fall back to the generic "review this" text.+ from repowise.core.analysis.health.biomarkers.registry import registered_biomarkers+ from repowise.core.analysis.health.suggestions import _TEMPLATES++ names = {d.name for d in registered_biomarkers()}+ names |= {"ungoverned_hotspot", "stale_governance", "contradictory_decision"}+ assert sorted(n for n in names if n not in _TEMPLATES) == []++def test_annotate_finding_adds_suggestion_field():out = annotate_finding({"biomarker_type": "nested_complexity", "severity": "high"})assert out["biomarker_type"] == "nested_complexity"diff --git a/tests/unit/server/test_health_impact_effort.py b/tests/unit/server/test_health_impact_effort.pynew file mode 100644index 000000000..984be6764--- /dev/null+++ b/tests/unit/server/test_health_impact_effort.py@@ -0,0 +1,97 @@+"""The impact / effort plane route: the whole filtered set, never one page of it."""++from __future__ import annotations++from dataclasses import replace++from repowise.core.analysis.health.impact_effort import (+ EFFORT_MIDLINE_LINES,+ GAIN_MIDLINE_POINTS,+ PLOT_CAP,+)++from .test_health_work_queue_controls import _finding, _metric, _queue, _repo+++async def _plane(client, repo_id, query: str = ""):+ url = f"/api/repos/{repo_id}/health/impact-effort"+ response = await client.get(f"{url}?{query}" if query else url)+ assert response.status_code == 200, response.text+ return response.json()+++async def test_the_plane_holds_every_file_the_queue_counts(client, session, tmp_path) -> None:+ metrics = [_metric(f"f{i}.py", 4.0, nloc=50 + i) for i in range(7)]+ findings = [_finding(f"f{i}.py", impact=1.0 + i) for i in range(7)]+ repo_id = await _repo(client, session, tmp_path, metrics, findings)++ page = await _queue(client, repo_id, "limit=2")+ plane = await _plane(client, repo_id)++ assert len(page["targets"]) == 2+ assert plane["total"] == plane["plotted"] == page["total"] == 7+ assert plane["cap"] == PLOT_CAP+ assert plane["effort_midline_lines"] == EFFORT_MIDLINE_LINES+ assert plane["gain_midline_points"] == GAIN_MIDLINE_POINTS+ first = plane["points"][0]+ # No plan stored, so the file speaks for itself.+ assert first == {+ "file_path": "f6.py",+ "effort_lines": 56,+ "effort_basis": "file",+ "recoverable_health": 7.0,+ "tier": first["tier"],+ "fix_rank": first["fix_rank"],+ }+++async def test_history_only_files_are_never_plotted(client, session, tmp_path) -> None:+ repo_id = await _repo(+ client,+ session,+ tmp_path,+ [_metric("a.py", 4.0), _metric("b.py", 5.0)],+ [_finding("a.py", "change_entropy"), _finding("b.py")],+ )++ plane = await _plane(client, repo_id)++ assert [p["file_path"] for p in plane["points"]] == ["b.py"]+ assert plane["history_only_excluded"] == 1+++async def test_the_queue_filters_narrow_the_plane_too(client, session, tmp_path) -> None:+ repo_id = await _repo(+ client,+ session,+ tmp_path,+ [_metric("src/a.py", 4.0), _metric("lib/b.py", 5.0)],+ [_finding("src/a.py"), _finding("lib/b.py", severity="low")],+ )++ by_search = await _plane(client, repo_id, "search=src/")+ by_severity = await _plane(client, repo_id, "severity=low")++ assert [p["file_path"] for p in by_search["points"]] == ["src/a.py"]+ assert [p["file_path"] for p in by_severity["points"]] == ["lib/b.py"]+++async def test_a_queue_row_says_whether_it_is_a_test(client, session, tmp_path) -> None:+ repo_id = await _repo(+ client,+ session,+ tmp_path,+ [_metric("a.py", 4.0), replace(_metric("tests/test_a.py", 5.0), is_test=True)],+ [_finding("a.py"), _finding("tests/test_a.py")],+ )++ rows = {t["file_path"]: t["is_test"] for t in (await _queue(client, repo_id))["targets"]}+ production = await _queue(client, repo_id, "scope=production")++ assert rows == {"a.py": False, "tests/test_a.py": True}+ assert [t["file_path"] for t in production["targets"]] == ["a.py"]+++async def test_an_unknown_repository_is_a_404(client) -> None:+ response = await client.get("/api/repos/nope/health/impact-effort")+ assert response.status_code == 404