Skip to content

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

feat(health): make the findings tab one triage list that pages (#2200)

Raghav Chamadiya2fee3e2b9f9d
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index 8eef9d10c..2b7a55829 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -92,7 +92,11 @@ export async function listHealthFindings(
biomarker_type?: string;
file_path?: string;
min_severity?: string;
+ /** Exact severities, comma-separated. Overrides `min_severity`. */
+ severity?: string;
dimension?: string;
+ /** Comma-separated statuses, or `"all"`. Defaults to open work. */
+ status?: string;
limit?: number;
scope?: HealthScope;
counts?: HealthCounts;
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index f7f078893..72cbe812c 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -381,21 +381,30 @@ async def get_health_findings(
*,
biomarker_type: str | None = None,
min_severity: str | None = None,
+ severity: str | None = None,
file_path: str | None = None,
dimension: str | None = None,
exclude_dimensions: tuple[str, ...] | None = None,
status: str = "open",
) -> list[HealthFinding]:
- """Open findings for one repository, ordered by health impact.
+ """Findings for one repository, ordered by health impact.
``exclude_dimensions`` is how a general queue keeps a dimension out of a
ranking it does not share units with. It is ignored when ``dimension``
names one explicitly, so asking for a dimension always returns it.
+
+ ``severity`` is an exact comma-separated selection and wins over the
+ ``min_severity`` threshold when both are given.
+
+ ``status`` defaults to open work. It also accepts a comma-separated list of
+ ``open`` / ``acknowledged`` / ``resolved`` / ``false_positive``, or ``all``
+ to drop the filter, so a triage surface can show what it has already
+ reviewed without a second read.
"""
- q = select(HealthFinding).where(
- HealthFinding.repository_id == repository_id,
- HealthFinding.status == status,
- )
+ q = select(HealthFinding).where(HealthFinding.repository_id == repository_id)
+ statuses = [s.strip() for s in status.split(",") if s.strip()]
+ if "all" not in statuses:
+ q = q.where(HealthFinding.status.in_(statuses or ["open"]))
if dimension is None and exclude_dimensions:
q = q.where(
or_(
@@ -419,7 +428,12 @@ async def get_health_findings(
q = q.where(or_(HealthFinding.dimension == "defect", HealthFinding.dimension.is_(None)))
else:
q = q.where(HealthFinding.dimension == dimension)
- if min_severity is not None:
+ exact = [v.strip().lower() for v in (severity or "").split(",") if v.strip()]
+ if exact:
+ # An exact selection answers the same question the queue's chips do, so
+ # the two levels of the list agree on which findings a row holds.
+ q = q.where(HealthFinding.severity.in_(exact))
+ elif min_severity is not None:
# Severity order: low < medium < high < critical
order = {"low": 0, "medium": 1, "high": 2, "critical": 3}
threshold = order.get(min_severity, 0)
diff --git a/packages/server/src/repowise/server/routers/code_health/file_filters.py b/packages/server/src/repowise/server/routers/code_health/file_filters.py
new file mode 100644
index 000000000..0ef6cae15
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/code_health/file_filters.py
@@ -0,0 +1,53 @@
+"""Row filters shared by the file inventory and the work queue.
+
+Both surfaces narrow the same per-file metric rows by the same five controls,
+and a queue that disagreed with the inventory about what "untested" means
+would be a second answer to one question.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import Any
+
+from repowise.core.analysis.health.grading import GOOD_MIN
+from repowise.core.persistence import crud
+
+FAILING_DESCRIPTION = f"score below {GOOD_MIN}, where green starts"
+
+
+async def hotspot_paths(session: Any, repo_id: str) -> set[str]:
+ """Paths git metadata marks as hotspots."""
+ git_meta = await crud.get_all_git_metadata(session, repo_id)
+ return {p for p, gm in git_meta.items() if getattr(gm, "is_hotspot", False)}
+
+
+def metric_filter(
+ *,
+ search: str | None = None,
+ module: str | None = None,
+ only_hotspots: bool = False,
+ only_untested: bool = False,
+ only_failing: bool = False,
+ hotspots: set[str] | None = None,
+) -> Callable[[Any], bool]:
+ """A predicate over metric rows for the inventory/queue controls.
+
+ ``only_failing`` is the band edge green starts at, so "failing" here means
+ the same thing the page's colour does.
+ """
+ needle = search.lower() if search else None
+ hotspot_set = hotspots or set()
+
+ def keep(m: Any) -> bool:
+ if needle and needle not in m.file_path.lower():
+ return False
+ if module and not m.file_path.startswith(module):
+ return False
+ if only_hotspots and m.file_path not in hotspot_set:
+ return False
+ if only_untested and m.has_test_file:
+ return False
+ return not (only_failing and m.score >= GOOD_MIN)
+
+ return keep
diff --git a/packages/server/src/repowise/server/routers/code_health/files_routes.py b/packages/server/src/repowise/server/routers/code_health/files_routes.py
index 50ce386db..1808e9740 100644
--- a/packages/server/src/repowise/server/routers/code_health/files_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/files_routes.py
@@ -16,6 +16,7 @@ from repowise.server.deps import get_db_session
from ._router import router
from .breakdown import _score_breakdown_from_findings
from .counts import CountsQuery, project
+from .file_filters import FAILING_DESCRIPTION, hotspot_paths, metric_filter
from .loaders import _attach_symbol_ids, _load_file_signals
from .scope import ScopeQuery, narrow
from .serializers import (
@@ -49,7 +50,7 @@ async def list_health_files(
module: str | None = Query(None, description="Filter to a module prefix"),
only_hotspots: bool = Query(False),
only_untested: bool = Query(False),
- only_failing: bool = Query(False, description="score < 7"),
+ only_failing: bool = Query(False, description=FAILING_DESCRIPTION),
fields: str = Query(
"full",
pattern="^(full|summary)$",
@@ -72,23 +73,15 @@ async def list_health_files(
# describe the same population the score does.
metrics, _unscored = project(counts, metrics)
- hotspot_paths: set[str] = set()
- if only_hotspots:
- git_meta = await crud.get_all_git_metadata(session, repo_id)
- hotspot_paths = {p for p, gm in git_meta.items() if getattr(gm, "is_hotspot", False)}
-
- def _keep(m: Any) -> bool:
- if search and search.lower() not in m.file_path.lower():
- return False
- if module and not m.file_path.startswith(module):
- return False
- if only_hotspots and m.file_path not in hotspot_paths:
- return False
- if only_untested and m.has_test_file:
- return False
- return not (only_failing and m.score >= 7)
-
- filtered = [m for m in metrics if _keep(m)]
+ keep = 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,
+ )
+ filtered = [m for m in metrics if keep(m)]
def _key(m: Any):
v = getattr(m, sort, None)
diff --git a/packages/server/src/repowise/server/routers/code_health/findings_routes.py b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
index 45fe5f552..5f14b81f3 100644
--- a/packages/server/src/repowise/server/routers/code_health/findings_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
@@ -21,6 +21,11 @@ from .counts import CountsQuery
from .loaders import _attach_symbol_ids
from .scope import ScopeQuery, narrow
from .serializers import _finding_to_dict
+from .statuses import (
+ ALLOWED_STATUSES,
+ STATUS_FILTER_DESCRIPTION,
+ parse_status_filter,
+)
@router.get(
@@ -31,14 +36,18 @@ async def list_health_findings(
repo_id: str,
biomarker_type: str | None = Query(None),
file_path: str | None = Query(None),
- min_severity: str | None = Query(None),
+ min_severity: str | None = Query(None, description="Severity floor"),
+ severity: str | None = Query(
+ None, description="Exact severities, comma-separated. Overrides min_severity."
+ ),
dimension: str | None = Query(None),
+ status: str = Query("open", description=STATUS_FILTER_DESCRIPTION),
limit: int = Query(100, ge=1, le=1000),
scope: str = ScopeQuery,
counts: str = CountsQuery,
session: AsyncSession = Depends(get_db_session),
) -> list[dict]:
- """Open findings, ranked by health impact.
+ """Findings, ranked by health impact. Open work unless ``status`` says otherwise.
Performance is out of the unfiltered list by default. Its findings carry a
health impact of zero by construction, so ranking them here sorts them
@@ -52,7 +61,9 @@ async def list_health_findings(
biomarker_type=biomarker_type,
file_path=file_path,
min_severity=min_severity,
+ severity=severity,
dimension=dimension,
+ status=parse_status_filter(status),
exclude_dimensions=("performance",),
)
# A finding carries a path, not ``is_test``, so narrowing it needs the
@@ -74,9 +85,6 @@ class FindingStatusUpdate(BaseModel):
status: str = Field(..., description="open | acknowledged | resolved | false_positive")
-_ALLOWED_STATUSES = {"open", "acknowledged", "resolved", "false_positive"}
-
-
@router.patch(
"/api/repos/{repo_id}/health/findings/{finding_id}",
response_model=HealthFindingResponse,
@@ -87,9 +95,9 @@ async def update_finding_status(
payload: FindingStatusUpdate,
session: AsyncSession = Depends(get_db_session),
) -> dict:
- if payload.status not in _ALLOWED_STATUSES:
+ if payload.status not in ALLOWED_STATUSES:
raise HTTPException(
- status_code=400, detail=f"status must be one of {sorted(_ALLOWED_STATUSES)}"
+ status_code=400, detail=f"status must be one of {sorted(ALLOWED_STATUSES)}"
)
f = await crud.update_health_finding_status(session, finding_id, payload.status)
if f is None:
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index 3846f06d9..e6dd8c37f 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
@@ -19,7 +19,9 @@ from repowise.server.schemas import HealthWorkQueueResponse
from ._router import router
from .counts import CountsQuery, project
+from .file_filters import FAILING_DESCRIPTION, hotspot_paths, metric_filter
from .scope import ScopeQuery, narrow
+from .statuses import STATUS_FILTER_DESCRIPTION, parse_status_filter
_SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}
@@ -37,10 +39,11 @@ _SORT_KEYS = {
# top and sorting on it alone returns them in dict-insertion order.
# ``total_impact`` is the same pre-clamp deduction magnitude the crud layer
# ranks metrics by — but summed over the findings that survived this
- # request's ``biomarker`` / ``min_severity`` filters, so under a filter this
- # ranks by the filtered depth rather than the file's full depth. That is
- # what a filtered queue should do; it just means the order is not expected
- # to match /health/files once a filter is on.
+ # request's finding-level filters (biomarker, severity, min_severity,
+ # dimension, status), so under a filter this ranks by the filtered depth
+ # rather than the file's full depth. That is what a filtered queue should
+ # do; it just means the order is not expected to match /health/files once
+ # a filter is on.
"score": lambda t: (t["score"], -t["total_impact"], t["file_path"]),
"finding_count": lambda t: -t["finding_count"],
}
@@ -60,9 +63,19 @@ def _effort_for_nloc(nloc: int) -> str:
async def health_work_queue(
repo_id: str,
limit: int = Query(200, ge=1, le=500),
+ offset: int = Query(0, ge=0),
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),
+ min_severity: str | None = Query(None, description="Severity floor"),
+ severity: str | None = Query(
+ None, description="Exact severities, comma-separated. Overrides min_severity."
+ ),
+ dimension: str | None = Query(None, description="defect | maintainability | performance"),
+ status: str = Query("open", description=STATUS_FILTER_DESCRIPTION),
+ search: str | None = Query(None, description="Substring filter on file_path"),
+ only_hotspots: bool = Query(False),
+ 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)$"
@@ -86,16 +99,43 @@ async def health_work_queue(
raise HTTPException(status_code=404, detail="Repository not found")
metrics = await crud.get_health_metrics(session, repo_id)
- findings = await crud.get_health_findings(session, repo_id)
+ findings = await crud.get_health_findings(
+ session,
+ repo_id,
+ dimension=dimension,
+ status=parse_status_filter(status),
+ # As the findings list does, so a row's count and the list behind it
+ # agree. Performance carries zero health impact and ranks by cause on
+ # its own surface; ``dimension=performance`` still returns it.
+ exclude_dimensions=("performance",),
+ )
metrics, findings = narrow(scope, metrics, findings)
metrics, findings, _unscored = project(counts, metrics, findings)
- metric_by_path = {m.file_path: m for m in metrics}
+
+ 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,
+ )
+ 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()}
+ exact_severities = picked or None
by_file: dict[str, list[Any]] = {}
for f in findings:
if biomarker and f.biomarker_type != biomarker:
continue
- if min_severity:
+ if exact_severities is not None:
+ if (f.severity or "").lower() not in exact_severities:
+ continue
+ elif min_severity:
order = _SEVERITY_ORDER
if order.get(f.severity, 0) < order.get(min_severity, 0):
continue
@@ -106,19 +146,21 @@ async def health_work_queue(
targets: list[dict] = []
for file_path, fs in by_file.items():
- if module and not file_path.startswith(module):
- continue
m = metric_by_path.get(file_path)
- # No metric row means this reading cannot score the file: under
- # ``code_shape`` that is a row with no recorded split. Ranking it on a
- # stand-in 10.0 would put an unmeasured file at the top of a list
- # ordered by how bad things are.
+ # Absent means either filtered out above, or a file this reading
+ # cannot score: under ``code_shape``, a row with no recorded split.
+ # Ranking that on a stand-in 10.0 would put an unmeasured file at the
+ # top of a list ordered by how bad things are.
if m is None:
continue
nloc = m.nloc
score = m.score
primary = primary_finding(fs)
- total_impact = round(sum(x.health_impact for x in fs), 3)
+ # Impact, and therefore the ranking, counts only findings still open:
+ # ``score`` on this row was computed from open findings, and a file
+ # whose findings were all dismissed is not work to rank near the top.
+ open_fs = [x for x in fs if (getattr(x, "status", None) or "open") == "open"]
+ total_impact = round(sum(x.health_impact for x in open_fs), 3)
effort_bucket = _effort_for_nloc(nloc)
if effort_rank[effort_bucket] > max_effort_rank:
continue
@@ -140,6 +182,7 @@ async def health_work_queue(
"primary_finding_id": primary.id,
"total_impact": total_impact,
"finding_count": len(fs),
+ "open_finding_count": len(open_fs),
"biomarkers": sorted({x.biomarker_type for x in fs}),
"effort_bucket": effort_bucket,
"impact_per_effort": ratio,
@@ -147,4 +190,12 @@ async def health_work_queue(
)
targets.sort(key=_SORT_KEYS[sort])
- return {"targets": targets[:limit], "total": len(targets)}
+ # Both counts, because the view lists files but triages findings: "50 of
+ # 812 files" alone leaves the size of the work unsaid.
+ return {
+ "targets": targets[offset : offset + limit],
+ "total": len(targets),
+ "finding_total": sum(t["finding_count"] for t in targets),
+ "offset": offset,
+ "limit": limit,
+ }
diff --git a/packages/server/src/repowise/server/routers/code_health/statuses.py b/packages/server/src/repowise/server/routers/code_health/statuses.py
new file mode 100644
index 000000000..55978d6c5
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/code_health/statuses.py
@@ -0,0 +1,32 @@
+"""The finding status vocabulary, shared by the routes that read and write it."""
+
+from __future__ import annotations
+
+from fastapi import HTTPException
+
+ALLOWED_STATUSES = frozenset({"open", "acknowledged", "resolved", "false_positive"})
+
+STATUS_FILTER_DESCRIPTION = (
+ "Comma-separated statuses (open | acknowledged | resolved | false_positive), "
+ "or 'all'. Defaults to open work."
+)
+
+
+def parse_status_filter(value: str) -> str:
+ """Validate a status filter, or 400.
+
+ Unvalidated, a typo returns ``200 []`` — indistinguishable from a filter
+ that genuinely matches nothing, which is the harder bug to notice.
+ """
+ wanted = [v.strip() for v in value.split(",") if v.strip()]
+ if not wanted:
+ return "open"
+ if wanted == ["all"]:
+ return "all"
+ unknown = sorted(set(wanted) - ALLOWED_STATUSES)
+ if unknown:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unknown status: {', '.join(unknown)}. Allowed: {', '.join(sorted(ALLOWED_STATUSES))}, all",
+ )
+ return ",".join(wanted)
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index c6379340e..d4e5a1b54 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -186,6 +186,9 @@ class HealthWorkItem(BaseModel):
#: Pre-clamp deduction magnitude over the findings that passed the filters.
total_impact: float
finding_count: int
+ #: How many of those are still open. Equal to ``finding_count`` under
+ #: the default status filter; lower once dismissed work is shown.
+ open_finding_count: int = 0
biomarkers: list[str] = []
#: S | M | L | XL
effort_bucket: str
@@ -194,4 +197,10 @@ class HealthWorkItem(BaseModel):
class HealthWorkQueueResponse(BaseModel):
targets: list[HealthWorkItem] = []
+ #: Files matching the filters, before the page slice.
total: int = 0
+ #: Findings across those files, so the page can size the work, not just
+ #: the file count it is paging through.
+ finding_total: int = 0
+ offset: int = 0
+ limit: int = 0
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index a5386506d..8a06591d3 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1597,6 +1597,7 @@ export interface HealthWorkItem {
primary_finding_id: string;
total_impact: number;
finding_count: number;
+ open_finding_count?: number;
biomarkers?: string[];
effort_bucket: string;
impact_per_effort: number;
@@ -1605,6 +1606,9 @@ export interface HealthWorkItem {
export interface HealthWorkQueueResponse {
targets?: HealthWorkItem[];
total?: number;
+ finding_total?: number;
+ offset?: number;
+ limit?: number;
}
export interface HotFilesGraphResponse {
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index d53328bc0..7f62e9d27 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -1079,6 +1079,11 @@ export interface HealthWorkItem {
primary_finding_id?: string;
total_impact: number;
finding_count: number;
+ /**
+ * How many of those are still open. Equal to `finding_count` under the
+ * default status filter. Optional: an older backend does not send it.
+ */
+ open_finding_count?: number;
biomarkers: string[];
effort_bucket: "S" | "M" | "L" | "XL";
impact_per_effort: number;
@@ -1102,15 +1107,38 @@ export interface HealthWorkItem {
export interface HealthWorkQueueResponse {
targets: HealthWorkItem[];
+ /** Files matching the filters, before the page slice. */
total: number;
+ /**
+ * Findings across those files. The view lists files but triages findings, so
+ * the file count alone leaves the size of the work unsaid. Optional: an older
+ * backend does not send it and the view omits the clause rather than
+ * inventing one.
+ */
+ finding_total?: number;
+ offset?: number;
+ limit?: number;
}
export interface HealthWorkQueueQuery {
counts?: HealthCounts;
limit?: number;
+ offset?: number;
module?: string;
biomarker?: string;
+ /** Severity floor. Ignored by the server when `severity` is given. */
min_severity?: string;
+ /** Exact severities, comma-separated. */
+ severity?: string;
+ dimension?: HealthDimension;
+ /** Comma-separated statuses, or `"all"`. Defaults to open work. */
+ status?: string;
+ /** Substring filter on `file_path`. */
+ search?: string;
+ only_hotspots?: boolean;
+ only_untested?: boolean;
+ /** Files below the score green starts at. */
+ only_failing?: boolean;
max_effort?: string;
sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";
/** Which half of the repository to describe. Defaults to `"all"`. */
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index 42a71823a..94745c532 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -25,7 +25,11 @@ export interface CodeHealthFindingsQuery {
biomarker_type?: string;
file_path?: string;
min_severity?: string;
+ /** Exact severities, comma-separated. Overrides `min_severity`. */
+ severity?: string;
dimension?: string;
+ /** Comma-separated statuses, or `"all"`. Defaults to open work. */
+ status?: string;
limit?: number;
scope?: HealthScope;
}
@@ -76,7 +80,12 @@ export interface CodeHealthAdapter {
): Promise<Paginated<HealthFinding>>;
/** Fetch one exact canonical plan for the performance drawer. */
getRefactoringPlan?(planId: string): Promise<RefactoringPlan>;
- listFiles(opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
+ /**
+ * @deprecated Unused. The repo's Files page owns the file inventory; the
+ * health views are triage surfaces and list only what carries findings.
+ * Optional so a host can stop binding it without breaking its build.
+ */
+ listFiles?(opts?: HealthFilesQuery): Promise<HealthFilesResponse>;
getHealthWorkQueue?(
opts?: HealthWorkQueueQuery,
): Promise<HealthWorkQueueResponse>;
diff --git a/packages/ui/src/health/code-health-controls.tsx b/packages/ui/src/health/code-health-controls.tsx
index 6f863518e..2d07be5fe 100644
--- a/packages/ui/src/health/code-health-controls.tsx
+++ b/packages/ui/src/health/code-health-controls.tsx
@@ -62,7 +62,7 @@ export function FilterChip({
);
}
-/** Segmented toggle for a single axis (Queue / All files, prompt target agent). */
+/** Segmented toggle for a single axis (e.g. the prompt's target agent). */
export function ViewToggle<T extends string>({
value,
options,
diff --git a/packages/ui/src/health/file-table.tsx b/packages/ui/src/health/file-table.tsx
deleted file mode 100644
index 9d8bd6c14..000000000
--- a/packages/ui/src/health/file-table.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-"use client";
-
-import { useMemo } from "react";
-import { FileText } from "lucide-react";
-import { EmptyState } from "../shared/empty-state";
-import {
- ResponsiveTable,
- type ResponsiveColumn,
-} from "../shared/responsive-table";
-import { biomarkerLabel } from "./biomarker-glossary";
-import { scoreBadgeClass } from "./tokens";
-
-export interface HealthFileRow {
- file_path: string;
- score: number;
- max_ccn: number;
- max_nesting: number;
- nloc: number;
- has_test_file: boolean;
- line_coverage_pct?: number | null;
- module?: string | null;
- duplication_pct?: number | null;
- /** Dominant-cause lead: the worst finding's biomarker + reason (P3). */
- primary_biomarker?: string | null;
- primary_reason?: string | null;
- /** Summed pre-floor `health_impact` — the depth behind a floored score (P1). */
- total_deduction?: number | null;
-}
-
-export type FileSortField =
- | "score"
- | "max_ccn"
- | "max_nesting"
- | "nloc"
- | "duplication_pct"
- | "line_coverage_pct"
- | "file_path";
-
-export interface HealthFileTableProps {
- files: HealthFileRow[];
- sortField?: FileSortField;
- sortOrder?: "asc" | "desc";
- onSort?: (field: FileSortField) => void;
- onSelect?: (row: HealthFileRow) => void;
- selectedPath?: string | null;
- emptyMessage?: string;
-}
-
-function num(value: number): string {
- return String(value);
-}
-
-function pct(value: number | null | undefined): string {
- return value == null ? "—" : `${value.toFixed(0)}%`;
-}
-
-export function HealthFileTable({
- files,
- sortField = "score",
- sortOrder = "asc",
- onSort,
- onSelect,
- selectedPath,
- emptyMessage,
-}: HealthFileTableProps) {
- // Two floored files both read 1.0; break that tie by deduction magnitude so
- // the deeper problem sorts first. The OSS server now does this in the crud
- // layer, which makes this a no-op there — but this component is published and
- // the hosted backend still sorts on score alone, so it stays as that
- // deployment's only tiebreak until the same ordering lands there.
- //
- // It can only ever refine the page it was handed. Recovering a file the
- // server left *off* the page needs the server-side sort; that is why this is
- // a fallback and not the fix.
- const rows = useMemo(() => {
- if (sortField !== "score") return files;
- const dir = sortOrder === "desc" ? -1 : 1;
- return [...files].sort((a, b) => {
- if (a.score !== b.score) return (a.score - b.score) * dir;
- return (b.total_deduction ?? 0) - (a.total_deduction ?? 0);
- });
- }, [files, sortField, sortOrder]);
-
- const columns: ResponsiveColumn<HealthFileRow>[] = [
- {
- key: "file_path",
- header: "File",
- priority: 1,
- sortable: true,
- cellClassName: "text-[var(--color-text-primary)] max-w-[440px]",
- render: (f) => (
- <span className="flex min-w-0 flex-col gap-0.5">
- <span className="flex items-center gap-1.5 min-w-0 font-mono text-xs">
- <FileText className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
- <span className="truncate" title={f.file_path}>
- {f.file_path}
- </span>
- </span>
- {f.primary_biomarker ? (
- <span
- className="truncate pl-[18px] text-[11px] text-[var(--color-text-tertiary)]"
- title={f.primary_reason ?? undefined}
- >
- <span className="font-medium text-[var(--color-text-secondary)]">
- {biomarkerLabel(f.primary_biomarker)}
- </span>
- {f.primary_reason ? ` — ${f.primary_reason}` : ""}
- </span>
- ) : null}
- </span>
- ),
- },
- {
- key: "score",
- header: "Score",
- align: "right",
- priority: 1,
- sortable: true,
- render: (f) => (
- <span className="inline-flex flex-col items-end gap-0.5">
- <span
- className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}
- >
- {f.score.toFixed(1)}
- </span>
- {/* Depth behind a floored score: two files that both print 1.0 are
- distinguishable by their summed deductions (P1 false-flag fix). */}
- {f.score <= 1 && f.total_deduction != null ? (
- <span
- className="text-[10px] tabular-nums text-[var(--color-error)]"
- title="Total deductions behind this floored score"
- >
- −{f.total_deduction.toFixed(1)}
- </span>
- ) : null}
- </span>
- ),
- },
- {
- key: "max_ccn",
- header: "CCN",
- align: "right",
- priority: 2,
- sortable: true,
- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
- render: (f) => num(f.max_ccn),
- },
- {
- key: "max_nesting",
- header: "Nest",
- align: "right",
- priority: 3,
- sortable: true,
- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
- render: (f) => num(f.max_nesting),
- },
- {
- key: "nloc",
- header: "NLOC",
- align: "right",
- priority: 3,
- sortable: true,
- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
- render: (f) => num(f.nloc),
- },
- {
- key: "duplication_pct",
- header: "Dup %",
- mobileLabel: "Dup",
- align: "right",
- priority: 2,
- sortable: true,
- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
- render: (f) => pct(f.duplication_pct),
- },
- {
- key: "line_coverage_pct",
- header: "Cov",
- align: "right",
- priority: 2,
- sortable: true,
- cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
- render: (f) => pct(f.line_coverage_pct),
- },
- {
- key: "tests",
- header: "Tests",
- align: "center",
- priority: 3,
- cellClassName: "text-xs",
- render: (f) =>
- f.has_test_file ? (
- <span className="text-[var(--color-success)]">✓</span>
- ) : (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- ),
- },
- ];
-
- return (
- <ResponsiveTable
- columns={columns}
- rows={rows}
- rowKey={(f) => f.file_path}
- onRowClick={onSelect}
- selectedKey={selectedPath ?? null}
- sortField={sortField}
- sortOrder={sortOrder}
- onSort={onSort ? (key) => onSort(key as FileSortField) : undefined}
- empty={
- <EmptyState
- title="No files match"
- description={emptyMessage ?? "No files match the current filters."}
- />
- }
- />
- );
-}
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index e33e40eff..4c0865677 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -1,22 +1,21 @@
"use client";
/**
- * Findings view — the engineer's workbench. The ranked fix-next queue
- * (health work items + file inventory) and the function-level /
- * hidden-coupling panels. Performance has its own causal-opportunity view.
+ * Findings — the triage list. One view at three levels: files ranked by
+ * leverage, expandable to their findings, each finding naming its line and
+ * linking to a plan where one exists. The function-level and hidden-coupling
+ * panels sit below it; performance has its own causal-opportunity view.
*
- * Split out of {@link TriageView} so the landing surface stays an airy
- * proof + map overview and the dense drill-down lives behind its own tab.
* Presentation + orchestration only: the host injects data, links, and the
* file-detail drawer through a {@link CodeHealthAdapter}.
*/
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import useSWR from "swr";
import { Search } from "lucide-react";
import type {
+ HealthDimension,
HealthFinding,
- HealthFilesResponse,
HealthOverviewResponse,
HealthWorkQueueQuery,
HealthWorkQueueResponse,
@@ -27,7 +26,6 @@ import { Button } from "../ui/button";
import { EmptyState } from "../shared/empty-state";
import { AiPromptModal } from "./ai-prompt-modal";
-import { HealthFileTable, type FileSortField } from "./file-table";
import { HotFunctionsPanel } from "./hot-functions-panel";
import { HiddenCouplingList } from "./hidden-coupling-list";
import {
@@ -36,23 +34,32 @@ import {
type HealthWorkItem,
} from "./refactoring-target-list";
import type { HealthWorkItemFinding } from "./refactoring-card";
-import { FilterSelect, FilterChip, ViewToggle } from "./code-health-controls";
+import { FilterSelect, FilterChip } from "./code-health-controls";
import { ImpactEffortQuadrant } from "./impact-effort-quadrant";
import { biomarkerLabel } from "./biomarker-glossary";
import { buildAiPrompt } from "./ai-prompt-builder";
-import { type Severity } from "./tokens";
+import { SEVERITY_LABEL, type Severity } from "./tokens";
import type { CodeHealthAdapter } from "./code-health-adapter";
const PAGE_SIZE = 50;
-const QUEUE_PAGE = 200;
-const QUEUE_MAX = 500;
+const SEARCH_DEBOUNCE_MS = 300;
type GroupBy = "none" | "biomarker" | "module" | "effort";
-type QueueView = "queue" | "files";
/** Function-level biomarker types fed to the Hot functions panel. */
const HOT_FN_TYPES = ["function_hotspot", "code_age_volatility", "complex_conditional"];
+/** Worst first, matching how the list is read. */
+const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
+
+/**
+ * The floor of an exact selection, sent beside it so a host whose backend
+ * knows only the threshold still narrows rather than showing everything.
+ */
+function lowestSeverity(picked: Severity[]): Severity {
+ return SEVERITIES.filter((s) => picked.includes(s)).pop() ?? "low";
+}
+
const EFFORT_LABEL: Record<string, string> = {
S: "Small (≤40 NLOC)",
M: "Medium (≤150 NLOC)",
@@ -65,7 +72,8 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
// Shares the page-level overview key, so this dedupes onto the one request
// the landing view already fired — no extra round-trip. Used to gate the
- // queue fetch and seed the biomarker filter options.
+ // queue fetch and to seed the marker filter with the repo's whole
+ // vocabulary rather than only the markers the current page happens to hold.
const { data: overview } = useSWR<HealthOverviewResponse>(
`code-health-overview:${cacheKey}`,
() => adapter.getOverview(25),
@@ -96,17 +104,72 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
[panelFindings],
);
- // ---- Queue filters ----
- const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
+ // ---- Filters ----
+ // Every one of these narrows the same server-side query, so the counts and
+ // the ranking beside the list always describe the rows in it. The page-level
+ // Counts control owns the code-shape / everything reading; repeating it here
+ // would put a second answer beside the first.
+ const [searchInput, setSearchInput] = useState("");
+ const [search, setSearch] = useState("");
+ const [dimension, setDimension] = useState<HealthDimension | "all">("all");
+ const [severities, setSeverities] = useState<Severity[]>([]);
const [biomarker, setBiomarker] = useState<string>("all");
const [maxEffort, setMaxEffort] = useState<string>("all");
+ const [onlyHotspots, setOnlyHotspots] = useState(false);
+ const [onlyUntested, setOnlyUntested] = useState(false);
+ const [onlyFailing, setOnlyFailing] = useState(false);
const [sort, setSort] = useState<HealthWorkQueueQuery["sort"]>("impact_per_effort");
const [groupBy, setGroupBy] = useState<GroupBy>("none");
- const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);
- const [view, setView] = useState<QueueView>("queue");
+ const [offset, setOffset] = useState(0);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [promptTarget, setPromptTarget] = useState<HealthWorkItem | null>(null);
+ // Typing a path should not mint a request per keystroke.
+ useEffect(() => {
+ const t = setTimeout(() => {
+ setSearch(searchInput);
+ setOffset(0);
+ }, SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(t);
+ }, [searchInput]);
+
+ /** Any narrowing beyond the defaults, which is what "clear" would undo. */
+ const filtered =
+ search !== "" ||
+ dimension !== "all" ||
+ severities.length > 0 ||
+ biomarker !== "all" ||
+ maxEffort !== "all" ||
+ onlyHotspots ||
+ onlyUntested ||
+ onlyFailing;
+
+ const clearFilters = () => {
+ setSearchInput("");
+ setSearch("");
+ setDimension("all");
+ setSeverities([]);
+ setBiomarker("all");
+ setMaxEffort("all");
+ setOnlyHotspots(false);
+ setOnlyUntested(false);
+ setOnlyFailing(false);
+ setOffset(0);
+ };
+
+ /** A filter change is a new question; page 1 is where it gets answered. */
+ const onFilterChange =
+ <T,>(set: (v: T) => void) =>
+ (v: T) => {
+ set(v);
+ setOffset(0);
+ };
+
+ const toggleSeverity = (s: Severity) => {
+ setSeverities((cur) => (cur.includes(s) ? cur.filter((v) => v !== s) : [...cur, s]));
+ setOffset(0);
+ };
+
// The targets list no longer ships `all_findings` — it cost 1.8 MB per
// request to serve two click-gated consumers. Both fetch here instead.
// `limit` is generous: this is one file's findings, and the worst file in a
@@ -115,6 +178,14 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
(await adapter.listFindings({
file_path: filePath,
limit: 1000,
+ // The same narrowing the row's own count was computed under. Without it
+ // "Show all 2 findings" opens onto fourteen.
+ ...(dimension !== "all" && { dimension }),
+ ...(biomarker !== "all" && { biomarker_type: biomarker }),
+ ...(severities.length > 0 && {
+ severity: severities.join(","),
+ min_severity: lowestSeverity(severities),
+ }),
})) as HealthWorkItemFinding[];
// Undefined when this host cannot answer, so the card stays silent rather
@@ -135,18 +206,39 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
}
};
- const queueKey = useMemo(
- () =>
- JSON.stringify({
- cacheKey,
- biomarker,
- minSeverity,
- maxEffort,
- sort,
- queueLimit,
+ const query: HealthWorkQueueQuery = useMemo(
+ () => ({
+ limit: PAGE_SIZE,
+ offset,
+ ...(search && { search }),
+ ...(dimension !== "all" && { dimension }),
+ ...(severities.length > 0 && {
+ severity: severities.join(","),
+ // A host whose backend predates the exact filter still narrows,
+ // rather than showing an unfiltered list under an active chip.
+ min_severity: lowestSeverity(severities),
}),
- [cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit],
+ ...(biomarker !== "all" && { biomarker }),
+ ...(maxEffort !== "all" && { max_effort: maxEffort }),
+ ...(onlyHotspots && { only_hotspots: true }),
+ ...(onlyUntested && { only_untested: true }),
+ ...(onlyFailing && { only_failing: true }),
+ ...(sort && { sort }),
+ }),
+ [
+ offset,
+ search,
+ dimension,
+ severities,
+ biomarker,
+ maxEffort,
+ onlyHotspots,
+ onlyUntested,
+ onlyFailing,
+ sort,
+ ],
);
+
const loadHealthWorkQueue = (opts: HealthWorkQueueQuery) => {
const load = adapter.getHealthWorkQueue ?? adapter.getRefactoringTargets;
return load ? load(opts) : Promise.resolve({ targets: [], total: 0 });
@@ -154,82 +246,25 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
const {
data: queue,
isLoading: queueLoading,
+ isValidating: queueValidating,
mutate: mutateQueue,
} = useSWR<HealthWorkQueueResponse>(
- overview ? `code-health-queue:${queueKey}` : null,
- () =>
- loadHealthWorkQueue({
- limit: queueLimit,
- ...(biomarker !== "all" && { biomarker }),
- ...(minSeverity !== "all" && { min_severity: minSeverity }),
- ...(maxEffort !== "all" && { max_effort: maxEffort }),
- ...(sort && { sort }),
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- // ---- All-files inventory view ----
- const [sortField, setSortField] = useState<FileSortField>("score");
- const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
- const [search, setSearch] = useState("");
- const [onlyHotspots, setOnlyHotspots] = useState(false);
- const [onlyUntested, setOnlyUntested] = useState(false);
- const [onlyFailing, setOnlyFailing] = useState(false);
- const [offset, setOffset] = useState(0);
-
- const filesKey = useMemo(
- () =>
- JSON.stringify({
- cacheKey,
- sortField,
- sortOrder,
- search,
- onlyHotspots,
- onlyUntested,
- onlyFailing,
- offset,
- }),
- [cacheKey, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],
- );
-
- const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(
- overview && view === "files" ? `code-health-files:${filesKey}` : null,
- () =>
- adapter.listFiles({
- sort: sortField,
- order: sortOrder,
- ...(search && { search }),
- ...(onlyHotspots && { only_hotspots: true }),
- ...(onlyUntested && { only_untested: true }),
- ...(onlyFailing && { only_failing: true }),
- offset,
- limit: PAGE_SIZE,
- }),
+ overview ? `code-health-queue:${cacheKey}:${JSON.stringify(query)}` : null,
+ () => loadHealthWorkQueue(query),
{ revalidateOnFocus: false, keepPreviousData: true },
);
- const handleSort = (field: FileSortField) => {
- if (field === sortField) {
- setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
- } else {
- setSortField(field);
- // Score: asc (worst first). Counts: desc. Path: asc.
- setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");
- }
- setOffset(0);
- };
-
- const handleStatus = async (findingId: string, status: FindingStatus) => {
- await adapter.updateFindingStatus(findingId, status);
+ const handleStatus = async (findingId: string, next: FindingStatus) => {
+ await adapter.updateFindingStatus(findingId, next);
mutateQueue();
};
- const biomarkerOptions = useMemo(() => {
- const set = new Set<string>();
- (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));
- (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));
- return [...set].sort();
- }, [overview, queue]);
+ // 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(
+ () => [...new Set((overview?.biomarkers ?? []).map((b) => b.biomarker_type))].sort(),
+ [overview],
+ );
// Grouped queue — group order follows the user's sort (first occurrence),
// not group size, so "Leverage" sorted stays leverage-led inside and out.
@@ -248,228 +283,254 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
return [...groups.entries()].map(([key, targets]) => ({ key, targets }));
}, [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);
+
return (
<div className="space-y-6">
- {/* The full ranked queue + file inventory. */}
<div className="space-y-3">
- <div className="flex flex-wrap items-center gap-2">
- <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h3 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
Fix next
- {queue?.total != null ? (
- <span className="ml-2 normal-case tracking-normal text-[var(--color-text-secondary)]">
- {queue.total} candidates
- </span>
- ) : null}
</h3>
- <ViewToggle
- value={view}
- onChange={setView}
+ {queue && !queueValidating ? (
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {total.toLocaleString()} {total === 1 ? "file" : "files"}
+ {findingTotal != null
+ ? ` · ${findingTotal.toLocaleString()} ${
+ findingTotal === 1 ? "finding" : "findings"
+ }`
+ : ""}
+ </span>
+ ) : null}
+ {filtered ? (
+ <button
+ type="button"
+ onClick={clearFilters}
+ className="ml-auto text-xs text-[var(--color-text-tertiary)] underline decoration-dotted underline-offset-2 hover:text-[var(--color-text-primary)]"
+ >
+ Clear filters
+ </button>
+ ) : null}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <input
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ placeholder="Filter path…"
+ aria-label="Filter by file path"
+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-hover)]"
+ />
+ </div>
+ <FilterSelect
+ label="Dimension"
+ value={dimension}
+ onChange={onFilterChange((v: string) =>
+ setDimension(v as HealthDimension | "all"),
+ )}
+ options={[
+ { value: "all", label: "All dimensions" },
+ { value: "defect", label: "Defect risk" },
+ { value: "maintainability", label: "Maintainability" },
+ ]}
+ />
+ <FilterSelect
+ label="Marker"
+ value={biomarker}
+ onChange={onFilterChange(setBiomarker)}
+ options={[
+ { value: "all", label: "All markers" },
+ ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
+ ]}
+ />
+ <FilterSelect
+ label="Max effort"
+ value={maxEffort}
+ onChange={onFilterChange(setMaxEffort)}
options={[
- { value: "queue", label: "Queue" },
- { value: "files", label: "All files" },
+ { value: "all", label: "Any effort" },
+ { value: "S", label: "Small only" },
+ { value: "M", label: "Medium and under" },
+ { value: "L", label: "Large and under" },
+ { value: "XL", label: "Extra large and under" },
+ ]}
+ />
+ <FilterSelect
+ label="Sort"
+ value={sort ?? "impact_per_effort"}
+ onChange={onFilterChange((v: string) =>
+ setSort(v as HealthWorkQueueQuery["sort"]),
+ )}
+ options={[
+ { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
+ { value: "total_impact", label: "Total impact" },
+ { value: "score", label: "Worst score" },
+ { value: "finding_count", label: "Finding count" },
+ ]}
+ />
+ <FilterSelect
+ label="Group"
+ value={groupBy}
+ onChange={(v) => setGroupBy(v as GroupBy)}
+ options={[
+ { value: "none", label: "Flat list" },
+ { value: "biomarker", label: "By marker" },
+ { value: "module", label: "By module" },
+ { value: "effort", label: "By effort" },
]}
/>
</div>
- {view === "queue" ? (
- <>
- <div className="flex flex-wrap items-center gap-2">
- <FilterSelect
- label="Marker"
- value={biomarker}
- onChange={setBiomarker}
- options={[
- { value: "all", label: "All markers" },
- ...biomarkerOptions.map((b) => ({
- value: b,
- label: biomarkerLabel(b),
- })),
- ]}
- />
- <FilterSelect
- label="Severity"
- value={minSeverity}
- onChange={(v) => setMinSeverity(v as Severity | "all")}
- options={[
- { value: "all", label: "All severities" },
- { value: "low", label: "Low+" },
- { value: "medium", label: "Medium+" },
- { value: "high", label: "High+" },
- { value: "critical", label: "Critical" },
- ]}
- />
- <FilterSelect
- label="Max effort"
- value={maxEffort}
- onChange={setMaxEffort}
- options={[
- { value: "all", label: "Any effort" },
- { value: "S", label: "Small only" },
- { value: "M", label: "Medium+" },
- { value: "L", label: "Large+" },
- ]}
- />
- <FilterSelect
- label="Sort"
- value={sort ?? "impact_per_effort"}
- onChange={(v) => setSort(v as HealthWorkQueueQuery["sort"])}
- options={[
- {
- value: "impact_per_effort",
- label: "Leverage (impact ÷ effort)",
- },
- { value: "total_impact", label: "Total impact" },
- { value: "score", label: "Worst score" },
- { value: "finding_count", label: "Finding count" },
- ]}
- />
- <FilterSelect
- label="Group"
- value={groupBy}
- onChange={(v) => setGroupBy(v as GroupBy)}
- options={[
- { value: "none", label: "Flat list" },
- { value: "biomarker", label: "By marker" },
- { value: "module", label: "By module" },
- { value: "effort", label: "By effort" },
- ]}
- />
- </div>
+ <div className="flex flex-wrap items-center gap-3">
+ <div
+ className="flex flex-wrap items-center gap-2"
+ role="group"
+ aria-label="Severity"
+ >
+ <span className="text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Severity
+ </span>
+ {SEVERITIES.map((s) => (
+ <FilterChip
+ key={s}
+ active={severities.includes(s)}
+ onClick={() => toggleSeverity(s)}
+ >
+ {SEVERITY_LABEL[s]}
+ </FilterChip>
+ ))}
+ </div>
+ <div
+ className="flex flex-wrap items-center gap-2"
+ role="group"
+ aria-label="File"
+ >
+ <span className="text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ File
+ </span>
+ <FilterChip
+ active={onlyHotspots}
+ onClick={() => {
+ setOnlyHotspots((v) => !v);
+ setOffset(0);
+ }}
+ >
+ Hotspots
+ </FilterChip>
+ <FilterChip
+ active={onlyUntested}
+ onClick={() => {
+ setOnlyUntested((v) => !v);
+ setOffset(0);
+ }}
+ >
+ Untested
+ </FilterChip>
+ <FilterChip
+ active={onlyFailing}
+ onClick={() => {
+ setOnlyFailing((v) => !v);
+ setOffset(0);
+ }}
+ >
+ Below green
+ </FilterChip>
+ </div>
+ </div>
- {queueLoading && !queue ? (
- <div className="grid gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-28 w-full" />
- ))}
- </div>
- ) : !queue || queue.targets.length === 0 ? (
- <EmptyState
- title="No findings match the current filters"
- description="Try widening the severity or effort filters, or sync the repo to refresh findings."
- />
- ) : (
- <>
- {/* Leverage at a glance — impact vs effort, click a dot to open
- the file. Replaces the text-dense ranking as the first read. */}
- <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)}
- />
- <div className="space-y-6">
- {grouped.map((g) => (
- <section key={g.key} className="space-y-2">
- {groupBy !== "none" ? (
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {g.key}{" "}
- <span className="text-[var(--color-text-secondary)]">
- ({g.targets.length})
- </span>
- </h3>
- ) : null}
- <HealthWorkQueueList
- targets={g.targets}
- onSelect={(t) => setSelectedFile(t.file_path)}
- onStatusChange={handleStatus}
- onGeneratePrompt={(t) => void openPrompt(t)}
- onLoadFindings={loadFindings}
- onLoadOpportunity={loadOpportunity}
- refactoringOpportunityHref={adapter.refactoringOpportunityHref}
- />
- </section>
- ))}
- </div>
-
- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span>
- Showing {queue.targets.length} of {queue.total} candidates
- </span>
- {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (
- <Button
- size="sm"
- variant="outline"
- onClick={() => setQueueLimit(QUEUE_MAX)}
- >
- Load more
- </Button>
- ) : null}
- </div>
- </>
- )}
- </>
+ {queueLoading && !queue ? (
+ <div className="grid gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-28 w-full" />
+ ))}
+ </div>
+ ) : total === 0 ? (
+ <EmptyState
+ title={filtered ? "Nothing matches these filters" : "No open findings"}
+ description={
+ filtered
+ ? "This view lists files carrying findings, ranked by leverage. Widen a filter to see more."
+ : "Files carrying findings appear here, ranked by leverage. Sync the repo to pick up new work."
+ }
+ {...(filtered
+ ? { action: { label: "Clear filters", onClick: clearFilters } }
+ : {})}
+ />
) : (
- <>
- <div className="flex flex-wrap items-center gap-2">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <input
- value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- setOffset(0);
- }}
- placeholder="Filter path…"
- className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-hover)]"
- />
- </div>
- <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
- Hotspots
- </FilterChip>
- <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>
- Untested
- </FilterChip>
- <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>
- Failing
- </FilterChip>
- <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">
- {files?.total != null ? `${files.total.toLocaleString()} files` : ""}
- </span>
+ <div
+ className={
+ queueValidating
+ ? "space-y-6 opacity-60 transition-opacity"
+ : "space-y-6 transition-opacity"
+ }
+ 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)}
+ />
+ <div className="space-y-6">
+ {grouped.map((g) => (
+ <section key={g.key} className="space-y-2">
+ {groupBy !== "none" ? (
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {g.key}{" "}
+ <span className="text-[var(--color-text-secondary)]">
+ ({g.targets.length})
+ </span>
+ </h3>
+ ) : null}
+ <HealthWorkQueueList
+ targets={g.targets}
+ onSelect={(t) => setSelectedFile(t.file_path)}
+ onStatusChange={handleStatus}
+ onGeneratePrompt={(t) => void openPrompt(t)}
+ onLoadFindings={loadFindings}
+ onLoadOpportunity={loadOpportunity}
+ refactoringOpportunityHref={adapter.refactoringOpportunityHref}
+ />
+ </section>
+ ))}
</div>
- {filesLoading && !files ? (
- <Skeleton className="h-64 w-full rounded-lg" />
- ) : (
- <HealthFileTable
- files={files?.files ?? []}
- sortField={sortField}
- sortOrder={sortOrder}
- onSort={handleSort}
- onSelect={(f) => setSelectedFile(f.file_path)}
- selectedPath={selectedFile}
- />
- )}
-
- {files && files.total > PAGE_SIZE ? (
- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span>
- Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}
- </span>
- <div className="flex gap-1">
- <Button
- size="sm"
- variant="outline"
- disabled={offset === 0}
- onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
- >
- Prev
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={offset + PAGE_SIZE >= files.total}
- onClick={() => setOffset(offset + PAGE_SIZE)}
- >
- Next
- </Button>
- </div>
+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ Showing {shownFrom.toLocaleString()}–{shownTo.toLocaleString()} of{" "}
+ {total.toLocaleString()} files
+ </span>
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset === 0}
+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
+ >
+ Prev
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset + PAGE_SIZE >= total}
+ onClick={() => setOffset(offset + PAGE_SIZE)}
+ >
+ Next
+ </Button>
</div>
- ) : null}
- </>
+ </div>
+ </div>
)}
</div>
@@ -504,9 +565,7 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
title="AI fix prompt"
description="A ready-to-paste prompt that gives your AI coding agent every marker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
getPrompt={
- promptTarget
- ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })
- : null
+ promptTarget ? (flavor) => buildAiPrompt({ target: promptTarget, flavor }) : null
}
/>
</div>
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 6b338c522..d25dbc8cd 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -110,7 +110,12 @@ export interface HealthFileDrawerProps {
/** Process / people / topology signals; the panel is silent when absent. */
signals?: FileSignals | null;
fileViewHref?: string;
- /** Build a per-line deep-link from the drawer's function:line span. */
+ /**
+ * Build a per-line deep-link from the drawer's function:line span. Unbound
+ * until a file view renders line anchors: no `#L<n>` resolves today, so a
+ * host that supplies one only adds a fragment that goes nowhere. Without
+ * it the label falls back to `fileViewHref`, the file page itself.
+ */
fileViewHrefFor?: ((lineStart: number) => string) | undefined;
permalinkHref?: string;
onPartnerSelect?: ((path: string) => void) | undefined;
diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsx
index fc9e95348..a76fd7b20 100644
--- a/packages/ui/src/health/impact-effort-quadrant.tsx
+++ b/packages/ui/src/health/impact-effort-quadrant.tsx
@@ -1,8 +1,9 @@
"use client";
import { useMemo, useState } from "react";
-import { bandForScore } from "@repowise-dev/types/health";
-import { HEALTH_BAND_FILL } from "./tokens";
+// 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 {
@@ -74,7 +75,7 @@ export function ImpactEffortQuadrant({
Impact × effort
</h3>
<span className="text-xs text-[var(--color-text-tertiary)]">
- {data.length} targets · click a dot to open
+ {data.length} on this page · click a dot to open
</span>
</div>
<div className="relative">
@@ -111,7 +112,7 @@ export function ImpactEffortQuadrant({
const cx = baseX + jitter(p.file_path);
const cy = yScale(p.total_impact);
const isHovered = hovered?.file_path === p.file_path;
- const fillCls = HEALTH_BAND_FILL[bandForScore(p.score)];
+ const fillCls = healthNodeFill(p.score);
return (
<circle
key={p.file_path}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 69b81ad5f..d7de77b57 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -1,7 +1,6 @@
export * from "./tokens";
export * from "./biomarker-glossary";
export * from "./biomarker-chip";
-export * from "./file-table";
export * from "./biomarker-list";
export * from "./biomarker-details";
export * from "./coverage-bar";
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index c76ffa11e..dd6ed9215 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -5,7 +5,7 @@ import { ArrowUpRight, ChevronDown, ChevronRight, Sparkles } from "lucide-react"
import { InfoTip } from "../shared/info-tip";
import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
-import { type Severity } from "./tokens";
+import { EFFORT_TINT, type Severity } from "./tokens";
import { ImpactFigure } from "./impact-figure";
import { FindingOpportunityLink } from "./file-opportunity";
import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
@@ -42,6 +42,7 @@ export interface HealthWorkItem {
primary_finding_id?: string;
total_impact: number;
finding_count: number;
+ open_finding_count?: number;
biomarkers: string[];
effort_bucket: EffortBucket;
impact_per_effort: number;
@@ -88,13 +89,6 @@ const effortLabel: Record<EffortBucket, string> = {
XL: "Extra large",
};
-const effortColor: Record<EffortBucket, string> = {
- S: "bg-[var(--color-success)]/15 text-[var(--color-success)]",
- M: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",
- L: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",
- XL: "bg-[var(--color-error)]/15 text-[var(--color-error)]",
-};
-
export function HealthWorkItemCard({
target,
onSelect,
@@ -167,7 +161,7 @@ export function HealthWorkItemCard({
</span>
) : null}
<span
- className={`inline-block rounded px-1.5 py-0.5 text-[10px] uppercase font-semibold ${effortColor[target.effort_bucket]}`}
+ className={`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})`}
>
{target.effort_bucket}
@@ -189,6 +183,7 @@ export function HealthWorkItemCard({
</div>
<button
type="button"
+ data-work-item-header=""
onClick={onSelect ? () => onSelect(target) : undefined}
className="group/file flex w-full items-center gap-1.5 text-left rounded-md -mx-1 px-1 py-0.5 hover:bg-[var(--color-bg-elevated)] disabled:cursor-default disabled:hover:bg-transparent"
disabled={!onSelect}
@@ -217,7 +212,13 @@ export function HealthWorkItemCard({
<span>Score {target.score.toFixed(1)}/10</span>
<span>· {target.nloc} NLOC</span>
<span>· {effortLabel[target.effort_bucket]} effort</span>
- <span>· {target.finding_count} findings</span>
+ <span>
+ {"· "}
+ {target.open_finding_count != null &&
+ target.open_finding_count !== target.finding_count
+ ? `${target.open_finding_count} open of ${target.finding_count} findings`
+ : `${target.finding_count} findings`}
+ </span>
<span className="ml-auto tabular-nums">leverage {target.impact_per_effort.toFixed(2)}</span>
</div>
{onGeneratePrompt ? (
@@ -265,6 +266,7 @@ export function HealthWorkItemCard({
{f.function_name ? (
<span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>
) : null}
+ <FindingLine lineStart={f.line_start} />
<ImpactFigure impact={f.health_impact} className="ml-auto text-xs" />
</div>
<p className="text-xs text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>
@@ -296,6 +298,20 @@ export type RefactoringTargetFinding = HealthWorkItemFinding;
export type RefactoringCardProps = HealthWorkItemCardProps;
export const RefactoringCard = HealthWorkItemCard;
+/**
+ * Where a finding sits. Not a link: no file view renders a line anchor, so a
+ * "line 412" href would land at the top of the page every time. Silent
+ * without a line, because a marker describing the whole file has none.
+ */
+function FindingLine({ lineStart }: { lineStart: number | null | undefined }) {
+ if (lineStart == null) return null;
+ return (
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ line {lineStart}
+ </span>
+ );
+}
+
function StatusButton({
current,
value,
diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsx
index 5cd2d300b..3f5766a92 100644
--- a/packages/ui/src/health/refactoring-target-list.tsx
+++ b/packages/ui/src/health/refactoring-target-list.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import {
HealthWorkItemCard,
@@ -10,13 +10,10 @@ import {
} from "./refactoring-card";
/**
- * Cards rendered per page. Matches the files view's `PAGE_SIZE`, deliberately:
- * the queue's "Load more" raises the *fetch* to `QUEUE_MAX = 500`, and every one
- * of those was previously mounted as a full `RefactoringCard` — tens of
- * thousands of DOM nodes in one commit, on top of the payload they arrived in.
- * Paging here rather than in the caller fixes it for every consumer of this
- * list at once, and it works per *group* when the queue is grouped, which a cap
- * applied to the fetched array could not do.
+ * Cards mounted per page. The queue now pages server-side at the same size, so
+ * this is inert for that caller and stays as the guard for any consumer that
+ * hands over a longer array: every target used to mount as a full card, which
+ * was tens of thousands of DOM nodes in one commit.
*/
const CARD_PAGE = 50;
@@ -72,6 +69,23 @@ export function HealthWorkQueueList({
highlightIndex >= 0 ? Math.ceil((highlightIndex + 1) / CARD_PAGE) * CARD_PAGE : 0,
);
+ // Arrow keys walk the queue. Each card's path button is the row's focus
+ // anchor, so this moves between files without stealing Tab from the controls
+ // inside an expanded card.
+ const gridRef = useRef<HTMLDivElement | null>(null);
+ const onArrowKey = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
+ const grid = gridRef.current;
+ if (!grid) return;
+ const headers = [...grid.querySelectorAll<HTMLButtonElement>("[data-work-item-header]")];
+ const here = headers.findIndex((h) => h.contains(e.target as Node));
+ if (here === -1) return;
+ // Swallowed at either end too: an arrow that scrolls the page away from
+ // the list reads as the key having done nothing.
+ e.preventDefault();
+ headers[here + (e.key === "ArrowDown" ? 1 : -1)]?.focus();
+ }, []);
+
if (targets.length === 0) {
return (
<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">
@@ -82,7 +96,7 @@ export function HealthWorkQueueList({
const remaining = targets.length - shown;
return (
<>
- <div className="grid gap-3">
+ <div className="grid gap-3" onKeyDown={onArrowKey} ref={gridRef}>
{targets.slice(0, shown).map((t) => (
<HealthWorkItemCard
key={t.file_path}
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 1eac7abfd..6aedddec6 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -52,6 +52,18 @@ export const SEVERITY_BAR: Record<Severity, string> = {
low: "bg-[var(--color-text-tertiary)]",
};
+/**
+ * Effort tint. A ramp, not a judgement: green is the cheap end, red the
+ * expensive one. The badge prints the bucket letter beside it, so it belongs
+ * on the semantic ramp. Here rather than in the card so it has one home.
+ */
+export const EFFORT_TINT: Record<"S" | "M" | "L" | "XL", string> = {
+ S: "bg-[var(--color-success)]/15 text-[var(--color-success)]",
+ M: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",
+ L: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",
+ XL: "bg-[var(--color-error)]/15 text-[var(--color-error)]",
+};
+
/**
* The one health band -> colour vocabulary. Excellent and Good share the
* green; the band word carries the difference. Every table below is written
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index f4b01a763..560516e89 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -406,7 +406,12 @@ export default function CodeHealthPage() {
const coveragePct = coverage?.summary.line_coverage_pct;
const badges: Partial<Record<TabId, number | string>> = {};
- if (overview) badges.findings = overview.summary.open_findings;
+ // Performance has its own tab and is out of the findings list, so counting
+ // it here would put a bigger number on the tab than the tab can show.
+ if (overview) {
+ badges.findings =
+ overview.summary.open_findings - (overview.summary.performance_findings ?? 0);
+ }
if (deadCode) badges["dead-code"] = deadCode.total_findings;
if (coveragePct != null) badges.coverage = `${Math.round(coveragePct)}%`;
diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsx
index fdcbe2a99..703785a75 100644
--- a/packages/web/src/components/code-health/coverage-tab.tsx
+++ b/packages/web/src/components/code-health/coverage-tab.tsx
@@ -14,7 +14,6 @@ import {
getTestsReaching,
getHealthOverview,
getHealthWorkQueue,
- listHealthFiles,
listHealthFindings,
updateFindingStatus,
} from "@/lib/api/code-health";
@@ -27,7 +26,6 @@ export function CoverageTab({ repoId: id }: { repoId: string }) {
cacheKey: id,
getOverview: (limit) => getHealthOverview(id, limit),
listFindings: (opts) => listHealthFindings(id, opts),
- listFiles: (opts) => listHealthFiles(id, opts),
getHealthWorkQueue: (opts) => getHealthWorkQueue(id, opts),
updateFindingStatus: (findingId, status) =>
updateFindingStatus(id, findingId, status),
diff --git a/packages/web/src/components/code-health/findings-tab.tsx b/packages/web/src/components/code-health/findings-tab.tsx
index 34bfed16f..a6180fab2 100644
--- a/packages/web/src/components/code-health/findings-tab.tsx
+++ b/packages/web/src/components/code-health/findings-tab.tsx
@@ -14,7 +14,6 @@ import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity
import {
getHealthOverview,
getHealthWorkQueue,
- listHealthFiles,
listHealthFindings,
getHealthCoverage,
updateFindingStatus,
@@ -50,7 +49,6 @@ export function FindingsTab({
getFileOpportunity: (filePath) => getFileOpportunity(id, filePath),
refactoringOpportunityHref: (opportunityId) =>
refactoringOpportunityHref(id, opportunityId),
- listFiles: (opts) => listHealthFiles(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),
getHealthWorkQueue: (opts) =>
getHealthWorkQueue(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),
updateFindingStatus: (findingId, status) =>
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index db83c8fae..e8798e790 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -18,7 +18,6 @@ import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity
import {
getHealthOverview,
getHealthWorkQueue,
- listHealthFiles,
listHealthFindings,
getHealthCoverage,
updateFindingStatus,
@@ -84,7 +83,6 @@ export function TriageTab({
getOverview: (limit) => getHealthOverview(id, limit, scope, counts),
listFindings: (opts) =>
listHealthFindings(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),
- listFiles: (opts) => listHealthFiles(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),
getHealthWorkQueue: (opts) =>
getHealthWorkQueue(id, { ...opts, ...(scope ? { scope } : {}), ...(counts ? { counts } : {}) }),
updateFindingStatus: (findingId, status) =>
diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsx
index dce99d0a4..eeb2f2d17 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -96,15 +96,6 @@ export function HealthFileDrawerHost({
}
permalinkHref={filePageHref ? `${filePageHref}?tab=health` : undefined}
fileViewHref={filePageHref}
- fileViewHrefFor={
- // Carry the line through. This used to discard its argument, which was
- // survivable while the link only appeared next to a function name; now
- // that file-level markers render their own line, dropping it would make
- // 34 visually distinct "line N" links resolve to one identical URL.
- filePageHref
- ? (lineStart) => `${filePageHref}?tab=health#L${lineStart}`
- : undefined
- }
onPartnerHref={(path) => fileEntityPath(prefix, path)}
onFindingStatusChange={async (findingId, status) => {
try {
diff --git a/tests/unit/server/test_health_work_queue_controls.py b/tests/unit/server/test_health_work_queue_controls.py
new file mode 100644
index 000000000..219f05b0f
--- /dev/null
+++ b/tests/unit/server/test_health_work_queue_controls.py
@@ -0,0 +1,275 @@
+"""The work queue's own filters, paging and counts.
+
+The queue is the triage list: one view, files ranked by leverage, narrowed by
+controls that must describe the rows beside them. These cover the controls the
+route grew for that view, and the two figures a reader steers by - how many
+files match, and how much work sits in them.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.models import HealthFileMetricData, HealthFindingData
+from repowise.core.persistence.crud import (
+ save_health_findings,
+ save_health_metrics,
+ upsert_repository,
+)
+
+from .conftest import create_test_repo
+
+
+def _metric(path: str, score: float, nloc: int = 100, has_test_file: bool = False):
+ return HealthFileMetricData(
+ file_path=path,
+ score=score,
+ max_ccn=1,
+ max_nesting=1,
+ nloc=nloc,
+ has_test_file=has_test_file,
+ defect_score=score,
+ structure_deduction=10.0 - score,
+ history_deduction=0.0,
+ )
+
+
+def _finding(
+ path: str,
+ biomarker_type: str = "complex_method",
+ severity: str = "high",
+ impact: float = 1.0,
+ dimension: str = "defect",
+):
+ return HealthFindingData(
+ biomarker_type=biomarker_type,
+ severity=severity,
+ file_path=path,
+ function_name=None,
+ line_start=12,
+ line_end=20,
+ details={},
+ health_impact=impact,
+ reason=f"{biomarker_type} in {path}",
+ dimension=dimension,
+ )
+
+
+async def _repo(client, session, tmp_path, metrics, findings):
+ repo = await create_test_repo(client, tmp_path)
+ await upsert_repository(session, name="r", local_path=repo["local_path"])
+ await save_health_metrics(session, repo["id"], metrics)
+ await save_health_findings(session, repo["id"], findings)
+ await session.commit()
+ return repo["id"]
+
+
+async def _queue(client, repo_id, query: str = ""):
+ url = f"/api/repos/{repo_id}/health/refactoring-targets"
+ return (await client.get(f"{url}?{query}" if query else url)).json()
+
+
+async def test_the_page_reports_both_files_and_findings(client, session, tmp_path) -> None:
+ """The view lists files but triages findings, so it states both."""
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0), _metric("b.py", 5.0)],
+ [_finding("a.py"), _finding("a.py", "god_class"), _finding("b.py")],
+ )
+
+ body = await _queue(client, repo_id)
+
+ assert body["total"] == 2
+ assert body["finding_total"] == 3
+ assert body["offset"] == 0
+
+
+async def test_paging_walks_the_whole_ranking(client, session, tmp_path) -> None:
+ """`total` counts the matches; `offset` moves through them without gaps."""
+ metrics = [_metric(f"f{i}.py", 3.0 + i * 0.1) for i in range(5)]
+ findings = [_finding(f"f{i}.py", impact=5.0 - i) for i in range(5)]
+ repo_id = await _repo(client, session, tmp_path, metrics, findings)
+
+ first = await _queue(client, repo_id, "limit=2&offset=0")
+ second = await _queue(client, repo_id, "limit=2&offset=2")
+ last = await _queue(client, repo_id, "limit=2&offset=4")
+
+ assert [t["file_path"] for t in first["targets"]] == ["f0.py", "f1.py"]
+ assert [t["file_path"] for t in second["targets"]] == ["f2.py", "f3.py"]
+ assert [t["file_path"] for t in last["targets"]] == ["f4.py"]
+ # Every page describes the same population.
+ assert first["total"] == second["total"] == last["total"] == 5
+
+
+async def test_an_offset_past_the_end_is_an_empty_page_not_an_error(
+ client, session, tmp_path
+) -> None:
+ repo_id = await _repo(client, session, tmp_path, [_metric("a.py", 4.0)], [_finding("a.py")])
+
+ body = await _queue(client, repo_id, "offset=500")
+
+ assert body["targets"] == []
+ assert body["total"] == 1
+
+
+async def test_severity_selects_exactly_what_was_asked_for(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", severity="low"), _finding("b.py", severity="critical")],
+ )
+
+ only_low = await _queue(client, repo_id, "severity=low")
+
+ assert [t["file_path"] for t in only_low["targets"]] == ["a.py"]
+
+
+async def test_an_empty_severity_list_does_not_empty_the_queue(
+ client, session, tmp_path
+) -> None:
+ """A client that serializes "nothing selected" as "," means no filter.
+
+ Read as an exact match, an empty set matches nothing and returns 200 with
+ an empty list - a filter that looks like a repository with no findings.
+ """
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0)],
+ [_finding("a.py", severity="low")],
+ )
+
+ assert (await _queue(client, repo_id, "severity=,"))["total"] == 1
+ assert (await _queue(client, repo_id, "severity=%20"))["total"] == 1
+
+
+async def test_search_and_the_file_chips_narrow_the_same_rows(
+ client, session, tmp_path
+) -> None:
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("src/a.py", 4.0), _metric("web/b.py", 9.0, has_test_file=True)],
+ [_finding("src/a.py"), _finding("web/b.py")],
+ )
+
+ assert [t["file_path"] for t in (await _queue(client, repo_id, "search=web"))["targets"]] == [
+ "web/b.py"
+ ]
+ # Below the score green starts at.
+ assert [
+ t["file_path"] for t in (await _queue(client, repo_id, "only_failing=true"))["targets"]
+ ] == ["src/a.py"]
+ assert [
+ t["file_path"] for t in (await _queue(client, repo_id, "only_untested=true"))["targets"]
+ ] == ["src/a.py"]
+
+
+async def test_performance_is_out_of_the_queue_as_it_is_out_of_the_list(
+ client, session, tmp_path
+) -> None:
+ """A row's count and the findings list behind it have to agree."""
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0)],
+ [_finding("a.py"), _finding("a.py", "io_in_loop", impact=0.0, dimension="performance")],
+ )
+
+ body = await _queue(client, repo_id)
+
+ assert body["finding_total"] == 1
+ assert body["targets"][0]["finding_count"] == 1
+ assert (await _queue(client, repo_id, "dimension=performance"))["finding_total"] == 1
+
+
+async def test_a_dismissed_finding_stops_ranking_the_file_as_work(
+ client, session, tmp_path
+) -> None:
+ """Dismissing findings must move a file down the queue, not leave it.
+
+ ``score`` on the row comes from open findings, so impact summed over
+ dismissed ones would rank a file by work nobody intends to do.
+ """
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0)],
+ [_finding("a.py", impact=3.0), _finding("a.py", "god_class", impact=2.0)],
+ )
+ findings = (await client.get(f"/api/repos/{repo_id}/health/findings")).json()
+ await client.patch(
+ f"/api/repos/{repo_id}/health/findings/{findings[0]['id']}",
+ json={"status": "false_positive"},
+ )
+
+ body = await _queue(client, repo_id, "status=all")
+ target = body["targets"][0]
+
+ assert target["finding_count"] == 2
+ assert target["open_finding_count"] == 1
+ assert target["total_impact"] == 2.0
+
+
+async def test_an_unknown_status_is_refused_rather_than_answered_emptily(
+ client, session, tmp_path
+) -> None:
+ """``200 []`` for a typo is indistinguishable from "nothing matches"."""
+ repo_id = await _repo(client, session, tmp_path, [_metric("a.py", 4.0)], [_finding("a.py")])
+
+ url = f"/api/repos/{repo_id}/health/refactoring-targets?status=dismissed"
+ assert (await client.get(url)).status_code == 400
+
+ findings_url = f"/api/repos/{repo_id}/health/findings?status=dismissed"
+ assert (await client.get(findings_url)).status_code == 400
+
+
+async def test_a_rows_count_matches_the_findings_behind_it(client, session, tmp_path) -> None:
+ """The expander says "all N findings"; opening it must show N.
+
+ The row's count is computed over the filtered findings, so the per-file
+ read behind it has to accept the same filters or the label lies.
+ """
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0)],
+ [
+ _finding("a.py", severity="critical"),
+ _finding("a.py", "god_class", severity="low"),
+ _finding("a.py", "large_method", severity="low"),
+ ],
+ )
+
+ row = (await _queue(client, repo_id, "severity=critical"))["targets"][0]
+ behind = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/findings?file_path=a.py&severity=critical"
+ )
+ ).json()
+
+ assert row["finding_count"] == len(behind) == 1
+
+
+async def test_exact_severity_beats_the_threshold_on_the_findings_list(
+ client, session, tmp_path
+) -> None:
+ repo_id = await _repo(
+ client,
+ session,
+ tmp_path,
+ [_metric("a.py", 4.0)],
+ [_finding("a.py", severity="low"), _finding("a.py", "god_class", severity="critical")],
+ )
+
+ url = f"/api/repos/{repo_id}/health/findings?file_path=a.py"
+ both = (await client.get(f"{url}&severity=low&min_severity=critical")).json()
+
+ assert [f["severity"] for f in both] == ["low"]