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): put the performance lens on the one Galaxy (#1987)

Raghav Chamadiya5d7501f699e6
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index cb56e860e..f54b6ea47 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -9,6 +9,8 @@ import type {
HealthFilesQuery,
HealthFilesResponse,
HealthFinding,
+ HealthMapFeed,
+ HealthMapQuery,
HealthCoverageResponse,
TestsReachingFile,
HealthFileBreakdownResponse,
@@ -40,6 +42,12 @@ export type {
HealthFilesQuery,
HealthFilesResponse,
HealthFinding,
+ HealthMapFeed,
+ HealthMapModuleRollup,
+ HealthMapOmissions,
+ HealthMapPerformance,
+ HealthMapQuery,
+ HealthMapSelection,
HealthModuleRow,
HealthOverviewResponse,
HealthTrendResponse,
@@ -101,6 +109,7 @@ export async function getPerformanceOpportunities(
actionability: opts.actionability,
view: opts.view,
sort: opts.sort,
+ file_paths: opts.file_paths?.length ? opts.file_paths.join(",") : undefined,
limit: opts.limit,
offset: opts.offset,
},
@@ -130,6 +139,23 @@ export async function getPerformanceOpportunityFindings(
);
}
+/**
+ * The bounded field the code-health map draws.
+ *
+ * Distinct from {@link listHealthFiles}, which is an inventory page: this one
+ * chooses its rows so the caller's selection and the repository's performance
+ * causes are guaranteed a node, and states what the cap left out.
+ */
+export async function getHealthMap(
+ repoId: string,
+ opts: HealthMapQuery = {},
+): Promise<HealthMapFeed> {
+ return apiGet<HealthMapFeed>(`/api/repos/${repoId}/health/map`, {
+ cap: opts.cap,
+ active: opts.active?.length ? opts.active.join(",") : undefined,
+ });
+}
+
export async function listHealthFiles(
repoId: string,
opts?: HealthFilesQuery,
diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.ts
index 417a13d43..4596fa028 100644
--- a/packages/api-client/src/hosted.ts
+++ b/packages/api-client/src/hosted.ts
@@ -812,8 +812,16 @@ export function createHostedProvider(config: HostedProviderConfig): HostedProvid
}),
getRefactoringPlan: (repoId, planId) =>
snapGet(repoId, `/refactoring/${encodeURIComponent(planId)}`),
- getPerformanceOpportunities: (repoId, opts = {}) =>
- snapGet(repoId, "/health/performance-opportunities", opts),
+ getPerformanceOpportunities: (repoId, opts = {}) => {
+ // The file scope is the one list-valued member of the query, and the
+ // parameter helper takes scalars, so it goes over the wire the way the
+ // route reads it rather than as an array the serializer would drop.
+ const { file_paths, ...rest } = opts;
+ return snapGet(repoId, "/health/performance-opportunities", {
+ ...rest,
+ ...(file_paths?.length ? { file_paths: file_paths.join(",") } : {}),
+ });
+ },
getPerformanceOpportunityFindings: (repoId, opportunityId, opts = {}) =>
snapGet(
repoId,
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index 5a67f9b80..59bd86a3d 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -65,6 +65,7 @@ from .performance import (
list_performance_opportunities,
opportunity_details,
performance_facet_counts,
+ performance_file_rollups,
)
from .refactoring import (
count_refactoring_suggestions,
@@ -113,6 +114,7 @@ __all__ = [
"load_coverage_for_repo",
"opportunity_details",
"performance_facet_counts",
+ "performance_file_rollups",
"replace_dead_code_findings",
"replace_governance_findings",
"save_coverage_files",
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 cc607a8eb..060c291e5 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -312,12 +312,26 @@ async def get_health_findings(
min_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.
+
+ ``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.
+ """
q = select(HealthFinding).where(
HealthFinding.repository_id == repository_id,
HealthFinding.status == status,
)
+ if dimension is None and exclude_dimensions:
+ q = q.where(
+ or_(
+ HealthFinding.dimension.is_(None),
+ HealthFinding.dimension.not_in(list(exclude_dimensions)),
+ )
+ )
if biomarker_type is not None:
# Accept a comma-separated list so a caller can pull several biomarker
# types in one request (e.g. the function-level + coupling panels).
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
index bffb9b615..88554a9a6 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -14,7 +14,7 @@ for the same reason - they can no longer describe the current tree.
from __future__ import annotations
import json
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, NamedTuple
from sqlalchemy import delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
@@ -519,6 +519,97 @@ async def performance_facet_counts(
return [tuple(row) for row in result.all()]
+_ACTIONABILITY_STATES = ("plan_ready", "advisory", "investigate")
+"""The states a rollup breaks down. Named, so a fourth cannot vanish silently."""
+
+
+class PerformanceFileRollup(NamedTuple):
+ """One file's open performance burden, folded from the grouped counts."""
+
+ file_path: str
+ opportunities: int
+ observations: int
+ plan_ready: int
+ advisory: int
+ investigate: int
+ best_rank: int
+ """Lowest ``rank_position`` on the file, so a map can rank files by cause."""
+
+
+async def performance_file_rollups(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ file_paths: tuple[str, ...] | None = None,
+) -> list[PerformanceFileRollup]:
+ """Per-file burden for every file carrying an open opportunity.
+
+ One indexed aggregate over ``(repository_id, status, file_path)`` returning
+ at most three rows per file rather than one per observation, so a caller
+ that needs the whole repository still pays a grouped scan and not a
+ per-file query. Ordered best-rank first, which is the order a bounded map
+ feed admits files in.
+ """
+ where = _predicates(
+ repository_id,
+ contexts=None,
+ boundary=None,
+ confidence=None,
+ actionability=None,
+ file_paths=file_paths,
+ )
+ result = await session.execute(
+ select(
+ PerformanceOpportunity.file_path,
+ PerformanceOpportunity.actionability_state,
+ func.count(),
+ func.sum(PerformanceOpportunity.observations_total),
+ func.min(PerformanceOpportunity.rank_position),
+ )
+ .where(*where)
+ .group_by(
+ PerformanceOpportunity.file_path,
+ PerformanceOpportunity.actionability_state,
+ )
+ )
+ folded: dict[str, dict[str, int]] = {}
+ for path, state, count, observations, best_rank in result.all():
+ if not path:
+ continue
+ row = folded.setdefault(
+ path,
+ {
+ "opportunities": 0,
+ "observations": 0,
+ "plan_ready": 0,
+ "advisory": 0,
+ "investigate": 0,
+ "best_rank": best_rank or 0,
+ },
+ )
+ row["opportunities"] += int(count or 0)
+ row["observations"] += int(observations or 0)
+ if state in _ACTIONABILITY_STATES:
+ row[state] += int(count or 0)
+ row["best_rank"] = min(row["best_rank"], int(best_rank or 0))
+ rollups = [
+ PerformanceFileRollup(
+ file_path=path,
+ opportunities=row["opportunities"],
+ observations=row["observations"],
+ plan_ready=row["plan_ready"],
+ advisory=row["advisory"],
+ investigate=row["investigate"],
+ best_rank=row["best_rank"],
+ )
+ for path, row in folded.items()
+ ]
+ # Best rank first, then path, so the order a cap is applied against is
+ # total and does not move between two reads of the same store.
+ rollups.sort(key=lambda r: (r.best_rank, r.file_path))
+ return rollups
+
+
async def get_performance_plan_rows(
session: AsyncSession, repository_id: str, opportunity_ids: list[str]
) -> dict[str, RefactoringSuggestion]:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index cd8920eca..f435f1191 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -495,6 +495,9 @@ def _stamp_nested_collections(value: Any) -> None:
_stamp_nested_collections(child)
+_RANKED_DIMENSIONS_DEFAULT = {"defect", "maintainability"}
+"""Dimensions the impact-ranked findings list carries when none is asked for."""
+
def _in_dimensions(row: Any, dimensions: set[str]) -> bool:
"""True when *row* belongs to one of *dimensions* (empty set -> everything).
@@ -1316,6 +1319,12 @@ async def get_health(
# to nothing while the total still reported the whole repo. The filter now
# decides which rows are eligible for the cap in the first place.
dimension_filter = include_set & {"performance", "defect", "maintainability"}
+ # The ranked findings list is ordered by health impact, and every
+ # performance finding carries zero impact by construction, so leaving it
+ # in an unfiltered list appends rows that can never rank and cannot be
+ # compared against the ones above them. Asking for the dimension still
+ # returns it, and the performance blocks rank the same evidence by cause.
+ ranked_dimensions = dimension_filter or _RANKED_DIMENSIONS_DEFAULT
# The serialized-rows read is the expensive optional one; skip it when no
# block that carries findings survives the projection.
wants_findings = wants("findings") or wants("top_findings")
@@ -1584,7 +1593,7 @@ async def get_health(
)
lead_rows: list[Any] = finding_rows
emitted = _rank_emitted(
- [f for f in finding_rows if _in_dimensions(f, dimension_filter)]
+ [f for f in finding_rows if _in_dimensions(f, ranked_dimensions)]
)
finding_rows = emitted
legend_rows: list[Any] = finding_rows
@@ -1634,7 +1643,9 @@ async def get_health(
# leads and the performance KPI, neither of which should change
# because the caller asked to *see* one dimension.
lead_rows = filter_rows_by_attr(lite_rows, "file_path", exclude_spec)
- emitted = _rank_emitted([r for r in lead_rows if _in_dimensions(r, dimension_filter)])
+ emitted = _rank_emitted(
+ [r for r in lead_rows if _in_dimensions(r, ranked_dimensions)]
+ )
# Test material goes in its own bucket rather than competing for
# the repo's headline finding list. Measured on this repo, **2 of
# the top 5** open findings by impact sit on test files, and 4-5 of
diff --git a/packages/server/src/repowise/server/routers/code_health/__init__.py b/packages/server/src/repowise/server/routers/code_health/__init__.py
index 299a7d94f..760a64f7f 100644
--- a/packages/server/src/repowise/server/routers/code_health/__init__.py
+++ b/packages/server/src/repowise/server/routers/code_health/__init__.py
@@ -20,6 +20,7 @@ from . import (
coverage_routes, # noqa: F401
files_routes, # noqa: F401
findings_routes, # noqa: F401
+ map_routes, # noqa: F401
overview_routes, # noqa: F401
performance_routes, # noqa: F401
refactoring_routes, # noqa: F401
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 b118ae2d5..45d50acc2 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
@@ -24,6 +24,14 @@ async def list_health_findings(
limit: int = Query(100, ge=1, le=1000),
session: AsyncSession = Depends(get_db_session),
) -> list[dict]:
+ """Open findings, ranked by health impact.
+
+ 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
+ below every defect row and reads as "nothing here" rather than as a
+ different unit; the performance surfaces rank the same evidence by cause.
+ Asking for ``dimension=performance`` still returns it.
+ """
findings = await crud.get_health_findings(
session,
repo_id,
@@ -31,6 +39,7 @@ async def list_health_findings(
file_path=file_path,
min_severity=min_severity,
dimension=dimension,
+ exclude_dimensions=("performance",),
)
return await _attach_symbol_ids(
session, repo_id, [_finding_to_dict(f) for f in findings[:limit]]
diff --git a/packages/server/src/repowise/server/routers/code_health/map_routes.py b/packages/server/src/repowise/server/routers/code_health/map_routes.py
new file mode 100644
index 000000000..c44567518
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/code_health/map_routes.py
@@ -0,0 +1,44 @@
+"""The bounded field the Code Health map draws.
+
+A thin adapter: the cap, the guaranteed paths, and the deterministic selection
+order live in the shared map service, so the rendered set and the counts that
+describe it come back from one place and cannot disagree.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import Depends, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.server.deps import get_db_session
+from repowise.server.services.health_map import (
+ DEFAULT_MAP_CAP,
+ MAX_MAP_CAP,
+ HealthMapService,
+ parse_active,
+)
+
+from ._router import router
+
+
[email protected]("/api/repos/{repo_id}/health/map")
+async def get_health_map(
+ repo_id: str,
+ cap: int = Query(DEFAULT_MAP_CAP, ge=1, le=MAX_MAP_CAP),
+ active: str | None = Query(
+ None,
+ description=(
+ "Comma-separated file paths guaranteed a node, admitted before any "
+ "other band. A deep link into a selected file or opportunity passes "
+ "them so the cap can never push the subject off its own map."
+ ),
+ ),
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """One bounded field plus the exact scope of what the cap left out."""
+ feed = await HealthMapService(session, repo_id).feed(
+ cap=cap, active=parse_active(active)
+ )
+ return feed.payload()
diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
index 2ce44fef3..f2507d2ce 100644
--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
@@ -106,8 +106,14 @@ async def health_overview(
[_finding_to_dict(f) for f in findings if f.biomarker_type == "prior_defect"],
)
+ # Ranked by health impact, so performance is out: its findings score zero
+ # impact by construction and would fill the tail of a defect ranking with
+ # rows the reader cannot compare against the ones above them. The counts
+ # and breakdowns above still see every dimension; only this queue is
+ # defect-and-maintainability work.
+ ranked = [f for f in findings if (getattr(f, "dimension", None) or "defect") != "performance"]
top_findings = await _attach_symbol_ids(
- session, repo_id, [_finding_to_dict(f) for f in findings[:limit]]
+ session, repo_id, [_finding_to_dict(f) for f in ranked[:limit]]
)
return {
diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
index 9f5401409..eedd0d84d 100644
--- a/packages/server/src/repowise/server/routers/code_health/performance_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
@@ -36,6 +36,18 @@ _EVIDENCE_PER_ITEM = 8
"""Evidence rows carried inline on a queue row, so the tab can show the paths."""
+_MAX_SCOPED_PATHS = 50
+"""Files one scoped request may name. A file surface asks about one or a few."""
+
+
+def _paths(raw: str | None) -> tuple[str, ...] | None:
+ """Split the file scope, or nothing when the caller did not scope."""
+ if not raw:
+ return None
+ parts = tuple(dict.fromkeys(p.strip() for p in raw.split(",") if p.strip()))
+ return parts[:_MAX_SCOPED_PATHS] or None
+
+
def _item(item: dict[str, Any]) -> dict[str, Any]:
"""Drop the reference minted for the other address space."""
return {key: value for key, value in item.items() if key != "plan_reference"}
@@ -50,6 +62,13 @@ async def list_performance_opportunities(
actionability: str | None = Query(None),
view: str = Query("detail"),
sort: str = Query("rank"),
+ file_paths: str | None = Query(
+ None,
+ description=(
+ "Comma-separated files to scope to, matched against the file "
+ "holding each opportunity's intervention."
+ ),
+ ),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session),
@@ -66,6 +85,7 @@ async def list_performance_opportunities(
actionability=actionability,
view=view,
sort=sort,
+ file_paths=_paths(file_paths),
limit=limit,
offset=offset,
)
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
new file mode 100644
index 000000000..72c6bca10
--- /dev/null
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -0,0 +1,302 @@
+"""The bounded field the Code Health map draws, selected deterministically.
+
+A map is a cap, and a cap is a claim about what is not drawn. Ordering the
+whole repository by lines of code and taking the top N is a defensible sample
+for the health lens and the wrong one for the performance lens: on this
+repository it hides tens of files that carry open opportunities, because a
+small file can hold the worst cause in the tree.
+
+So the feed admits files in three bands - the caller's active selection first,
+then the files carrying open performance opportunities in rank order, then the
+lines-of-code sample fills whatever capacity is left - and states exactly what
+the cap pushed out. One response carries both the rendered set and the counts
+describing it, so a caption can never disagree with the field beside it.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.health.perf.coverage import supported_perf_languages
+from repowise.core.persistence import crud
+
+__all__ = [
+ "DEFAULT_MAP_CAP",
+ "MAX_MAP_CAP",
+ "HealthMapFeed",
+ "HealthMapService",
+]
+
+DEFAULT_MAP_CAP = 2000
+"""Nodes drawn by default. Above this the field stops separating anything."""
+
+MAX_MAP_CAP = 4000
+"""Ceiling a caller may raise the cap to. Beyond it the canvas is a texture."""
+
+_MAX_ACTIVE = 50
+"""Guaranteed paths one request may pin. A deep link names one or a few."""
+
+_MODULE_ROLLUP_CAP = 200
+"""Modules described in the textual alternative, worst performance first."""
+
+
+@dataclass
+class HealthMapFeed:
+ """One bounded field plus the exact scope of what it leaves out."""
+
+ files: list[dict[str, Any]]
+ cap: int
+ shown: int
+ eligible_total: int
+ repository_total: int
+ selection: dict[str, Any]
+ omitted: dict[str, int]
+ recovery: dict[str, Any]
+ modules: list[dict[str, Any]] = field(default_factory=list)
+ performance: dict[str, Any] | None = None
+
+ def payload(self) -> dict[str, Any]:
+ return {
+ "files": self.files,
+ "cap": self.cap,
+ "shown": self.shown,
+ "eligible_total": self.eligible_total,
+ "repository_total": self.repository_total,
+ "selection": self.selection,
+ "omitted": self.omitted,
+ "recovery": self.recovery,
+ "modules": self.modules,
+ "performance": self.performance,
+ }
+
+
+def parse_active(raw: str | None) -> tuple[str, ...]:
+ """Split and bound the caller's guaranteed paths.
+
+ Order is preserved and duplicates collapse, because the first band is
+ admitted in the order the caller asked for.
+ """
+ if not raw:
+ return ()
+ seen: dict[str, None] = {}
+ for part in raw.split(","):
+ path = part.strip()
+ if path and path not in seen:
+ seen[path] = None
+ if len(seen) >= _MAX_ACTIVE:
+ break
+ return tuple(seen)
+
+
+class HealthMapService:
+ """Builds the map feed for one repository."""
+
+ def __init__(self, session: AsyncSession, repository_id: str) -> None:
+ self._session = session
+ self._repository_id = repository_id
+
+ async def feed(
+ self, *, cap: int = DEFAULT_MAP_CAP, active: tuple[str, ...] = ()
+ ) -> HealthMapFeed:
+ session, repo_id = self._session, self._repository_id
+ metrics = await crud.get_health_metrics(session, repo_id)
+ rollups = await crud.performance_file_rollups(session, repo_id)
+ languages = await crud.get_file_language_map(session, repo_id)
+ summary = await crud.get_performance_summary(session, repo_id)
+ perf_languages = supported_perf_languages()
+
+ by_path = {m.file_path: m for m in metrics}
+ # A zero-NLOC file cannot be sized, and the map drops it on arrival.
+ # Counting it as eligible would promise a node that never appears.
+ eligible = [m for m in metrics if (m.nloc or 0) > 0]
+ eligible_paths = {m.file_path for m in eligible}
+ burden = {r.file_path: r for r in rollups}
+
+ chosen: list[str] = []
+ taken: set[str] = set()
+
+ def admit(path: str) -> bool:
+ if path in taken or path not in eligible_paths or len(chosen) >= cap:
+ return False
+ chosen.append(path)
+ taken.add(path)
+ return True
+
+ active_shown = [path for path in active if admit(path)]
+
+ performance_eligible = [r.file_path for r in rollups if r.file_path in eligible_paths]
+ performance_shown = sum(1 for path in performance_eligible if admit(path))
+
+ nloc_before = len(chosen)
+ for metric in sorted(eligible, key=lambda m: (-(m.nloc or 0), m.file_path)):
+ if len(chosen) >= cap:
+ break
+ admit(metric.file_path)
+ nloc_shown = len(chosen) - nloc_before
+
+ drawn = [by_path[path] for path in chosen]
+ files = [
+ self._row(metric, burden.get(metric.file_path), languages, perf_languages)
+ for metric in drawn
+ ]
+
+ # Eligible and not taken, so this is what the cap pushed out. A cause
+ # on a file with no lines can never be drawn at any cap, and counting
+ # it here would promise a recovery that pinning the path cannot give.
+ undrawn_perf = [
+ r for r in rollups if r.file_path in eligible_paths and r.file_path not in taken
+ ]
+ omitted = {
+ "files": len(eligible) - len(chosen),
+ "performance_files": len(undrawn_perf),
+ "opportunities": sum(r.opportunities for r in undrawn_perf),
+ "observations": sum(r.observations for r in undrawn_perf),
+ }
+
+ return HealthMapFeed(
+ files=files,
+ cap=cap,
+ shown=len(chosen),
+ eligible_total=len(eligible),
+ repository_total=len(metrics),
+ selection={
+ "basis": "active_then_performance_then_nloc",
+ "active_requested": list(active),
+ "active_shown": active_shown,
+ "active_missing": [p for p in active if p not in taken],
+ "performance_shown": performance_shown,
+ "performance_eligible": len(performance_eligible),
+ "nloc_shown": nloc_shown,
+ },
+ omitted=omitted,
+ recovery={
+ "guarantee_paths": (
+ "Re-request this feed with active=<comma-separated paths> to pin any "
+ "file into the drawn field."
+ ),
+ "opportunity_queue": (
+ f"/api/repos/{repo_id}/health/performance-opportunities lists every "
+ "open opportunity, drawn or not."
+ ),
+ "raise_cap": f"cap accepts up to {MAX_MAP_CAP}.",
+ },
+ modules=self._modules(drawn, burden),
+ performance=self._performance_block(rollups, summary, len(performance_eligible)),
+ )
+
+ def _row(
+ self,
+ metric: Any,
+ rollup: Any,
+ languages: dict[str, str | None],
+ perf_languages: Any,
+ ) -> dict[str, Any]:
+ """One node. The lens reads the rollup; everything else is geometry.
+
+ The counts are always present, because a missing count is how the lens
+ recognizes a server with no read model and it must not confuse that
+ with a clear file. The two nullable keys are omitted when empty: most
+ of a large field carries no cause, and ``null`` on every row of it is
+ payload spent saying nothing.
+ """
+ row: dict[str, Any] = {
+ "file_path": metric.file_path,
+ "score": metric.score,
+ "nloc": metric.nloc,
+ "module": metric.module,
+ "line_coverage_pct": metric.line_coverage_pct,
+ "has_test_file": metric.has_test_file,
+ "maintainability_score": metric.maintainability_score,
+ "performance_analyzed": languages.get(metric.file_path) in perf_languages,
+ "performance_opportunities": rollup.opportunities if rollup else 0,
+ "performance_observations": rollup.observations if rollup else 0,
+ }
+ actionability = _leading_actionability(rollup)
+ if actionability is not None:
+ row["performance_actionability"] = actionability
+ row["performance_rank"] = rollup.best_rank
+ return row
+
+ def _modules(self, drawn: list[Any], burden: dict[str, Any]) -> list[dict[str, Any]]:
+ """Per-module rollup over the drawn field, for the navigable list.
+
+ Counted over what is drawn rather than over the repository, because
+ this list is how a keyboard reaches the field it describes.
+ """
+ rollup: dict[str, dict[str, Any]] = {}
+ for metric in drawn:
+ key = metric.module or "(ungrouped)"
+ row = rollup.setdefault(
+ key,
+ {
+ "module": key,
+ "files_shown": 0,
+ "opportunities": 0,
+ "observations": 0,
+ "plan_ready": 0,
+ "best_rank": None,
+ },
+ )
+ row["files_shown"] += 1
+ file_burden = burden.get(metric.file_path)
+ if file_burden is None:
+ continue
+ row["opportunities"] += file_burden.opportunities
+ row["observations"] += file_burden.observations
+ row["plan_ready"] += file_burden.plan_ready
+ best = row["best_rank"]
+ row["best_rank"] = (
+ file_burden.best_rank if best is None else min(best, file_burden.best_rank)
+ )
+ ordered = sorted(
+ rollup.values(),
+ key=lambda r: (
+ 0 if r["best_rank"] is not None else 1,
+ r["best_rank"] if r["best_rank"] is not None else 0,
+ r["module"],
+ ),
+ )
+ return ordered[:_MODULE_ROLLUP_CAP]
+
+ def _performance_block(
+ self, rollups: list[Any], summary: Any, eligible: int
+ ) -> dict[str, Any] | None:
+ """What the lens needs to describe itself honestly, or nothing.
+
+ ``None`` means this index has never materialized the read model, which
+ is a different answer from "analyzed and nothing surfaced" and the lens
+ must not render the two the same way.
+ """
+ if summary is None and not rollups:
+ return None
+ return {
+ "files_with_opportunities": len(rollups),
+ "files_with_opportunities_eligible": eligible,
+ "opportunities_total": sum(r.opportunities for r in rollups),
+ "observations_total": sum(r.observations for r in rollups),
+ "actionability": {
+ "plan_ready": sum(r.plan_ready for r in rollups),
+ "advisory": sum(r.advisory for r in rollups),
+ "investigate": sum(r.investigate for r in rollups),
+ },
+ "model_version": getattr(summary, "performance_model_version", None),
+ "analyzed_commit": getattr(summary, "analyzed_commit", None),
+ }
+
+
+def _leading_actionability(rollup: Any) -> str | None:
+ """The best thing a reader could do about this file, or nothing.
+
+ Best rather than most common: a file with one stored plan and nine
+ investigations is a file with a stored plan.
+ """
+ if rollup is None or rollup.opportunities == 0:
+ return None
+ if rollup.plan_ready:
+ return "plan_ready"
+ if rollup.advisory:
+ return "advisory"
+ return "investigate"
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 258c01ad2..417c0de1a 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -194,6 +194,24 @@ export interface HealthFileMetric {
* surfaced nothing", never "verified fast". `null`/absent on older payloads.
*/
performance_analyzed?: boolean | null;
+ /**
+ * Open causal opportunities on this file, and the observations behind them.
+ * The map's performance lens sizes its pressure ring by the opportunity
+ * count, because an opportunity is one thing a reader could go and do while
+ * an observation is one place a detector looked. Absent on payloads from a
+ * server that serves no materialized read model, which the lens renders as
+ * an unknown state rather than as zero.
+ */
+ performance_opportunities?: number | null;
+ performance_observations?: number | null;
+ /**
+ * Best available next step on this file: a stored plan outranks an advisory
+ * intervention, which outranks an investigation. `null` when the file
+ * carries no open opportunity. Never a claim about runtime magnitude.
+ */
+ performance_actionability?: PerformanceActionabilityState | null;
+ /** Best (lowest) queue rank position among this file's opportunities. */
+ performance_rank?: number | null;
/**
* Dominant-cause lead: the biomarker + reason of this file's worst finding, so
* a low file can headline "the one reason" instead of a wall of markers. Null
@@ -394,6 +412,12 @@ export type PerformanceOpportunityQuery = {
/** `summary` drops the explanatory fields and keeps identity and counts. */
view?: "detail" | "summary";
sort?: "rank" | "leverage" | "observations";
+ /**
+ * Scope to the opportunities whose intervention lives in these files. This
+ * is how a file-scoped surface asks the queue about one file instead of
+ * filtering a page it already narrowed.
+ */
+ file_paths?: string[];
limit?: number;
offset?: number;
};
@@ -535,6 +559,93 @@ export interface HealthFilesQuery {
fields?: "full" | "summary";
}
+/* ------------------------------------------------------------------ *
+ * Map feed
+ * ------------------------------------------------------------------ */
+
+/**
+ * How the server chose the drawn field.
+ *
+ * `active_then_performance_then_nloc`: the caller's guaranteed paths first,
+ * then the files carrying open performance opportunities in rank order, then
+ * lines-of-code descending for whatever capacity is left. Ranking the whole
+ * repository by size alone is a defensible sample for the health lens and the
+ * wrong one for performance, because a small file can hold the worst cause.
+ */
+export type HealthMapSelectionBasis = "active_then_performance_then_nloc";
+
+export interface HealthMapSelection {
+ basis: HealthMapSelectionBasis;
+ /** Paths the caller asked to pin, in the order they were asked for. */
+ active_requested: string[];
+ active_shown: string[];
+ /** Requested paths with no drawable metric row, so nothing pretends they are there. */
+ active_missing: string[];
+ performance_shown: number;
+ performance_eligible: number;
+ nloc_shown: number;
+}
+
+/** What the cap pushed out, in the units a reader would ask about. */
+export interface HealthMapOmissions {
+ files: number;
+ performance_files: number;
+ opportunities: number;
+ observations: number;
+}
+
+export interface HealthMapModuleRollup {
+ module: string;
+ files_shown: number;
+ opportunities: number;
+ observations: number;
+ plan_ready: number;
+ /** Best queue rank in the module, or `null` when it carries no opportunity. */
+ best_rank: number | null;
+}
+
+/** Repository-wide performance state the lens needs to describe itself. */
+export interface HealthMapPerformance {
+ files_with_opportunities: number;
+ files_with_opportunities_eligible: number;
+ opportunities_total: number;
+ observations_total: number;
+ actionability: {
+ plan_ready: number;
+ advisory: number;
+ investigate: number;
+ };
+ model_version: number | null;
+ analyzed_commit: string | null;
+}
+
+/**
+ * The bounded field the map draws, plus the exact scope of what it leaves out.
+ *
+ * The rendered set and the counts describing it come from one response, so a
+ * caption can never disagree with the field beside it.
+ */
+export interface HealthMapFeed {
+ files: HealthFileMetric[];
+ cap: number;
+ shown: number;
+ /** Files that could be drawn at all: a zero-NLOC file cannot be sized. */
+ eligible_total: number;
+ repository_total: number;
+ selection: HealthMapSelection;
+ omitted: HealthMapOmissions;
+ recovery: Record<string, string>;
+ modules: HealthMapModuleRollup[];
+ /** `null` when this index has never materialized the performance read model. */
+ performance: HealthMapPerformance | null;
+}
+
+export interface HealthMapQuery {
+ cap?: number;
+ /** Paths guaranteed a node, admitted before any other band. */
+ active?: string[];
+}
+
/* ------------------------------------------------------------------ *
* File breakdown (score drill-down)
* ------------------------------------------------------------------ */
diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsx
index 0d5a68e6e..f6203a640 100644
--- a/packages/ui/__tests__/health/code-health-map.test.tsx
+++ b/packages/ui/__tests__/health/code-health-map.test.tsx
@@ -5,6 +5,9 @@ import {
MapLegend,
MapLensSwitcher,
groupByModule,
+ performanceBurden,
+ performanceFill,
+ performanceSentence,
type CodeHealthMapFile,
} from "../../src/health/code-health-map.js";
@@ -115,10 +118,21 @@ describe("CodeHealthMap", () => {
expect(blob).toBeTruthy();
fireEvent.click(blob!);
expect(getByText("← Overview")).toBeInTheDocument();
- fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent.keyDown(blob!, { key: "Escape" });
expect(queryByText("← Overview")).not.toBeInTheDocument();
});
+ it("leaves an Escape aimed at something else alone", () => {
+ // The listener used to be on the window, so dismissing anything else on
+ // the page - the file drawer this map opens, most of all - also reset the
+ // zoom underneath it.
+ const files = [f("core/a.py", 120, "core"), f("ui/c.py", 40, "ui")];
+ const { getByText, container } = render(<CodeHealthMap files={files} />);
+ fireEvent.click(container.querySelector("circle[data-galaxy]")!);
+ fireEvent.keyDown(document.body, { key: "Escape" });
+ expect(getByText("← Overview")).toBeInTheDocument();
+ });
+
it("shows the on-canvas health legend", () => {
const { getByText } = render(<CodeHealthMap files={[f("a.py", 30, "core")]} />);
expect(getByText("Health")).toBeInTheDocument();
@@ -134,29 +148,71 @@ describe("CodeHealthMap", () => {
expect(getByText("≥80%")).toBeInTheDocument();
});
- it("performance lens colors by findings + coverage, not the score", () => {
- // Three files: covered-with-findings (heat), covered-clean (green), and an
- // unsupported-language file the perf pass never ran on (grey, NOT green).
+ it("never fills an analyzed-clear file green under the performance lens", () => {
+ // A detector that surfaced nothing has proved the absence of a *supported
+ // pattern*, not that the file is fast. Green is the strongest reassurance
+ // the surface has, and this is its weakest evidence.
const files: CodeHealthMapFile[] = [
- { ...f("core/hot.py", 120, "core"), performance_findings: 7, performance_analyzed: true },
- { ...f("core/clean.py", 80, "core"), performance_findings: 0, performance_analyzed: true },
- { ...f("core/leveldb.cc", 60, "core"), performance_findings: 0, performance_analyzed: false },
+ { ...f("core/hot.py", 120, "core"), performance_opportunities: 7, performance_observations: 12, performance_actionability: "plan_ready", performance_analyzed: true },
+ { ...f("core/clean.py", 80, "core"), performance_opportunities: 0, performance_analyzed: true },
+ { ...f("core/leveldb.cc", 60, "core"), performance_opportunities: 0, performance_analyzed: false },
];
- const { container, getByText } = render(
- <CodeHealthMap files={files} overlay="performance" />,
- );
- // Educational legend: findings-first, plus the "not analyzed" grey.
- expect(getByText("5+ findings")).toBeInTheDocument();
- expect(getByText("Not analyzed")).toBeInTheDocument();
- expect(getByText("Analyzed, none found")).toBeInTheDocument();
-
+ const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
const fillFor = (path: string) =>
container.querySelector(`circle[data-path="${path}"]`)?.getAttribute("fill");
- // A file with findings burns red; a covered-clean file is green; an
- // un-analyzed file is grey (tertiary) — never green.
- expect(fillFor("core/hot.py")).toBe("var(--color-error)");
- expect(fillFor("core/clean.py")).toBe("var(--color-success)");
- expect(fillFor("core/leveldb.cc")).toBe("var(--color-text-tertiary)");
+ for (const path of ["core/hot.py", "core/clean.py", "core/leveldb.cc"]) {
+ expect(fillFor(path)).not.toBe("var(--color-success)");
+ }
+ // Analysed and unanalysed differ, and neither differs by hue.
+ expect(fillFor("core/clean.py")).toBe("var(--color-text-tertiary)");
+ expect(fillFor("core/leveldb.cc")).toBe("var(--color-border-default)");
+ });
+
+ it("carries the burden on the node and the plan on the ring", () => {
+ const files: CodeHealthMapFile[] = [
+ { ...f("core/planned.py", 120, "core"), performance_opportunities: 9, performance_actionability: "plan_ready", performance_analyzed: true },
+ { ...f("core/one.py", 100, "core"), performance_opportunities: 1, performance_actionability: "investigate", performance_analyzed: true },
+ { ...f("core/clean.py", 80, "core"), performance_opportunities: 0, performance_analyzed: true },
+ ];
+ const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
+ const fillOf = (p: string) =>
+ container.querySelector(`circle[data-path="${p}"]`)?.getAttribute("fill");
+ expect(fillOf("core/planned.py")).toBe("var(--color-error)");
+ expect(fillOf("core/one.py")).toContain("--color-caution");
+ expect(fillOf("core/clean.py")).toBe("var(--color-text-tertiary)");
+ // The ring is the rare mark, not one every coloured node carries.
+ expect(container.querySelector('circle[data-ring="core/planned.py"]')).toBeTruthy();
+ expect(container.querySelector('circle[data-ring="core/one.py"]')).toBeNull();
+ expect(container.querySelector('circle[data-ring="core/clean.py"]')).toBeNull();
+ });
+
+ it("draws no ring under any other lens", () => {
+ const files: CodeHealthMapFile[] = [
+ { ...f("core/many.py", 120, "core"), performance_opportunities: 9, performance_analyzed: true },
+ ];
+ const { container } = render(<CodeHealthMap files={files} overlay="health" />);
+ expect(container.querySelectorAll("circle[data-ring]")).toHaveLength(0);
+ });
+
+ it("counts observations and says so when the host serves no causal model", () => {
+ // A host with raw observations and no read model still gets a lens; it is
+ // told which unit it is counting rather than being handed a number under
+ // the other one's name.
+ const files: CodeHealthMapFile[] = [
+ { ...f("core/hot.py", 120, "core"), performance_findings: 4, performance_analyzed: true },
+ ];
+ expect(performanceBurden(files[0]!)).toEqual({
+ state: "investigate",
+ count: 4,
+ unit: "observations",
+ });
+ expect(performanceSentence(files[0]!)).toContain("observations");
+ });
+
+ it("reports an unknown state when nothing on the row says either way", () => {
+ const row = f("core/x.py", 10, "core");
+ expect(performanceBurden(row).state).toBe("unknown");
+ expect(performanceFill(row)).toBe("var(--color-border-default)");
});
it("fires onOverlayChange when a lens-switch button is clicked", () => {
@@ -167,8 +223,9 @@ describe("CodeHealthMap", () => {
onOverlayChange={onOverlayChange}
/>,
);
- // The lens switcher renders one toggle button per lens; click "Maintainability".
- fireEvent.click(getByRole("button", { name: "Maintainability" }));
+ // One switcher implementation, on the canvas and off it, so the two can
+ // never disagree about what picking a lens means.
+ fireEvent.click(getByRole("radio", { name: "Maintainability" }));
expect(onOverlayChange).toHaveBeenCalledWith("maintainability");
});
@@ -180,10 +237,10 @@ describe("CodeHealthMap", () => {
lenses={["health", "churn"]}
/>,
);
- expect(getByRole("button", { name: "Churn" })).toBeInTheDocument();
+ expect(getByRole("radio", { name: "Churn" })).toBeInTheDocument();
// Churn is not a default lens: it colors from a field the host has to join
// in, so a host that did not join it must not be able to select it.
- expect(queryByRole("button", { name: "Maintainability" })).not.toBeInTheDocument();
+ expect(queryByRole("radio", { name: "Maintainability" })).not.toBeInTheDocument();
});
it('chrome="none" renders neither the switcher nor the legend', () => {
@@ -194,7 +251,7 @@ describe("CodeHealthMap", () => {
chrome="none"
/>,
);
- expect(queryByRole("button", { name: "Maintainability" })).not.toBeInTheDocument();
+ expect(queryByRole("radio", { name: "Maintainability" })).not.toBeInTheDocument();
expect(queryByText(/galaxy = module/i)).not.toBeInTheDocument();
});
@@ -204,7 +261,7 @@ describe("CodeHealthMap", () => {
const { getByRole } = render(
<CodeHealthMap files={[f("a.py", 30, "core")]} onOverlayChange={vi.fn()} />,
);
- expect(getByRole("button", { name: "Maintainability" })).toBeInTheDocument();
+ expect(getByRole("radio", { name: "Maintainability" })).toBeInTheDocument();
});
});
@@ -222,9 +279,13 @@ describe("map chrome, off canvas", () => {
it("MapLegend renders the active lens's bands and caption", () => {
const { getByText } = render(<MapLegend overlay="performance" />);
- expect(getByText("5+ findings")).toBeInTheDocument();
+ expect(getByText("5 or more")).toBeInTheDocument();
expect(getByText("Not analyzed")).toBeInTheDocument();
- expect(getByText(/color = findings, not a score/i)).toBeInTheDocument();
+ // The caption refuses the runtime claim the colour could be read as making,
+ // and the rows are grouped so a flat column of swatches is not the whole key.
+ expect(getByText(/never a runtime measurement/i)).toBeInTheDocument();
+ expect(getByText("Open causes")).toBeInTheDocument();
+ expect(getByText("Ringed")).toBeInTheDocument();
});
it("MapLegend says it is loading rather than showing bands for absent data", () => {
diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsx
index 1f9e8fc04..0067c0e40 100644
--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx
+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx
@@ -5,6 +5,7 @@ import {
type HealthDrawerFinding,
type HealthDrawerMetric,
} from "../../src/health/health-file-drawer.js";
+import type { PerformanceOpportunity } from "@repowise-dev/types/health";
function metric(partial: Partial<HealthDrawerMetric> = {}): HealthDrawerMetric {
return {
@@ -467,3 +468,150 @@ describe("HealthFileDrawer bug history", () => {
expect(screen.queryByRole("button", { name: /Bug history/ })).not.toBeInTheDocument();
});
});
+
+describe("HealthFileDrawer under the performance lens", () => {
+ function cause(
+ id: string,
+ partial: Partial<PerformanceOpportunity> = {},
+ ): PerformanceOpportunity {
+ return {
+ opportunity_id: id,
+ performance_model_version: 2,
+ biomarker_type: "serial_await_in_loop",
+ biomarker_types: ["serial_await_in_loop"],
+ boundary_kind: "db",
+ execution_context: "production",
+ terminal_sink: null,
+ shared_path_suffix: [],
+ intervention_symbol: null,
+ file_path: "packages/cli/doctor_cmd.py",
+ resource_fingerprints: [],
+ affected_call_sites_total: 1,
+ affected_files_total: 1,
+ observations_total: 1,
+ evidence: [],
+ evidence_truncated: false,
+ evidence_total: 1,
+ evidence_emitted: 1,
+ reliable_entry_reachability: null,
+ provenance: "direct",
+ confidence: "high",
+ facets: {
+ actionability_confidence: "high",
+ exposure: "unknown",
+ amplification: "unknown",
+ leverage: "single_site",
+ change_risk: "low",
+ },
+ actionability_state: "plan_ready",
+ actionability_reason: "proven_strategy",
+ prerequisites: [],
+ rank_score: 10,
+ rank_position: 0,
+ rank_factors: {},
+ why_ranked: [],
+ fix: null,
+ plan_id: "plan-1",
+ plan_status: "available",
+ plan_reason: "",
+ ...partial,
+ } as PerformanceOpportunity;
+ }
+
+ const located = (id: string, fn: string, line: number) =>
+ cause(id, {
+ evidence: [
+ {
+ finding_id: `finding_${id}`,
+ file_path: "packages/cli/doctor_cmd.py",
+ biomarker_type: "serial_await_in_loop",
+ function_name: fn,
+ line_start: line,
+ line_end: line,
+ reason: "a database call is awaited serially in a loop",
+ path: [],
+ provenance: "direct",
+ },
+ ],
+ });
+
+ it("leads with the causes rather than with the defect score", () => {
+ const { getByText } = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ lens="performance"
+ performance={{ items: [cause("perf2_a")], total: 1 }}
+ />,
+ );
+ expect(getByText("Performance causes")).toBeInTheDocument();
+ });
+
+ it("tells two causes of one marker apart by where they fire", () => {
+ // Thirty-six causes of a single marker on one file is real here. Titling
+ // them by the marker alone renders thirty-six identical rows.
+ const { getByText } = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ lens="performance"
+ performance={{
+ items: [located("perf2_a", "sweep_pages", 1312), located("perf2_b", "sweep_cycles", 1218)],
+ total: 2,
+ }}
+ />,
+ );
+ expect(getByText("sweep_pages:1312")).toBeInTheDocument();
+ expect(getByText("sweep_cycles:1218")).toBeInTheDocument();
+ });
+
+ it("counts the repository's causes, not the slice it was handed", () => {
+ const { getByText } = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ lens="performance"
+ performance={{ items: [cause("perf2_a"), cause("perf2_b")], total: 36 }}
+ />,
+ );
+ // The figures sit in their own tabular-nums spans, so read the sentence.
+ const summary = getByText(/open cause/).textContent ?? "";
+ expect(summary).toContain("36 open causes");
+ expect(summary).toContain("2 shown");
+ });
+
+ it("says nothing about performance under another lens", () => {
+ const { queryByText } = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ performance={{ items: [cause("perf2_a")], total: 1 }}
+ />,
+ );
+ expect(queryByText("Performance causes")).not.toBeInTheDocument();
+ });
+
+ it("distinguishes a host that did not ask from a file with no cause", () => {
+ const notWired = render(
+ <HealthFileDrawer open onClose={() => {}} metric={metric()} lens="performance" />,
+ );
+ expect(notWired.getByText(/no performance data wired up/)).toBeInTheDocument();
+
+ const clean = render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ lens="performance"
+ performance={{ items: [], total: 0 }}
+ />,
+ );
+ // And refuses the reading that a clear detector run means the file is fast.
+ const empty = clean.getByText(/No open cause names this file/).textContent ?? "";
+ expect(empty).toContain("not a measurement that it is fast");
+ });
+});
diff --git a/packages/ui/__tests__/health/impact-figure.test.tsx b/packages/ui/__tests__/health/impact-figure.test.tsx
new file mode 100644
index 000000000..15768850c
--- /dev/null
+++ b/packages/ui/__tests__/health/impact-figure.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * How a deduction is printed, in one place.
+ *
+ * Two zeros meet here and must not be confused. A performance finding scores
+ * exactly zero by construction and has no deduction to show; a defect finding
+ * worth a thousandth of a point has one that is merely too small to print. The
+ * old formatter rendered both as a red "-0.00".
+ */
+import { describe, it, expect } from "vitest";
+import { render } from "@testing-library/react";
+import { ImpactFigure } from "../../src/health/impact-figure.js";
+import { formatDelta, formatHealthImpact } from "../../src/health/tokens.js";
+
+describe("formatHealthImpact", () => {
+ it("has nothing to print for a finding that scores no impact", () => {
+ expect(formatHealthImpact(0)).toBeNull();
+ expect(formatHealthImpact(null)).toBeNull();
+ expect(formatHealthImpact(undefined)).toBeNull();
+ });
+
+ it("prints a real deduction too small to show as a bound, not as zero", () => {
+ // The alternative reads as "measured, and it costs nothing", which is a
+ // stronger claim than the number supports.
+ expect(formatHealthImpact(0.003)).toBe("−<0.01");
+ expect(formatHealthImpact(-0.003)).toBe("−<0.01");
+ });
+
+ it("prints an ordinary deduction to two places", () => {
+ expect(formatHealthImpact(1.234)).toBe("−1.23");
+ expect(formatHealthImpact(2.5)).toBe("−2.50");
+ });
+
+ it("never yields a signed zero", () => {
+ for (const v of [0, -0, 0.0001, -0.0001, 0.004]) {
+ expect(formatHealthImpact(v)).not.toBe("−0.00");
+ }
+ });
+});
+
+describe("formatDelta", () => {
+ it("does not sign a delta that rounded to nothing", () => {
+ expect(formatDelta(-0.001)).toBe("0.00");
+ expect(formatDelta(0.001)).toBe("0.00");
+ expect(formatDelta(-0.4)).toBe("-0.40");
+ expect(formatDelta(0.4)).toBe("+0.40");
+ });
+});
+
+describe("ImpactFigure", () => {
+ it("says a marker is unscored in a word, not a number", () => {
+ const { container } = render(<ImpactFigure impact={0} />);
+ expect(container.textContent).toBe("not scored");
+ });
+
+ it("keeps the deduction colour for deductions only", () => {
+ // Red is what a deduction looks like on this surface. A marker with none
+ // wearing it is the same confusion the figure was meant to end.
+ const unscored = render(<ImpactFigure impact={0} />).container.firstElementChild;
+ expect(unscored?.className).not.toContain("color-error");
+
+ const scored = render(<ImpactFigure impact={1.2} />).container.firstElementChild;
+ expect(scored?.className).toContain("color-error");
+ expect(scored?.textContent).toBe("−1.20");
+ });
+
+ it("keeps the caller's layout classes on both branches", () => {
+ for (const impact of [0, 1.2]) {
+ const el = render(<ImpactFigure impact={impact} className="ml-auto text-xs" />)
+ .container.firstElementChild;
+ expect(el?.className).toContain("ml-auto");
+ }
+ });
+});
diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsx
new file mode 100644
index 000000000..dd2745a03
--- /dev/null
+++ b/packages/ui/__tests__/health/map-lens.test.tsx
@@ -0,0 +1,406 @@
+/**
+ * The performance lens on the one galaxy: what the field says, what it refuses
+ * to say, and what it costs to interact with.
+ */
+import { describe, it, expect, vi, beforeAll } from "vitest";
+import { render, fireEvent } from "@testing-library/react";
+import {
+ CodeHealthMap,
+ SEARCH_MARK_CAP,
+ burdenBand,
+ performanceBurden,
+ performanceFill,
+ performanceOpacity,
+ pressureRing,
+ type CodeHealthMapFile,
+ type MapScope,
+} from "../../src/health/code-health-map.js";
+import { MapFieldList, MapInspector } from "../../src/health/map/inspector.js";
+
+function f(
+ file_path: string,
+ nloc: number,
+ module: string | null,
+ extra: Partial<CodeHealthMapFile> = {},
+): CodeHealthMapFile {
+ return {
+ file_path,
+ nloc,
+ score: 7,
+ module,
+ line_coverage_pct: null,
+ has_test_file: false,
+ ...extra,
+ };
+}
+
+beforeAll(() => {
+ class RO {
+ cb: ResizeObserverCallback;
+ constructor(cb: ResizeObserverCallback) {
+ this.cb = cb;
+ }
+ observe() {
+ this.cb(
+ [{ contentRect: { width: 800, height: 600 } } as ResizeObserverEntry],
+ this as unknown as ResizeObserver,
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal("ResizeObserver", RO);
+});
+
+const scope: MapScope = {
+ shown: 2,
+ eligible: 40,
+ repository: 44,
+ cap: 2,
+ omitted: { files: 38, performanceFiles: 3, opportunities: 9, observations: 14 },
+};
+
+describe("burden encoding", () => {
+ it("bands the count rather than scaling with it", () => {
+ // Forty causes and five are the same instruction to the reader. A ring that
+ // grew with the raw count would claim a magnitude the analysis has not
+ // measured.
+ expect(burdenBand(0)).toBe(0);
+ expect(burdenBand(1)).toBe(1);
+ expect([burdenBand(2), burdenBand(4)]).toEqual([2, 2]);
+ expect([burdenBand(5), burdenBand(40)]).toEqual([3, 3]);
+ });
+
+ it("leads with the best available step, not the most common one", () => {
+ const row = f("a.py", 10, "core", {
+ performance_opportunities: 10,
+ performance_actionability: "plan_ready",
+ performance_analyzed: true,
+ });
+ expect(performanceBurden(row).state).toBe("actionable");
+ // The one file shape that earns a second mark.
+ expect(pressureRing(row)).not.toBeNull();
+ });
+
+ it("rings only a cause with a stored plan, so the mark stays rare", () => {
+ const base = { performance_opportunities: 9, performance_analyzed: true } as const;
+ expect(
+ pressureRing(f("a.py", 10, "core", { ...base, performance_actionability: "advisory" })),
+ ).toBeNull();
+ expect(
+ pressureRing(f("b.py", 10, "core", { ...base, performance_actionability: "investigate" })),
+ ).toBeNull();
+ });
+
+ it("colours the node by how many causes it carries", () => {
+ const at = (n: number) =>
+ performanceFill(f("a.py", 10, "core", {
+ performance_opportunities: n,
+ performance_analyzed: true,
+ }));
+ expect(at(1)).toContain("--color-caution");
+ expect(at(3)).toContain("--color-warning");
+ expect(at(9)).toBe("var(--color-error)");
+ // The two quiet steps mix toward the page, never toward transparency.
+ expect(at(1)).toContain("--color-bg-root");
+ });
+
+ it("pushes a file with no cause into the ground", () => {
+ // Most of a repository is this, and the first cut drew every one of them
+ // at nine tenths opacity, which tiled into a sheet the marks sat behind.
+ const clear = f("a.py", 10, "core", {
+ performance_opportunities: 0,
+ performance_analyzed: true,
+ });
+ const loaded = f("b.py", 10, "core", {
+ performance_opportunities: 6,
+ performance_actionability: "advisory",
+ performance_analyzed: true,
+ });
+ const unsupported = f("c.cc", 10, "core", {
+ performance_opportunities: 0,
+ performance_analyzed: false,
+ });
+ expect(performanceOpacity(clear)).toBeLessThan(0.4);
+ expect(performanceOpacity(loaded)).toBeGreaterThan(performanceOpacity(clear));
+ expect(performanceOpacity(unsupported)).toBeLessThan(performanceOpacity(clear));
+
+ // A loaded node is fully present whatever its band: the nodes overlap, so
+ // a translucent ramp composites two light ones into the darker band's tone.
+ const at = (n: number) =>
+ performanceOpacity(f("x.py", 10, "core", {
+ performance_opportunities: n,
+ performance_analyzed: true,
+ }));
+ expect(at(1)).toBe(at(9));
+ });
+
+ it("gives an unsupported language no ring and no clear verdict", () => {
+ const row = f("a.cc", 10, "core", {
+ performance_opportunities: 0,
+ performance_analyzed: false,
+ });
+ expect(pressureRing(row)).toBeNull();
+ expect(performanceBurden(row).state).toBe("unsupported");
+ });
+});
+
+describe("scope disclosure", () => {
+ it("states the drawn count against the eligible count, not the repository", () => {
+ const { getByTestId } = render(
+ <CodeHealthMap files={[f("a.py", 10, "core"), f("b.py", 5, "core")]} scope={scope} />,
+ );
+ const note = getByTestId("map-scope").textContent ?? "";
+ expect(note).toContain("2 of 40");
+ expect(note).not.toContain("44");
+ });
+
+ it("names the files with causes the cap pushed out", () => {
+ const { getByTestId } = render(
+ <CodeHealthMap files={[f("a.py", 10, "core")]} scope={scope} />,
+ );
+ expect(getByTestId("map-scope").textContent).toContain("3 files with open causes not drawn");
+ });
+
+ it("says so when the cap left no cause behind", () => {
+ const { getByTestId } = render(
+ <CodeHealthMap
+ files={[f("a.py", 10, "core")]}
+ scope={{ ...scope, omitted: { ...scope.omitted, performanceFiles: 0 } }}
+ />,
+ );
+ expect(getByTestId("map-scope").textContent).toContain(
+ "every file with an open cause is drawn",
+ );
+ });
+});
+
+describe("search", () => {
+ const files = Array.from({ length: 40 }, (_, i) =>
+ f(`core/file${i}.py`, 100 - i, "core"),
+ );
+
+ it("marks the matches instead of touching the field", () => {
+ const { container, rerender } = render(<CodeHealthMap files={files} search="" />);
+ const before = container.querySelector('circle[data-path="core/file7.py"]');
+ rerender(<CodeHealthMap files={files} search="file7" />);
+ const after = container.querySelector('circle[data-path="core/file7.py"]');
+ // The same DOM node, with the same attributes: the base layer was not
+ // reconciled, so typing costs the marks and nothing else.
+ expect(after).toBe(before);
+ expect(after!.getAttribute("fill-opacity")).toBe("0.9");
+ expect(container.querySelectorAll("circle[data-match]").length).toBeGreaterThan(0);
+ });
+
+ it("does not re-lay the field when the query changes", () => {
+ const { container, rerender } = render(<CodeHealthMap files={files} search="" />);
+ const at = (p: string) => {
+ const n = container.querySelector(`circle[data-path="${p}"]`)!;
+ return `${n.getAttribute("cx")},${n.getAttribute("cy")},${n.getAttribute("r")}`;
+ };
+ const before = at("core/file3.py");
+ rerender(<CodeHealthMap files={files} search="fi" />);
+ rerender(<CodeHealthMap files={files} search="file" />);
+ expect(at("core/file3.py")).toBe(before);
+ });
+
+ it("bounds how many matches it draws", () => {
+ const many = Array.from({ length: SEARCH_MARK_CAP + 30 }, (_, i) =>
+ f(`core/hit${i}.py`, 50, "core"),
+ );
+ const { container } = render(<CodeHealthMap files={many} search="hit" />);
+ expect(container.querySelectorAll("circle[data-match]").length).toBe(SEARCH_MARK_CAP);
+ });
+
+ it("marks the paths a deep link asked for, with no query at all", () => {
+ const { container } = render(
+ <CodeHealthMap files={files} highlightPaths={["core/file2.py"]} />,
+ );
+ expect(container.querySelector('circle[data-match="core/file2.py"]')).toBeTruthy();
+ });
+});
+
+describe("what the field costs to draw", () => {
+ const files = Array.from({ length: 300 }, (_, i) =>
+ f(`core/f${i}.py`, 200 - (i % 150), i % 2 ? "core" : "ui", {
+ performance_opportunities: i % 5 === 0 ? (i % 9) + 1 : 0,
+ performance_actionability: "advisory",
+ performance_analyzed: true,
+ }),
+ );
+
+ it("rings a fraction of the field, not a mark on every node", () => {
+ const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
+ const nodes = container.querySelectorAll("circle[data-path]").length;
+ const rings = container.querySelectorAll("circle[data-ring]").length;
+ expect(nodes).toBe(300);
+ // The fixture's causes are all advisory, so none earns a ring: the burden
+ // rides on the node's own colour and costs no extra element at all.
+ expect(rings).toBe(0);
+ });
+
+ it("keeps the safeguards that make thousands of nodes affordable", () => {
+ const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
+ // A native tooltip per node, an offscreen raster pass, and a per-frame
+ // stroke recomputation. Each was measured and removed; none may return.
+ expect(container.querySelectorAll("title")).toHaveLength(0);
+ expect(container.querySelectorAll("filter")).toHaveLength(0);
+ expect(container.querySelectorAll("circle[data-path][vector-effect]")).toHaveLength(0);
+ expect(container.querySelectorAll("circle[data-ring][vector-effect]")).toHaveLength(0);
+ });
+});
+
+describe("keyboard", () => {
+ const files = [
+ f("core/a.py", 120, "core"),
+ f("core/b.py", 60, "core"),
+ f("ui/c.py", 40, "ui"),
+ ];
+
+ it("reaches every file through one tab stop", () => {
+ const onSelectFile = vi.fn();
+ const { getByRole, container } = render(
+ <CodeHealthMap files={files} onSelectFile={onSelectFile} />,
+ );
+ // One focusable region for the whole field. Thousands of tab stops is not
+ // navigation, and a canvas with none is not reachable.
+ expect(container.querySelectorAll('[tabindex="0"]')).toHaveLength(1);
+ const field = getByRole("group", { name: /Code health map/ });
+
+ fireEvent.keyDown(field, { key: "Enter" }); // into the first module
+ fireEvent.keyDown(field, { key: "ArrowRight" }); // second file in it
+ expect(container.querySelector("circle[data-keyboard-cursor]")).toBeTruthy();
+ fireEvent.keyDown(field, { key: "Enter" });
+ expect(onSelectFile).toHaveBeenCalledWith("core/b.py");
+ });
+
+ it("announces where the cursor is", () => {
+ const { getByRole, container } = render(<CodeHealthMap files={files} />);
+ const field = getByRole("group", { name: /Code health map/ });
+ fireEvent.keyDown(field, { key: "Enter" });
+ const live = container.querySelector('[aria-live="polite"]');
+ expect(live?.textContent).toContain("core/a.py");
+ });
+
+ it("Escape climbs back out to the modules", () => {
+ const { getByRole, container, queryByText } = render(<CodeHealthMap files={files} />);
+ const field = getByRole("group", { name: /Code health map/ });
+ fireEvent.keyDown(field, { key: "Enter" });
+ expect(queryByText("← Overview")).toBeInTheDocument();
+ fireEvent.keyDown(field, { key: "Escape" });
+ expect(container.querySelector("circle[data-keyboard-cursor]")).toBeNull();
+ });
+});
+
+describe("the navigable list beside the field", () => {
+ const files = [
+ f("core/a.py", 120, "core", {
+ performance_opportunities: 5,
+ performance_observations: 8,
+ performance_actionability: "advisory",
+ performance_rank: 2,
+ performance_analyzed: true,
+ }),
+ f("core/b.py", 60, "core", {
+ performance_opportunities: 1,
+ performance_actionability: "plan_ready",
+ performance_rank: 0,
+ performance_analyzed: true,
+ }),
+ f("ui/c.py", 40, "ui", { performance_opportunities: 0, performance_analyzed: true }),
+ ];
+
+ it("ranks by the queue's own order and opens the same selection a click does", () => {
+ const onSelectFile = vi.fn();
+ const { getAllByRole } = render(
+ <MapFieldList files={files} overlay="performance" onSelectFile={onSelectFile} />,
+ );
+ const rows = getAllByRole("button");
+ expect(rows[0]!.textContent).toContain("core/b.py"); // rank 0 leads
+ fireEvent.click(rows[0]!);
+ expect(onSelectFile).toHaveBeenCalledWith("core/b.py");
+ });
+
+ it("lists only files with a cause under the performance lens, and says how many", () => {
+ const { getAllByRole, getByText } = render(
+ <MapFieldList files={files} overlay="performance" onSelectFile={vi.fn()} scope={scope} />,
+ );
+ expect(getAllByRole("button")).toHaveLength(2);
+ expect(getByText(/3 more carry causes outside the drawn field/)).toBeInTheDocument();
+ });
+
+ it("says plainly when the drawn field carries none", () => {
+ const { getByText } = render(
+ <MapFieldList
+ files={[f("ui/c.py", 40, "ui", { performance_opportunities: 0 })]}
+ overlay="performance"
+ onSelectFile={vi.fn()}
+ />,
+ );
+ expect(getByText(/No file in the drawn field carries an open performance cause/)).toBeInTheDocument();
+ });
+
+ it("ranks worst-score-first under a score lens", () => {
+ const scored = [f("a.py", 10, "core"), { ...f("b.py", 10, "core"), score: 2 }];
+ const { getAllByRole } = render(
+ <MapFieldList files={scored} overlay="health" onSelectFile={vi.fn()} />,
+ );
+ expect(getAllByRole("button")[0]!.textContent).toContain("b.py");
+ });
+});
+
+describe("the inspector", () => {
+ const row = f("core/a.py", 120, "core", {
+ performance_opportunities: 5,
+ performance_observations: 8,
+ performance_actionability: "advisory",
+ performance_analyzed: true,
+ });
+
+ it("describes the selection in the active lens's terms", () => {
+ const { getByText } = render(
+ <MapInspector file={row} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
+ );
+ expect(getByText("Open opportunities")).toBeInTheDocument();
+ expect(getByText("Observations behind them")).toBeInTheDocument();
+ expect(getByText("Advisory")).toBeInTheDocument();
+ });
+
+ it("leads with the burden, not the defect score, under its own lens", () => {
+ // The defect badge led here, so a file with a healthy score and a heavy
+ // ring beside it opened an inspector that said the opposite of the mark.
+ const { container, getByText } = render(
+ <MapInspector file={row} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
+ );
+ expect(getByText("Open opportunities")).toBeInTheDocument();
+ expect(getByText(/defect risk 7\.0/)).toBeInTheDocument();
+ // The score badge, which is the defect ramp, is not the leading mark.
+ const leading = container.querySelector("section > div")?.firstElementChild;
+ expect(leading?.textContent).toBe("");
+ });
+
+ it("keeps the defect score leading under a score lens", () => {
+ const { getByText } = render(
+ <MapInspector file={row} overlay="health" onOpen={vi.fn()} onClose={vi.fn()} />,
+ );
+ expect(getByText("7.0")).toBeInTheDocument();
+ });
+
+ it("says nothing about performance under another lens", () => {
+ const { queryByText } = render(
+ <MapInspector file={row} overlay="health" onOpen={vi.fn()} onClose={vi.fn()} />,
+ );
+ expect(queryByText("Open opportunities")).not.toBeInTheDocument();
+ });
+
+ it("never calls an analyzed-clear file fast", () => {
+ const clear = f("core/clean.py", 10, "core", {
+ performance_opportunities: 0,
+ performance_analyzed: true,
+ });
+ const { getByText } = render(
+ <MapInspector file={clear} overlay="performance" onOpen={vi.fn()} onClose={vi.fn()} />,
+ );
+ expect(getByText("Analyzed, nothing surfaced")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsx
index 82f2a320c..3fa78d417 100644
--- a/packages/ui/__tests__/health/performance-view.test.tsx
+++ b/packages/ui/__tests__/health/performance-view.test.tsx
@@ -538,3 +538,59 @@ describe("PerformanceView accessibility", () => {
expect(statuses.some((text) => text.includes("opportunities"))).toBe(true);
});
});
+
+describe("PerformanceView opened by a link", () => {
+ it("opens the cause the link names, even when the queue page does not hold it", async () => {
+ // The map and the file drawer mint links naming a cause by id. This
+ // repository has hundreds of them, so the named one is usually not on the
+ // page the filters would have loaded, and searching the page for it would
+ // find nothing.
+ const detail = resolvedDetail({ opportunity_id: "perf2_linked" });
+ const getPerformanceOpportunity = vi.fn(async () => detail);
+ render(
+ <PerformanceView
+ adapter={adapter({ getPerformanceOpportunity })}
+ openOpportunityId="perf2_linked"
+ />,
+ );
+ expect(await screen.findByRole("dialog")).toBeTruthy();
+ expect(getPerformanceOpportunity).toHaveBeenCalledWith("perf2_linked", {
+ evidenceLimit: 8,
+ });
+ });
+
+ it("reports the id back so an inspected cause is itself a link", async () => {
+ const onOpenOpportunityChange = vi.fn();
+ render(
+ <PerformanceView adapter={adapter()} onOpenOpportunityChange={onOpenOpportunityChange} />,
+ );
+ await openFirstRow();
+ // The first row of the fixture page, by its stable id.
+ expect(onOpenOpportunityChange).toHaveBeenCalledWith(page().items[0]!.opportunity_id);
+ });
+
+ it("says so when the link names a cause this index cannot resolve", async () => {
+ const unresolved = {
+ resolved: false as const,
+ opportunity_id: "perf2_retired",
+ model_state: {
+ state: "stale_model" as const,
+ opportunity_id: "perf2_retired",
+ performance_model_version: 2,
+ requested_model_version: 1,
+ refresh_required: true,
+ },
+ detail: "That cause was written by an older model.",
+ };
+ render(
+ <PerformanceView
+ adapter={adapter({ getPerformanceOpportunity: vi.fn(async () => unresolved) })}
+ openOpportunityId="perf2_retired"
+ />,
+ );
+ // Named, not silently ignored: the link is shareable and the reader may be
+ // holding it somewhere else.
+ expect(await screen.findByText(/perf2_retired/)).toBeTruthy();
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+});
diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsx
index 08fbe4bf2..b7a66a227 100644
--- a/packages/ui/src/health/biomarker-list.tsx
+++ b/packages/ui/src/health/biomarker-list.tsx
@@ -15,6 +15,7 @@ import {
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";
import { SeverityMark } from "./severity-mark";
+import { ImpactFigure } from "./impact-figure";
/** Severity → dot color, same ramp as every score pill on the surface. */
const SEVERITY_DOT: Record<Severity, string> = {
@@ -288,9 +289,7 @@ function CompactFindingRow({
<span className="shrink-0 text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
{biomarkerLabel(f.biomarker_type)}
</span>
- <span className="shrink-0 tabular-nums text-[var(--color-error)]">
- −{f.health_impact.toFixed(2)}
- </span>
+ <ImpactFigure impact={f.health_impact} />
</li>
);
}
@@ -340,9 +339,7 @@ function FindingRow({
<DimensionChip dimension={findingDimension(f)} />
</span>
) : null}
- <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">
- −{f.health_impact.toFixed(2)}
- </span>
+ <ImpactFigure impact={f.health_impact} className="ml-auto text-xs" />
</div>
<p className="text-xs text-[var(--color-text-secondary)] truncate font-mono">
{f.file_path}
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index eb85f89b7..c5d632bc8 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -13,6 +13,7 @@ import type {
TestsReachingFile,
} from "@repowise-dev/types/health";
import type { Paginated } from "@repowise-dev/types";
+import type { CodeHealthOverlay } from "./map/types";
import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
/** Subset of the findings list query the shared views need. */
@@ -104,6 +105,11 @@ export interface CodeHealthAdapter {
symbolHref?(symbolId: string): string | undefined;
/** Exact stable-id handoff into the existing structured-plan page. */
refactoringPlanHref?(planId: string, opportunityId: string): string;
+ /**
+ * Where this cause lives on the one map. Optional: a host without a galaxy
+ * offers no link rather than a second map.
+ */
+ mapHref?(opportunityId: string, filePath: string): string;
/** Navigate to an href (host wires this to its router). */
navigate(href: string): void;
@@ -111,9 +117,15 @@ export interface CodeHealthAdapter {
* Render the app's file-detail drawer for the inspected path. Kept as a slot
* so each app supplies its own data fetch + toast wiring; pass `null` for
* `filePath` to render nothing.
+ *
+ * `lens` names the surface the file was opened from, so the drawer can lead
+ * with what the reader was looking at. It is optional in both directions: a
+ * host that ignores it renders exactly what it rendered before, and a caller
+ * that does not know one omits it and gets the default.
*/
renderFileDrawer(args: {
filePath: string | null;
onClose: () => void;
+ lens?: CodeHealthOverlay;
}): ReactNode;
}
diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsx
index c823fc824..6c2646410 100644
--- a/packages/ui/src/health/code-health-map.tsx
+++ b/packages/ui/src/health/code-health-map.tsx
@@ -1,336 +1,118 @@
"use client";
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
-// Aliased: the bare name would shadow the DOM `KeyboardEvent` the Esc handler
-// below is typed against.
-import type { KeyboardEvent as ReactKeyboardEvent } from "react";
-import * as d3 from "d3-hierarchy";
-import { scoreBand, type ScoreBand } from "./tokens";
-import { useCommunityFamilies } from "../shared/use-theme-tokens";
-
-export interface CodeHealthMapFile {
- file_path: string;
- score: number;
- nloc: number;
- module: string | null;
- line_coverage_pct: number | null;
- has_test_file: boolean;
- /** Maintainability pillar score (1–10) — drives the maintainability overlay. */
- maintainability_score?: number | null;
- /** Performance-risk pillar score (1–10) — computed but NOT used to color the
- * performance overlay (it is compressed to [8,10] and reads uniformly green).
- * The performance lens colors by {@link performance_findings} + coverage. */
- performance_score?: number | null;
- /** Open performance-risk findings on this file — drives the performance heat. */
- performance_findings?: number | null;
- /** Whether a perf detector ran on this file's language (has a dialect). `false`
- * → grey "not analyzed"; the pillar is high-precision / low-recall, so green
- * can only mean "a detector ran and surfaced nothing", never "verified fast". */
- performance_analyzed?: boolean | null;
- /** 0–100 churn percentile — drives the churn overlay. */
- churn_percentile?: number | null;
- /** Reclaimable lines on this file — drives the dead-code overlay. */
- dead_code_lines?: number | null;
- /** Open security findings on this file — drives the security overlay. */
- security_findings?: number | null;
-}
-
/**
- * Lens applied to the same field — recolors every file node without re-laying
- * the galaxies. One diagram, switchable overlay (the page spine).
+ * The Code Health galaxy: one field, one geometry, a switchable lens.
+ *
+ * This module is the facade. The layout, the lens encodings, the base node
+ * layer, the pointer overlay, and the key are separate modules under `map/`,
+ * and everything they export is re-exported here so a host's import path never
+ * had to change. What is left in this file is composition: sizing, camera,
+ * selection, keyboard navigation, and which layer sees which prop.
+ *
+ * The geometry is deterministic and lens-independent on purpose. A reader
+ * builds spatial memory of this field, and switching a lens must recolor it
+ * rather than redraw it, or that memory is worth nothing.
*/
-export type CodeHealthOverlay =
- | "health"
- | "maintainability"
- | "performance"
- | "coverage"
- | "churn"
- | "dead-code"
- | "security";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+
+import { useCommunityFamilies } from "../shared/use-theme-tokens";
+import { OVERLAY_ORDER, OVERLAY_SPECS } from "./map/lens";
+import { packGalaxies, rand } from "./map/layout";
+import { FileNodes, PressureRings } from "./map/node-layer";
+import { HoverCard, NodeHighlight, SearchMatches } from "./map/overlay";
+import { MapLegendRows, MapLensSwitcher } from "./map/legend";
+import type { CodeHealthMapFile, CodeHealthOverlay, FileNode, MapScope } from "./map/types";
+
+export type {
+ CodeHealthMapFile,
+ CodeHealthOverlay,
+ FileNode,
+ Galaxy,
+ GalaxyAgg,
+ MapScope,
+ PerformanceActionability,
+} from "./map/types";
+export {
+ ABSENT_FILL,
+ NEUTRAL_FILL,
+ OVERLAY_ORDER,
+ OVERLAY_SPECS,
+ PERFORMANCE_STATE_LABEL,
+ burdenBand,
+ performanceBurden,
+ performanceFill,
+ performanceOpacity,
+ performanceSentence,
+ pressureRing,
+} from "./map/lens";
+export type {
+ LegendRow,
+ OverlaySpec,
+ PerformanceBurden,
+ PerformanceBurdenUnit,
+ PerformanceNodeState,
+ PressureRing,
+} from "./map/lens";
+export { groupByModule, moduleColorId, packGalaxies } from "./map/layout";
+export { MapLegend, MapLensSwitcher } from "./map/legend";
+export { SEARCH_MARK_CAP } from "./map/overlay";
+export { FIELD_LIST_CAP, MapFieldList, MapInspector } from "./map/inspector";
export interface CodeHealthMapProps {
files: CodeHealthMapFile[];
- /** Highlight ring on this file. */
+ /** Selection ring on this file. Owned by the host so a link can set it. */
selectedPath?: string | null;
- /** Filename substring — non-matching nodes dim out. */
+ /** Filename substring. Matching nodes take a ring; the field is untouched. */
search?: string;
- /** File click → open the drawer. */
+ /** Extra paths to mark, for a deep link into an opportunity's files. */
+ highlightPaths?: string[];
+ /** File click or keyboard selection. */
onSelectFile?: (path: string) => void;
- /** Hover feeds the details rail. */
+ /** Hover feeds the host's inspector. */
onHoverFile?: (file: CodeHealthMapFile | null) => void;
/** Canvas min height in px. */
minHeight?: number;
/** Which lens recolors the field. Defaults to `health`. */
overlay?: CodeHealthOverlay;
- /** When provided, the lens is switchable. */
+ /** When provided, the lens is switchable from the on-canvas chrome. */
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
/** Lenses offered in the switcher. Defaults to {@link OVERLAY_ORDER}. */
lenses?: CodeHealthOverlay[];
/**
- * The active overlay's per-file signal is still loading. When true the legend
- * shows a "loading…" note instead of its bands, so an all-neutral field reads
- * as "fetching data" rather than "no data".
+ * The active lens's per-file signal is still loading. The key says so, so an
+ * all-neutral field reads as "fetching" rather than as "no data".
*/
overlayLoading?: boolean;
/**
- * Where the lens switcher and legend live.
- *
- * `"canvas"` (default) floats them over the map. `"none"` renders neither, for
- * hosts that lay them out themselves with {@link MapLensSwitcher} /
- * {@link MapLegend} — the section-style Code Health page does this, because
- * three glass panels stacked on the left of the canvas put chrome on top of
- * the one thing the reader came for.
+ * What the server drew and what it left out. Rendered as one sentence over
+ * the canvas, from the same response the field came from.
+ */
+ scope?: MapScope;
+ /**
+ * Where the lens switcher and key live.
*
- * Defaults to `"canvas"` so the VS Code webview, which has no other lens
- * picker, keeps working untouched.
+ * `"canvas"` (default) floats them over the map, for a host with nowhere
+ * else to put them. `"none"` renders neither, for a host that lays them out
+ * around the canvas with {@link MapLensSwitcher} / {@link MapLegend}.
*/
chrome?: "canvas" | "none";
}
-/* Band → SVG fill var(). Same ramp as every score pill on the surface:
- * worst files burn clay/red, healthy ones go green. */
-const BAND_FILL: Record<ScoreBand, string> = {
- critical: "var(--color-error)",
- poor: "var(--color-warning)",
- fair: "var(--color-caution)",
- good: "var(--color-success)",
-};
-
-const BAND_LABEL: { band: ScoreBand; label: string }[] = [
- { band: "critical", label: "Alert" },
- { band: "poor", label: "Warning" },
- { band: "fair", label: "Fair" },
- { band: "good", label: "Healthy" },
-];
-
-/** Neutral fill for nodes a non-health overlay has no signal for. */
-const NEUTRAL_FILL = "var(--color-text-tertiary)";
-
-export interface LegendRow {
- fill: string;
- label: string;
-}
-
-/** Lens metadata: how to fill a node and what the key reads. */
-export interface OverlaySpec {
- label: string;
- /** Caption shown under the legend key. */
- caption: string;
- fill: (f: CodeHealthMapFile) => string;
- legend: LegendRow[];
-}
-
-/** Score band: same ramp as the health lens, grey when the pillar is unscored. */
-function scoreFill(score: number | null | undefined): string {
- if (score == null) return NEUTRAL_FILL;
- return BAND_FILL[scoreBand(score)];
-}
-
-/** Coverage band: green = well covered, red = uncovered, grey = no data. */
-function coverageFill(pct: number | null | undefined): string {
- if (pct == null) return NEUTRAL_FILL;
- if (pct >= 80) return "var(--color-success)";
- if (pct >= 50) return "var(--color-caution)";
- if (pct >= 20) return "var(--color-warning)";
- return "var(--color-error)";
-}
-
-/**
- * Performance lens fill — by findings + coverage state, NOT by the performance
- * score. The score is capped to [9,10] so a score ramp paints the whole map
- * green and hides where the risk actually is. Instead:
- * heat (yellow→red) = open perf findings, so 40 N+1s ≠ 1;
- * green = a detector ran and surfaced nothing (NOT "verified fast");
- * grey = no detector for this language ever ran ("not analyzed").
- * This keeps the pillar's high-precision / low-recall honesty on the map.
- */
-function perfFill(f: CodeHealthMapFile): string {
- const n = f.performance_findings ?? 0;
- if (n > 0) {
- if (n >= 5) return "var(--color-error)";
- if (n >= 2) return "var(--color-warning)";
- return "var(--color-caution)";
- }
- // No findings: green only when a detector actually ran on this language;
- // otherwise grey so an un-analyzed file never reads as "clean".
- return f.performance_analyzed ? "var(--color-success)" : NEUTRAL_FILL;
-}
-
-/** Churn band: red = top-decile churn, green = quiet. */
-function churnFill(pctile: number | null | undefined): string {
- if (pctile == null) return NEUTRAL_FILL;
- if (pctile >= 90) return "var(--color-error)";
- if (pctile >= 70) return "var(--color-warning)";
- if (pctile >= 40) return "var(--color-caution)";
- return "var(--color-success)";
-}
-
-export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
- health: {
- label: "Health",
- caption: "galaxy = module · size = lines of code",
- fill: (f) => BAND_FILL[scoreBand(f.score)],
- legend: BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),
- },
- maintainability: {
- label: "Maintainability",
- caption: "color = maintainability score · grey = not measured",
- fill: (f) => scoreFill(f.maintainability_score),
- legend: [
- ...BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),
- { fill: NEUTRAL_FILL, label: "not measured" },
- ],
- },
- performance: {
- label: "Performance",
- caption: "color = findings, not a score · grey = language not analyzed",
- fill: perfFill,
- legend: [
- { fill: "var(--color-error)", label: "5+ findings" },
- { fill: "var(--color-warning)", label: "2–4 findings" },
- { fill: "var(--color-caution)", label: "1 finding" },
- { fill: "var(--color-success)", label: "Analyzed, none found" },
- { fill: NEUTRAL_FILL, label: "Not analyzed" },
- ],
- },
- coverage: {
- label: "Coverage",
- caption: "color = line coverage · grey = no coverage data",
- fill: (f) => coverageFill(f.line_coverage_pct),
- legend: [
- { fill: "var(--color-success)", label: "≥80%" },
- { fill: "var(--color-caution)", label: "50–80%" },
- { fill: "var(--color-warning)", label: "20–50%" },
- { fill: "var(--color-error)", label: "<20%" },
- { fill: NEUTRAL_FILL, label: "no data" },
- ],
- },
- churn: {
- label: "Churn",
- caption: "color = 90-day churn percentile",
- fill: (f) => churnFill(f.churn_percentile),
- legend: [
- { fill: "var(--color-error)", label: "Top 10%" },
- { fill: "var(--color-warning)", label: "Top 30%" },
- { fill: "var(--color-caution)", label: "Top 60%" },
- { fill: "var(--color-success)", label: "Quiet" },
- { fill: NEUTRAL_FILL, label: "no data" },
- ],
- },
- "dead-code": {
- label: "Dead code",
- caption: "red = reclaimable lines · grey = clean",
- fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),
- legend: [
- { fill: "var(--color-error)", label: "Has dead code" },
- { fill: NEUTRAL_FILL, label: "Clean" },
- ],
- },
- security: {
- label: "Security",
- caption: "red = open findings · grey = clean",
- fill: (f) => ((f.security_findings ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),
- legend: [
- { fill: "var(--color-error)", label: "Has findings" },
- { fill: NEUTRAL_FILL, label: "Clean" },
- ],
- },
-};
-
-/**
- * Default lenses offered in the switcher: the three co-equal health signals,
- * all backed by a per-file score that rides on the map payload itself.
- *
- * Churn is deliberately not in the default. It colors by `churn_percentile`,
- * which arrives on a separate request the host has to join in, so offering it
- * where nobody joined it paints an all-neutral field that reads as "no churn"
- * rather than "no data". Hosts that do the join pass their own `lenses`.
- */
-export const OVERLAY_ORDER: CodeHealthOverlay[] = [
- "health",
- "maintainability",
- "performance",
-];
-
-const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad
-
-/** One module = one galaxy: its files plus size aggregates. */
-export interface GalaxyAgg {
- module: string;
- files: CodeHealthMapFile[]; // NLOC-desc
- totalNloc: number;
- maxNloc: number;
-}
-
-/**
- * Group flat file rows into per-module galaxies, dropping zero-NLOC files
- * (they can't be sized). Files come back sorted biggest-first. Pure + exported
- * for unit testing.
- */
-export function groupByModule(files: CodeHealthMapFile[]): GalaxyAgg[] {
- const byModule = new Map<string, CodeHealthMapFile[]>();
- for (const f of files) {
- if (f.nloc <= 0) continue;
- const key = f.module ?? "(ungrouped)";
- const arr = byModule.get(key);
- if (arr) arr.push(f);
- else byModule.set(key, [f]);
- }
- const out: GalaxyAgg[] = [];
- for (const [module, group] of byModule) {
- group.sort((a, b) => b.nloc - a.nloc);
- out.push({
- module,
- files: group,
- totalNloc: group.reduce((s, f) => s + f.nloc, 0),
- maxNloc: group[0]?.nloc ?? 1,
- });
- }
- // Biggest galaxies first → stable z-order (small ones paint on top).
- out.sort((a, b) => b.totalNloc - a.totalNloc);
- return out;
-}
-
-interface FileNode {
- file: CodeHealthMapFile;
- x: number;
- y: number;
- r: number;
-}
-
-interface Galaxy {
- module: string;
- cx: number;
- cy: number;
- R: number;
- fileCount: number;
- colorId: number;
- nodes: FileNode[];
-}
-
-/** Stable, well-spread hash so a module maps to a consistent palette family. */
-function moduleColorId(module: string): number {
- let h = 0;
- for (let i = 0; i < module.length; i++) h = (h * 31 + module.charCodeAt(i)) | 0;
- return Math.abs(h);
-}
-
-/** Deterministic pseudo-random in [0,1) — for the static starfield. */
-function rand(i: number): number {
- const x = Math.sin(i * 127.1) * 43758.5453;
- return x - Math.floor(x);
-}
-
/** Label a galaxy once its on-screen footprint clears this radius (px). */
const LABEL_MIN_SCREEN_R = 40;
/** Spokes drawn from each hub to its N biggest files (overview / focused). */
const SPOKES_OVERVIEW = 8;
const SPOKES_FOCUSED = 36;
+type KeyboardLevel = "module" | "file";
+
export function CodeHealthMap({
files,
selectedPath,
search,
+ highlightPaths,
onSelectFile,
onHoverFile,
minHeight = 640,
@@ -338,24 +120,38 @@ export function CodeHealthMap({
onOverlayChange,
lenses = OVERLAY_ORDER,
overlayLoading = false,
+ scope,
chrome = "canvas",
}: CodeHealthMapProps) {
const overlaySpec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
const containerRef = useRef<HTMLDivElement>(null);
+ const keyboardRef = useRef<HTMLDivElement>(null);
const [dims, setDims] = useState({ width: 0, height: 0 });
const [focusModule, setFocusModule] = useState<string | null>(null);
const [hovered, setHovered] = useState<CodeHealthMapFile | null>(null);
+ // Keyboard cursor. One tab stop reaches the whole field: arrows move over
+ // modules, Enter descends into one, arrows then move over its files. The
+ // alternative is a tab stop per node, which is thousands of them.
+ const [kbLevel, setKbLevel] = useState<KeyboardLevel>("module");
+ const [kbModule, setKbModule] = useState(0);
+ const [kbFile, setKbFile] = useState(0);
const famFor = useCommunityFamilies();
// Latest callbacks held in refs so the node-layer handlers stay referentially
- // stable across renders (the parent re-renders on every hover to drive the
- // rail). Stable handlers let the memoized <FileNodes> skip re-rendering its
- // ~2,000 circles when only the hover/selection highlight changes.
+ // stable across renders (the host re-renders on every hover to drive its
+ // inspector). Stable handlers let the memoized layers skip reconciling their
+ // thousands of circles when only a highlight changed.
const onSelectRef = useRef(onSelectFile);
onSelectRef.current = onSelectFile;
const onHoverRef = useRef(onHoverFile);
onHoverRef.current = onHoverFile;
- const handleSelect = useCallback((path: string) => onSelectRef.current?.(path), []);
+ const handleSelect = useCallback((path: string) => {
+ // Clicking a node hands focus to the field's keyboard region, so a reader
+ // who reached the map with a pointer can carry on with arrow keys instead
+ // of having to tab back into it.
+ keyboardRef.current?.focus();
+ onSelectRef.current?.(path);
+ }, []);
const handleHoverEnter = useCallback((f: CodeHealthMapFile) => {
setHovered(f);
onHoverRef.current?.(f);
@@ -376,66 +172,35 @@ export function CodeHealthMap({
return () => observer.disconnect();
}, [minHeight]);
- // Esc always exits a focused galaxy — a guaranteed zoom-out.
+ // Escape exits a focused galaxy, while the focus is inside the field. It
+ // used to be bound to the window, which meant dismissing anything else on
+ // the page - the file drawer this map now opens, most of all - also reset
+ // the zoom underneath it.
useEffect(() => {
+ const node = containerRef.current;
+ if (!node) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setFocusModule(null);
};
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
+ node.addEventListener("keydown", onKey);
+ return () => node.removeEventListener("keydown", onKey);
}, []);
const S = Math.max(0, Math.min(dims.width, dims.height));
- // Galaxy placement (d3-pack) + hub-and-spoke file layout (phyllotaxis).
- const { galaxies, byModule } = useMemo(() => {
- if (S === 0 || files.length === 0) {
- return { galaxies: [] as Galaxy[], byModule: new Map<string, Galaxy>() };
- }
- const aggs = groupByModule(files);
- const root = d3
- .hierarchy<{ value?: number; agg?: GalaxyAgg; children?: unknown[] }>(
- { children: aggs.map((a) => ({ value: a.totalNloc, agg: a })) },
- (d) => d.children as { value?: number; agg?: GalaxyAgg }[] | undefined,
- )
- .sum((d) => d.value ?? 0);
- d3.pack<{ value?: number; agg?: GalaxyAgg }>().size([S, S]).padding(S * 0.012)(
- root as d3.HierarchyNode<{ value?: number; agg?: GalaxyAgg }>,
- );
- const galaxies: Galaxy[] = [];
- for (const leaf of root.leaves() as d3.HierarchyCircularNode<{ agg?: GalaxyAgg }>[]) {
- const agg = leaf.data.agg;
- if (!agg) continue;
- const R = leaf.r;
- const cx = leaf.x;
- const cy = leaf.y;
- const n = agg.files.length;
- const spread = R * 0.84;
- const maxNodeR = Math.max(2, R * 0.16);
- const nodes: FileNode[] = agg.files.map((file, i) => {
- const rr = spread * Math.sqrt((i + 0.55) / n);
- const ang = i * GOLDEN_ANGLE;
- const nodeR = Math.max(
- 1.2,
- Math.min(maxNodeR, maxNodeR * Math.sqrt(file.nloc / agg.maxNloc)),
- );
- return { file, x: cx + rr * Math.cos(ang), y: cy + rr * Math.sin(ang), r: nodeR };
- });
- galaxies.push({ module: agg.module, cx, cy, R, fileCount: n, colorId: moduleColorId(agg.module), nodes });
- }
- const byModule = new Map(galaxies.map((g) => [g.module, g]));
- return { galaxies, byModule };
- }, [files, S]);
+ const galaxies = useMemo(() => packGalaxies(files, S), [files, S]);
+
+ const byModule = useMemo(() => new Map(galaxies.map((g) => [g.module, g])), [galaxies]);
- // path → laid-out node, for the highlight overlay to position itself without
- // re-rendering the whole node layer on hover/selection.
+ // path -> laid-out node, so the overlays can position themselves without
+ // re-rendering the base layer on hover, selection, or a keystroke.
const nodeIndex = useMemo(() => {
const m = new Map<string, FileNode>();
for (const g of galaxies) for (const nd of g.nodes) m.set(nd.file.file_path, nd);
return m;
}, [galaxies]);
- // Starfield — static layer, regenerated only on resize.
+ // Starfield: static, regenerated only on resize.
const stars = useMemo(() => {
const { width, height } = dims;
if (width === 0) return [] as { x: number; y: number; r: number }[];
@@ -447,8 +212,67 @@ export function CodeHealthMap({
}));
}, [dims]);
+ const q = (search ?? "").trim().toLowerCase();
+ // Matching runs over the loaded field only and produces a bounded list of
+ // paths for the overlay. Neither the layout nor the base layer sees the
+ // query, so typing repaints the marks and nothing else.
+ const matches = useMemo(() => {
+ if (q.length === 0) return [] as string[];
+ const out: string[] = [];
+ for (const path of nodeIndex.keys()) {
+ if (path.toLowerCase().includes(q)) out.push(path);
+ }
+ return out;
+ }, [q, nodeIndex]);
+
+ const marked = useMemo(() => {
+ if (!highlightPaths?.length) return matches;
+ return [...new Set([...highlightPaths, ...matches])];
+ }, [highlightPaths, matches]);
+
const focusGalaxy = focusModule ? byModule.get(focusModule) ?? null : null;
+ const kbGalaxy = galaxies[Math.min(kbModule, Math.max(0, galaxies.length - 1))] ?? null;
+ const kbNode =
+ kbLevel === "file" && kbGalaxy
+ ? kbGalaxy.nodes[Math.min(kbFile, Math.max(0, kbGalaxy.nodes.length - 1))] ?? null
+ : null;
+
+ const onCanvasKeyDown = useCallback(
+ (e: ReactKeyboardEvent) => {
+ const forward = e.key === "ArrowRight" || e.key === "ArrowDown";
+ const back = e.key === "ArrowLeft" || e.key === "ArrowUp";
+ if (kbLevel === "module") {
+ if (forward || back) {
+ e.preventDefault();
+ setKbModule((i) => {
+ const n = galaxies.length;
+ return n === 0 ? 0 : (i + (forward ? 1 : n - 1)) % n;
+ });
+ } else if (e.key === "Enter" && kbGalaxy) {
+ e.preventDefault();
+ setKbLevel("file");
+ setKbFile(0);
+ setFocusModule(kbGalaxy.module);
+ }
+ return;
+ }
+ if (forward || back) {
+ e.preventDefault();
+ const n = kbGalaxy?.nodes.length ?? 0;
+ setKbFile((i) => (n === 0 ? 0 : (i + (forward ? 1 : n - 1)) % n));
+ } else if (e.key === "Enter" && kbNode) {
+ e.preventDefault();
+ handleSelect(kbNode.file.file_path);
+ } else if (e.key === "Backspace" || e.key === "Escape") {
+ e.preventDefault();
+ setKbLevel("module");
+ setFocusModule(null);
+ }
+ },
+ [kbLevel, kbGalaxy, kbNode, galaxies.length, handleSelect],
+ );
+
const offX = (dims.width - S) / 2;
const offY = (dims.height - S) / 2;
const k = focusGalaxy ? (S * 0.9) / (2 * focusGalaxy.R) : 1;
@@ -458,10 +282,14 @@ export function CodeHealthMap({
const ty = dims.height / 2 - k * (camY + offY);
const toScreen = (x: number, y: number) => ({ x: k * (x + offX) + tx, y: k * (y + offY) + ty });
- const q = (search ?? "").trim().toLowerCase();
-
if (S === 0) {
- return <div ref={containerRef} className="w-full rounded-xl bg-[var(--color-bg-root)]" style={{ minHeight }} />;
+ return (
+ <div
+ ref={containerRef}
+ className="w-full rounded-xl bg-[var(--color-bg-root)]"
+ style={{ minHeight }}
+ />
+ );
}
if (files.length === 0) {
@@ -478,18 +306,41 @@ export function CodeHealthMap({
const labelled = galaxies.filter((g) => focusGalaxy === g || g.R * k >= LABEL_MIN_SCREEN_R);
const spokeCap = focusGalaxy ? SPOKES_FOCUSED : SPOKES_OVERVIEW;
+ const cursorLabel =
+ kbLevel === "file" && kbNode
+ ? `${kbNode.file.file_path}, ${overlaySpec.label} lens`
+ : kbGalaxy
+ ? `${kbGalaxy.module}, ${kbGalaxy.fileCount} files`
+ : "";
return (
<div
ref={containerRef}
- className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)]"
+ className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)] focus-within:ring-2 focus-within:ring-[var(--color-accent-primary)]"
style={{ minHeight }}
>
+ {/* One tab stop for the whole field. Arrows move over modules, Enter
+ descends into one and then moves over its files, Enter again selects
+ it and opens the same inspector a click opens. A tab stop per node
+ would be thousands of them, which is not navigation. Pointer events
+ stay off so it never intercepts a click meant for the canvas. */}
+ <div
+ ref={keyboardRef}
+ tabIndex={0}
+ role="group"
+ aria-label={`Code health map, ${overlaySpec.label} lens. Arrow keys move between modules, Enter opens one.`}
+ onKeyDown={onCanvasKeyDown}
+ className="pointer-events-none absolute inset-0 z-10 outline-none"
+ />
+ <span aria-live="polite" className="sr-only">
+ {cursorLabel}
+ </span>
+
<svg
width={dims.width}
height={dims.height}
role="img"
- aria-label={`Code universe: modules as galaxies, files radiating from each hub, sized by lines of code and colored by ${overlaySpec.label.toLowerCase()}`}
+ aria-label={`Code universe: modules as galaxies, files radiating from each hub, sized by lines of code and marked by ${overlaySpec.label.toLowerCase()}`}
className="block"
>
<defs>
@@ -498,13 +349,11 @@ export function CodeHealthMap({
<stop offset="100%" stopColor="var(--color-bg-root)" />
</radialGradient>
{/* Nebula falloff. This was an feGaussianBlur, which is an offscreen
- raster pass per blob — and the blobs live inside the group whose
- transform animates on every galaxy zoom, so all of them re-rastered
- every frame of a 460ms transition. A gradient is painted directly,
- costs nothing to animate, and the stops below are tuned to match
- the old stdDeviation=7 edge: flat through the middle, soft over the
- last ~15%. `currentColor` resolves per blob, so one def serves
- every galaxy family instead of one gradient each. */}
+ raster pass per blob, and the blobs live inside the group whose
+ transform animates on every galaxy zoom, so all of them
+ re-rastered every frame of the transition. A gradient is painted
+ directly and costs nothing to animate. `currentColor` resolves per
+ blob, so one def serves every galaxy family. */}
<radialGradient id="ch-nebula">
<stop offset="0%" stopColor="currentColor" stopOpacity="1" />
<stop offset="70%" stopColor="currentColor" stopOpacity="1" />
@@ -513,7 +362,7 @@ export function CodeHealthMap({
</radialGradient>
</defs>
- {/* Misty backdrop + starfield (static, clicking it exits a galaxy). */}
+ {/* Misty backdrop + starfield (static; clicking it exits a galaxy). */}
<rect
x={0}
y={0}
@@ -528,7 +377,10 @@ export function CodeHealthMap({
))}
</g>
- <g style={{ transition: "transform 460ms cubic-bezier(0.4,0,0.2,1)" }} transform={`translate(${tx},${ty}) scale(${k})`}>
+ <g
+ style={{ transition: "transform 460ms cubic-bezier(0.4,0,0.2,1)" }}
+ transform={`translate(${tx},${ty}) scale(${k})`}
+ >
{/* Nebula blobs (back layer) */}
{galaxies.map((g) => {
const fam = famFor(g.colorId);
@@ -541,7 +393,6 @@ export function CodeHealthMap({
// Was 0.96 with a blur that spread past the edge; the gradient
// stops inside its own radius, so the blob grows to compensate.
r={g.R * 1.02}
- // `color` feeds the gradient's currentColor stops.
style={{ color: fam.hub }}
fill="url(#ch-nebula)"
fillOpacity={faded ? 0.05 : 0.16}
@@ -555,11 +406,10 @@ export function CodeHealthMap({
);
})}
- {/* Spokes — hub to its biggest files */}
+ {/* Spokes: hub to its biggest files */}
{galaxies.map((g) => {
const fam = famFor(g.colorId);
- const faded = focusGalaxy != null && focusGalaxy !== g;
- if (faded) return null;
+ if (focusGalaxy != null && focusGalaxy !== g) return null;
return (
<g key={`spokes-${g.module}`} stroke={fam.hub} strokeOpacity={0.28}>
{g.nodes.slice(0, spokeCap).map((nd) => (
@@ -569,22 +419,18 @@ export function CodeHealthMap({
y1={g.cy + offY}
x2={nd.x + offX}
y2={nd.y + offY}
- strokeWidth={0.6}
- vectorEffect="non-scaling-stroke"
+ strokeWidth={0.6 / k}
/>
))}
</g>
);
})}
- {/* File nodes — memoized base layer (~2,000 circles). Hover and
- selection are drawn by the cheap highlight layer below, so moving
- the mouse never re-renders this layer. */}
<FileNodes
galaxies={galaxies}
focusModuleKey={focusGalaxy?.module ?? null}
fill={overlaySpec.fill}
- q={q}
+ fillOpacity={overlaySpec.fillOpacity}
offX={offX}
offY={offY}
strokeWidth={0.5 / k}
@@ -594,9 +440,18 @@ export function CodeHealthMap({
onHoverLeave={handleHoverLeave}
/>
- {/* Highlight overlay — the hovered (enlarged, opaque) and selected
- (ring) nodes only, drawn on top. Re-renders on hover/select; the
- base node layer above stays untouched. */}
+ {overlay === "performance" ? (
+ <PressureRings
+ galaxies={galaxies}
+ focusModuleKey={focusGalaxy?.module ?? null}
+ offX={offX}
+ offY={offY}
+ scale={k}
+ />
+ ) : null}
+
+ <SearchMatches paths={marked} nodeIndex={nodeIndex} offX={offX} offY={offY} />
+
<NodeHighlight
hovered={hovered}
selectedPath={selectedPath ?? null}
@@ -606,6 +461,22 @@ export function CodeHealthMap({
fill={overlaySpec.fill}
/>
+ {/* Keyboard cursor, drawn like a focus ring so the one tab stop has
+ a visible position on the field. */}
+ {kbNode ? (
+ <circle
+ data-keyboard-cursor={kbNode.file.file_path}
+ cx={kbNode.x + offX}
+ cy={kbNode.y + offY}
+ r={kbNode.r + 3.5}
+ fill="none"
+ stroke="var(--color-accent-primary)"
+ strokeWidth={2 / k}
+ strokeDasharray={`${3 / k} ${2 / k}`}
+ className="pointer-events-none"
+ />
+ ) : null}
+
{/* Hub markers */}
{galaxies.map((g) => {
const fam = famFor(g.colorId);
@@ -619,8 +490,7 @@ export function CodeHealthMap({
fill={fam.hub}
fillOpacity={faded ? 0.3 : 0.95}
stroke="var(--color-bg-root)"
- strokeWidth={1}
- vectorEffect="non-scaling-stroke"
+ strokeWidth={1 / k}
className="pointer-events-none"
/>
);
@@ -628,63 +498,59 @@ export function CodeHealthMap({
</g>
</svg>
- {/* Editorial galaxy labels — real-px HTML overlay, crisp at any zoom */}
+ {/* Editorial galaxy labels: a real-px HTML overlay, crisp at any zoom. */}
<div className="pointer-events-none absolute inset-0">
{labelled.map((g) => {
const fam = famFor(g.colorId);
- // toScreen already folds in offX/offY — pass the raw pack coords so
- // the label lands on the hub (don't double-add the offset).
+ // toScreen already folds in offX/offY, so pass the raw pack coords.
const p = toScreen(g.cx, g.cy);
if (p.x < -40 || p.x > dims.width + 40 || p.y < 0 || p.y > dims.height) return null;
const big = focusGalaxy === g;
+ const cursor = kbLevel === "module" && kbGalaxy === g;
return (
<span
key={`lbl-${g.module}`}
- // Mono, not serif. These are data-viz labels on a canvas overlay
- // — machine-produced names, which the type rules put in mono;
- // serif is reserved for long-form reading surfaces.
- className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-mono uppercase tracking-[0.12em] text-[var(--color-text-primary)] shadow-sm ring-1 ring-[var(--color-border-default)] backdrop-blur-sm ${
- big ? "text-[11px] font-medium" : "text-[10px]"
- }`}
+ // Mono, not serif. These are data-viz labels on a canvas overlay,
+ // machine-produced names, which the type rules put in mono.
+ className={`absolute -translate-x-1/2 -translate-y-1/2 inline-flex items-center gap-1.5 whitespace-nowrap rounded bg-[var(--color-bg-glass)] px-1.5 py-0.5 font-mono uppercase tracking-[0.12em] text-[var(--color-text-primary)] shadow-sm backdrop-blur-sm ${
+ cursor
+ ? "ring-2 ring-[var(--color-accent-primary)]"
+ : "ring-1 ring-[var(--color-border-default)]"
+ } ${big ? "text-[11px] font-medium" : "text-[10px]"}`}
style={{ left: p.x, top: p.y }}
>
- {/* Galaxy color as a dot — the text itself stays high-contrast so
- purple/plum module hues remain legible in dark mode. */}
- <span className="h-1.5 w-1.5 shrink-0 rounded-full" style={{ backgroundColor: fam.hub }} aria-hidden />
+ {/* Galaxy color as a dot; the text stays high-contrast so plum
+ module hues remain legible in dark mode. */}
+ <span
+ className="h-1.5 w-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: fam.hub }}
+ aria-hidden
+ />
{g.module}
</span>
);
})}
</div>
- {/* Lens switcher + legend, floated over the canvas. Only for hosts that
- have nowhere else to put them (the VS Code webview). The web page
- passes chrome="none" and lays both out around the map instead, so the
- reader is not looking at the field through three glass panels. */}
+ {/* Lens switcher + key, floated over the canvas. Only for a host with
+ nowhere else to put them. A host that lays them out around the map
+ passes chrome="none", so the reader is not looking at the field
+ through a stack of glass panels. */}
{chrome === "canvas" ? (
<>
{onOverlayChange ? (
- <div className="absolute left-3 top-3 flex flex-wrap gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 text-xs shadow-sm backdrop-blur-sm">
- {lenses.map((mode) => (
- <button
- key={mode}
- type="button"
- onClick={() => onOverlayChange(mode)}
- aria-pressed={overlay === mode}
- className={
- overlay === mode
- ? "rounded px-2 py-1 font-medium bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
- : "rounded px-2 py-1 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }
- >
- {OVERLAY_SPECS[mode].label}
- </button>
- ))}
+ <div className="absolute left-3 top-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] p-1 shadow-sm backdrop-blur-sm">
+ <MapLensSwitcher
+ overlay={overlay}
+ onOverlayChange={onOverlayChange}
+ lenses={lenses}
+ className="border-0"
+ />
</div>
) : null}
<div
- className={`absolute left-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${
+ className={`absolute left-3 max-w-[220px] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-3 py-2 text-xs shadow-sm backdrop-blur-sm ${
onOverlayChange ? "top-14" : "top-3"
}`}
>
@@ -701,13 +567,18 @@ export function CodeHealthMap({
</>
) : null}
- {/* Zoom-out breadcrumb — only shown while a galaxy is focused */}
+ {/* Zoom-out breadcrumb, only while a galaxy is focused. */}
{focusGalaxy ? (
<div className="absolute right-3 top-3 flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-xs shadow-sm backdrop-blur-sm">
- <span className="max-w-[180px] truncate font-medium text-[var(--color-text-primary)]">{focusGalaxy.module}</span>
+ <span className="max-w-[180px] truncate font-medium text-[var(--color-text-primary)]">
+ {focusGalaxy.module}
+ </span>
<button
type="button"
- onClick={() => setFocusModule(null)}
+ onClick={() => {
+ setFocusModule(null);
+ setKbLevel("module");
+ }}
className="ml-1 rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
>
← Overview
@@ -715,289 +586,58 @@ export function CodeHealthMap({
</div>
) : null}
- {/* Hover tooltip */}
- {hovered ? <HoverCard file={hovered} /> : null}
- </div>
- );
-}
-
-/**
- * The base file-node layer: every file as a circle, sized + colored by the
- * active lens. Memoized and fed only stable props (laid-out galaxies, a stable
- * fill fn, stable handlers), so a hover — which re-renders the parent — never
- * reconciles these ~2,000 elements. Hover/selection live in {@link NodeHighlight}.
- */
-const FileNodes = memo(function FileNodes({
- galaxies,
- focusModuleKey,
- fill,
- q,
- offX,
- offY,
- strokeWidth,
- interactive,
- onSelect,
- onHoverEnter,
- onHoverLeave,
-}: {
- galaxies: Galaxy[];
- focusModuleKey: string | null;
- fill: (f: CodeHealthMapFile) => string;
- q: string;
- offX: number;
- offY: number;
- /**
- * Stroke in user units, pre-divided by the zoom scale so it lands on 0.5
- * device px at rest.
- *
- * The obvious spelling is `vectorEffect="non-scaling-stroke"`, which is what
- * this used. But Chrome recomputes stroke geometry per element per frame for
- * that attribute, and these are ~2,000 elements inside the group whose
- * transform animates on every galaxy zoom. Dividing by `k` instead is free.
- * The trade is that during the 460ms transition the browser interpolates the
- * transform while this value is already at its destination, so strokes are
- * fractionally off mid-flight — invisible on a 0.5px line under a moving
- * field, and the field is correct the instant it settles.
- */
- strokeWidth: number;
- interactive: boolean;
- onSelect: (path: string) => void;
- onHoverEnter: (f: CodeHealthMapFile) => void;
- onHoverLeave: (f: CodeHealthMapFile) => void;
-}) {
- return (
- <>
- {galaxies.map((g) => {
- const faded = focusModuleKey != null && g.module !== focusModuleKey;
- return (
- <g key={`nodes-${g.module}`}>
- {g.nodes.map((nd) => {
- const f = nd.file;
- const dim = q.length > 0 && !f.file_path.toLowerCase().includes(q);
- return (
- /* No <title> child. It was ~2,000 extra DOM nodes driving a
- native tooltip that appears on its own delay, in the corner
- the pointer is in, restating what HoverCard already shows
- the moment you touch a node — two tooltips racing. `data-path`
- costs no node and gives tests a stable handle. */
- <circle
- key={f.file_path}
- data-path={f.file_path}
- cx={nd.x + offX}
- cy={nd.y + offY}
- r={nd.r}
- fill={fill(f)}
- fillOpacity={faded ? 0.18 : dim ? 0.12 : 0.9}
- stroke="var(--color-bg-root)"
- strokeWidth={strokeWidth}
- className={interactive ? "cursor-pointer" : undefined}
- onMouseEnter={() => onHoverEnter(f)}
- onMouseLeave={() => onHoverLeave(f)}
- onClick={(e) => {
- e.stopPropagation();
- onSelect(f.file_path);
- }}
- />
- );
- })}
- </g>
- );
- })}
- </>
- );
-});
-
-/** The hovered + selected nodes only, drawn on top of the static node layer so
- * pointer movement repaints two circles instead of the whole field. */
-function NodeHighlight({
- hovered,
- selectedPath,
- nodeIndex,
- offX,
- offY,
- fill,
-}: {
- hovered: CodeHealthMapFile | null;
- selectedPath: string | null;
- nodeIndex: Map<string, FileNode>;
- offX: number;
- offY: number;
- fill: (f: CodeHealthMapFile) => string;
-}) {
- const sel = selectedPath ? nodeIndex.get(selectedPath) : null;
- const hov = hovered ? nodeIndex.get(hovered.file_path) : null;
- return (
- <g className="pointer-events-none">
- {sel ? (
- <circle
- cx={sel.x + offX}
- cy={sel.y + offY}
- r={sel.r}
- fill={fill(sel.file)}
- fillOpacity={1}
- stroke="var(--color-text-primary)"
- strokeWidth={2}
- vectorEffect="non-scaling-stroke"
- />
- ) : null}
- {hov && hov !== sel ? (
- <circle
- cx={hov.x + offX}
- cy={hov.y + offY}
- r={hov.r + 1.5}
- fill={fill(hov.file)}
- fillOpacity={1}
- stroke="var(--color-bg-root)"
- strokeWidth={0.5}
- vectorEffect="non-scaling-stroke"
- />
- ) : null}
- </g>
- );
-}
-
-function HoverCard({ file }: { file: CodeHealthMapFile }) {
- const cov = file.line_coverage_pct;
- return (
- <div className="pointer-events-none absolute bottom-3 left-3 max-w-[75%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs shadow-md">
- <div className="truncate font-mono text-[var(--color-text-primary)]">{file.file_path}</div>
- <div className="text-[var(--color-text-tertiary)]">
- score {file.score.toFixed(1)} · {file.nloc.toLocaleString()} NLOC
- {cov != null ? ` · ${Math.round(cov)}% cov` : ""}
- {file.has_test_file ? "" : " · untested"}
- </div>
- </div>
- );
-}
-
-/* ------------------------------------------------------------------ *
- * Map chrome
- *
- * The switcher and the key, as components a host can place around the map
- * rather than on top of it. Both read the same {@link OVERLAY_SPECS} the
- * canvas does, so an off-canvas legend can never drift from the fills it is
- * describing.
- * ------------------------------------------------------------------ */
-
-/** The legend's colour rows, shared by both placements. */
-function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: boolean }) {
- if (loading) {
- return (
- <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
- <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
- loading {spec.label.toLowerCase()}…
- </div>
- );
- }
- return (
- <div className="flex flex-col gap-1">
- {spec.legend.map((row) => (
- <span key={row.label} className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
- <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: row.fill }} />
- {row.label}
- </span>
- ))}
- </div>
- );
-}
-
-/**
- * The lens switcher as a real segmented control, for `chrome="none"` hosts.
- *
- * A radiogroup rather than a row of `aria-pressed` buttons: picking a lens is
- * one choice out of a set, and the roving-tabindex arrow-key behaviour comes
- * free with the role.
- */
-export function MapLensSwitcher({
- overlay,
- onOverlayChange,
- lenses = OVERLAY_ORDER,
- className,
-}: {
- overlay: CodeHealthOverlay;
- onOverlayChange: (overlay: CodeHealthOverlay) => void;
- lenses?: CodeHealthOverlay[];
- className?: string;
-}) {
- const onKeyDown = (e: ReactKeyboardEvent) => {
- const i = lenses.indexOf(overlay);
- if (i < 0) return;
- let next = i;
- if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % lenses.length;
- else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
- next = (i - 1 + lenses.length) % lenses.length;
- else return;
- e.preventDefault();
- const target = lenses[next];
- if (target) onOverlayChange(target);
- };
+ {scope ? <MapScopeNote scope={scope} matches={matches.length} query={q} /> : null}
- return (
- <div
- role="radiogroup"
- aria-label="Map lens"
- onKeyDown={onKeyDown}
- className={`inline-flex rounded-md border border-[var(--color-border-default)] p-0.5 ${className ?? ""}`}
- >
- {lenses.map((mode) => {
- const active = overlay === mode;
- return (
- <button
- key={mode}
- type="button"
- role="radio"
- aria-checked={active}
- tabIndex={active ? 0 : -1}
- onClick={() => onOverlayChange(mode)}
- className={`rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
- active
- ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
- : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- {OVERLAY_SPECS[mode].label}
- </button>
- );
- })}
+ {hovered ? <HoverCard file={hovered} overlay={overlay} /> : null}
</div>
);
}
/**
- * The active lens's key, laid out as a horizontal strip to sit under the map.
+ * What this field is, in one sentence, from the response that drew it.
*
- * Same content as the on-canvas panel, arranged to read as a caption rather
- * than as a floating card: the swatches run inline and the lens caption closes
- * the line.
+ * A count and the visual it describes have to come from one source, so this
+ * reads the server's own selection totals rather than the array length: a
+ * caption saying "3,808 files" over a two-thousand node field is a claim the
+ * reader has no way to check.
*/
-export function MapLegend({
- overlay,
- loading = false,
- className,
+function MapScopeNote({
+ scope,
+ matches,
+ query,
}: {
- overlay: CodeHealthOverlay;
- loading?: boolean;
- className?: string;
+ scope: MapScope;
+ matches: number;
+ query: string;
}) {
- const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ const capped = scope.shown < scope.eligible;
+ const hiddenCauses = scope.omitted.performanceFiles;
return (
<div
- className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-[var(--color-text-tertiary)] ${className ?? ""}`}
+ data-testid="map-scope"
+ className="pointer-events-none absolute bottom-3 right-3 max-w-[64%] rounded-md sm:max-w-[52%] border border-[var(--color-border-default)] bg-[var(--color-bg-glass)] px-2.5 py-1.5 text-right text-[11px] text-[var(--color-text-tertiary)] shadow-sm backdrop-blur-sm"
>
- {loading ? (
- <span className="flex items-center gap-1.5">
- <span className="h-2 w-2 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
- loading {spec.label.toLowerCase()}…
- </span>
- ) : (
- spec.legend.map((row) => (
- <span key={row.label} className="flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full" style={{ backgroundColor: row.fill }} />
- {row.label}
- </span>
- ))
- )}
- <span className="font-mono text-[10px] uppercase tracking-[0.12em]">{spec.caption}</span>
+ <span className="font-mono tabular-nums">
+ {scope.shown.toLocaleString()} of {scope.eligible.toLocaleString()}
+ </span>{" "}
+ files drawn
+ {capped ? (
+ <>
+ {" · "}
+ {hiddenCauses == null
+ ? `${scope.omitted.files.toLocaleString()} not drawn`
+ : hiddenCauses > 0
+ ? `${hiddenCauses.toLocaleString()} file${hiddenCauses === 1 ? "" : "s"} with open causes not drawn`
+ : "every file with an open cause is drawn"}
+ </>
+ ) : null}
+ {query ? (
+ <>
+ {" · "}
+ <span className="tabular-nums">{matches.toLocaleString()}</span>
+ {` match${matches === 1 ? "" : "es"} here`}
+ </>
+ ) : null}
</div>
);
}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 2c6cc3036..3aaff5c32 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -30,8 +30,13 @@ import {
// Shared band function, never a local threshold: two surfaces disagreeing
// about where "Good" starts is worse than the import.
import { healthBand } from "../overview/health-lede";
-import type { FileHealthTrend, FileSignals } from "@repowise-dev/types/health";
+import type {
+ FileHealthTrend,
+ FileSignals,
+ PerformanceOpportunity,
+} from "@repowise-dev/types/health";
import { SeverityMark } from "./severity-mark";
+import { ImpactFigure } from "./impact-figure";
export interface HealthDrawerFinding {
id: string;
@@ -96,6 +101,21 @@ export interface HealthFileDrawerProps {
onFindingStatusChange?:
| ((findingId: string, status: string) => Promise<void> | void)
| undefined;
+ /**
+ * The surface this file was opened from. In `performance` the drawer leads
+ * with the file's causes rather than with its defect score, because that is
+ * what the reader was looking at. Anything else renders as before.
+ */
+ lens?: string;
+ /**
+ * The file's open performance causes, when the host fetched them. `null` is
+ * "the host did not ask", which the section says rather than drawing an
+ * empty list that reads as a clear file.
+ */
+ performance?: { items: PerformanceOpportunity[]; total: number } | null;
+ performanceLoading?: boolean;
+ /** Open one cause on the performance surface. */
+ onOpportunitySelect?: ((opportunityId: string) => void) | undefined;
}
/** Bucket for one-off file-level markers, kept pooled so a file with several
@@ -126,6 +146,10 @@ export function HealthFileDrawer({
onPartnerSelect,
onPartnerHref,
onFindingStatusChange,
+ lens,
+ performance,
+ performanceLoading = false,
+ onOpportunitySelect,
}: HealthFileDrawerProps) {
const [statusOverride, setStatusOverride] = useState<Record<string, string>>({});
const [savingId, setSavingId] = useState<string | null>(null);
@@ -212,7 +236,7 @@ export function HealthFileDrawer({
</span>
);
})() : null}
- <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">−{f.health_impact.toFixed(2)}</span>
+ <ImpactFigure impact={f.health_impact} className="ml-auto text-xs" />
</div>
<p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
<BiomarkerDetails
@@ -455,6 +479,14 @@ export function HealthFileDrawer({
{/* The other two pillars and the structural counters, as a
hairline list. Ten bordered tiles made a 3.1 and a 14 read as
the same kind of news. */}
+ {lens === "performance" ? (
+ <PerformanceCauses
+ page={performance ?? null}
+ loading={performanceLoading}
+ onSelect={onOpportunitySelect}
+ />
+ ) : null}
+
<MetricGrid metric={metric} />
<FileSignalsPanel signals={signals} />
@@ -633,7 +665,7 @@ function FunctionFindingsGroup({
<span className="text-[var(--color-text-tertiary)]">
{findings.length} {findings.length === 1 ? "marker" : "markers"}
</span>
- <span className="text-[var(--color-error)]">−{total.toFixed(2)}</span>
+ <ImpactFigure impact={total} />
{/* Why 34 markers cost half a point. Without this the count reads as
the severity and the capped total looks like a bug. The
explanation rides in the accessible name, not a `title`: a bare
@@ -783,3 +815,132 @@ function PlainValue({ children }: { children: React.ReactNode }) {
<span className="text-sm tabular-nums text-[var(--color-text-primary)]">{children}</span>
);
}
+
+/**
+ * The file's open performance causes, when the reader arrived from that lens.
+ *
+ * Counts and causes, not a score: the performance pillar compresses into a
+ * narrow band and a number from it says nothing about this file.
+ *
+ * A cause is titled by the shape the detector recognized and identified by
+ * where it fires, because on one file that is what tells two of them apart:
+ * this repository has files carrying thirty-six causes of a single marker, and
+ * titling them by the marker alone produces thirty-six identical rows. The
+ * whole section says plainly when the host never asked for the data, because
+ * an empty list would read as a clear file.
+ */
+function PerformanceCauses({
+ page,
+ loading,
+ onSelect,
+}: {
+ page: { items: PerformanceOpportunity[]; total: number } | null;
+ loading: boolean;
+ onSelect?: ((opportunityId: string) => void) | undefined;
+}) {
+ const items = page?.items ?? [];
+ const withPlan = items.filter((o) => o.plan_id).length;
+ return (
+ <section className="flex flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Performance causes
+ </h3>
+ {loading ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading causes…</p>
+ ) : page === null ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ This view has no performance data wired up, so nothing is claimed about this
+ file either way.
+ </p>
+ ) : items.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No open cause names this file as the place to intervene. The detectors are
+ high precision and low recall, so that is not a measurement that it is fast.
+ </p>
+ ) : (
+ <>
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ <span className="tabular-nums">{page.total.toLocaleString()}</span> open cause
+ {page.total === 1 ? "" : "s"} name this file as the place to intervene
+ {items.length < page.total ? (
+ <>
+ , <span className="tabular-nums">{items.length}</span> shown
+ </>
+ ) : null}
+ . <span className="tabular-nums">{withPlan}</span> of those carry a stored plan.
+ </p>
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
+ {items.map((o) => (
+ <CauseRow key={o.opportunity_id} opportunity={o} onSelect={onSelect} />
+ ))}
+ </ul>
+ </>
+ )}
+ </section>
+ );
+}
+
+/** Where a cause fires, from the evidence the queue already carries. */
+function causeLocation(o: PerformanceOpportunity): string | null {
+ if (o.terminal_sink) return o.terminal_sink;
+ if (o.intervention_symbol) return o.intervention_symbol;
+ const first = o.evidence[0];
+ if (!first) return null;
+ const name = first.function_name ?? null;
+ if (name && first.line_start != null) return `${name}:${first.line_start}`;
+ if (name) return name;
+ return first.line_start != null ? `line ${first.line_start}` : null;
+}
+
+function CauseRow({
+ opportunity: o,
+ onSelect,
+}: {
+ opportunity: PerformanceOpportunity;
+ onSelect?: ((opportunityId: string) => void) | undefined;
+}) {
+ const location = causeLocation(o);
+ const body = (
+ <>
+ <span className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 text-xs font-medium text-[var(--color-text-primary)]">
+ {biomarkerLabel(o.biomarker_type)}
+ </span>
+ <span className="shrink-0 font-mono text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {ACTIONABILITY_WORD[o.actionability_state] ?? o.actionability_state}
+ </span>
+ </span>
+ {location ? (
+ <span className="truncate font-mono text-[10px] text-[var(--color-text-secondary)]">
+ {location}
+ </span>
+ ) : null}
+ <span className="text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {o.observations_total} observation{o.observations_total === 1 ? "" : "s"} ·{" "}
+ {o.affected_files_total} file{o.affected_files_total === 1 ? "" : "s"} ·{" "}
+ {o.plan_id ? "stored plan" : o.plan_reason}
+ </span>
+ </>
+ );
+ return (
+ <li>
+ {onSelect ? (
+ <button
+ type="button"
+ onClick={() => onSelect(o.opportunity_id)}
+ className="flex w-full flex-col gap-0.5 px-1 py-2 text-left transition-colors hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {body}
+ </button>
+ ) : (
+ <div className="flex flex-col gap-0.5 px-1 py-2">{body}</div>
+ )}
+ </li>
+ );
+}
+
+const ACTIONABILITY_WORD: Record<string, string> = {
+ plan_ready: "Plan ready",
+ advisory: "Advisory",
+ investigate: "Investigate",
+};
diff --git a/packages/ui/src/health/impact-figure.tsx b/packages/ui/src/health/impact-figure.tsx
new file mode 100644
index 000000000..59d761948
--- /dev/null
+++ b/packages/ui/src/health/impact-figure.tsx
@@ -0,0 +1,34 @@
+import { cn } from "../lib/cn";
+import { formatHealthImpact } from "./tokens";
+
+/**
+ * A finding's deduction, or the word for not having one.
+ *
+ * One owner for the figure, because the alternative is every surface deciding
+ * for itself what a zero means. Performance findings carry an impact of zero
+ * by construction, and the defect formatter rendered that as "−0.00" in red:
+ * a measured deduction that rounded away, on a marker that never scored one.
+ * A marker with no deduction says so in a word, in the neutral colour, because
+ * the red is the deduction's colour and there is no deduction.
+ */
+export function ImpactFigure({
+ impact,
+ className,
+}: {
+ impact: number | null | undefined;
+ className?: string;
+}) {
+ const figure = formatHealthImpact(impact);
+ if (figure === null) {
+ return (
+ <span className={cn("shrink-0 text-[var(--color-text-tertiary)]", className)}>
+ not scored
+ </span>
+ );
+ }
+ return (
+ <span className={cn("shrink-0 tabular-nums text-[var(--color-error)]", className)}>
+ {figure}
+ </span>
+ );
+}
diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsx
new file mode 100644
index 000000000..616237fc2
--- /dev/null
+++ b/packages/ui/src/health/map/inspector.tsx
@@ -0,0 +1,291 @@
+"use client";
+
+/**
+ * The two things beside the canvas: what is selected, and how to reach the
+ * rest of the field without a pointer.
+ *
+ * The rail used to hold the repository's top findings permanently, which made
+ * it a second findings list rather than an inspector: it never described the
+ * object under the cursor, and it never changed when the lens did. An
+ * inspector explains a selection, so it renders when there is one; the ranked
+ * list is what fills the space otherwise, and it is also the field's keyboard
+ * and screen-reader route into itself.
+ */
+
+import { useMemo } from "react";
+import { cn } from "../../lib/cn";
+import { scoreBadgeClass } from "../tokens";
+import {
+ PERFORMANCE_STATE_LABEL,
+ burdenBand,
+ performanceBurden,
+ performanceSentence,
+} from "./lens";
+import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./types";
+
+/** The ring's colour per band, so the inspector's mark matches the canvas. */
+const RING_TONE: Record<0 | 1 | 2 | 3, string> = {
+ 0: "var(--color-border-default)",
+ 1: "var(--color-caution)",
+ 2: "var(--color-warning)",
+ 3: "var(--color-error)",
+};
+
+/** Rows the ranked list draws. Past this it is an inventory, not a lead. */
+export const FIELD_LIST_CAP = 50;
+
+/**
+ * What the list can say about causes it is not showing.
+ *
+ * Three answers, and a missing scope is the third one. A host that wires no
+ * scope knows nothing about the field beyond it, and printing nothing there
+ * would read as "there is nothing beyond it".
+ */
+function causesOutside(scope: MapScope | undefined): string {
+ const omitted = scope?.omitted.performanceFiles;
+ if (scope === undefined || omitted === null || omitted === undefined) {
+ return ". Whether more carry causes outside the drawn field is not reported here.";
+ }
+ if (omitted === 0) return ". Every file with an open cause is drawn.";
+ return `. ${omitted.toLocaleString()} more carry causes outside the drawn field.`;
+}
+
+/** Worst-first for the active lens, so the list ranks what the field marks. */
+function rankFiles(
+ files: CodeHealthMapFile[],
+ overlay: CodeHealthOverlay,
+): CodeHealthMapFile[] {
+ if (overlay === "performance") {
+ return files
+ .filter((f) => performanceBurden(f).count > 0)
+ .sort((a, b) => {
+ const ar = a.performance_rank ?? Number.MAX_SAFE_INTEGER;
+ const br = b.performance_rank ?? Number.MAX_SAFE_INTEGER;
+ if (ar !== br) return ar - br;
+ const ac = performanceBurden(a).count;
+ const bc = performanceBurden(b).count;
+ if (ac !== bc) return bc - ac;
+ return a.file_path.localeCompare(b.file_path);
+ });
+ }
+ return [...files].sort((a, b) => a.score - b.score || a.file_path.localeCompare(b.file_path));
+}
+
+const LIST_HEADING: Record<string, string> = {
+ performance: "Files by performance pressure",
+ maintainability: "Files by maintainability",
+ health: "Files by health",
+};
+
+/**
+ * A bounded ranked list of the drawn files, in the active lens's order.
+ *
+ * This is the canvas's navigable alternative: every row is a real button, so
+ * a keyboard and a screen reader reach the same objects a pointer does and
+ * open the same inspector, without turning the field itself into thousands of
+ * tab stops. It states its own truncation, because a list that silently stops
+ * at fifty reads as a repository with fifty problems.
+ */
+export function MapFieldList({
+ files,
+ overlay,
+ selectedPath,
+ onSelectFile,
+ scope,
+}: {
+ files: CodeHealthMapFile[];
+ overlay: CodeHealthOverlay;
+ selectedPath?: string | null;
+ onSelectFile: (path: string) => void;
+ scope?: MapScope;
+}) {
+ const ranked = useMemo(() => rankFiles(files, overlay), [files, overlay]);
+ const rows = ranked.slice(0, FIELD_LIST_CAP);
+ const heading = LIST_HEADING[overlay] ?? "Files in this field";
+
+ if (rows.length === 0) {
+ return (
+ <div className="text-xs text-[var(--color-text-tertiary)]">
+ {overlay === "performance"
+ ? "No file in the drawn field carries an open performance cause."
+ : "Nothing to rank in the drawn field yet."}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-0 flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {heading}
+ </h3>
+ <ul className="flex min-h-0 flex-col divide-y divide-[var(--color-border-default)] overflow-y-auto">
+ {rows.map((f) => {
+ const selected = f.file_path === selectedPath;
+ const name = f.file_path.split("/").pop() ?? f.file_path;
+ return (
+ <li key={f.file_path}>
+ <button
+ type="button"
+ onClick={() => onSelectFile(f.file_path)}
+ aria-current={selected ? "true" : undefined}
+ className={cn(
+ "flex w-full flex-col gap-0.5 px-1.5 py-2 text-left transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",
+ selected
+ ? "bg-[var(--color-accent-muted)]"
+ : "hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ <span className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 truncate text-xs font-medium text-[var(--color-text-primary)]">
+ {name}
+ </span>
+ {overlay === "performance" ? (
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-secondary)]">
+ {performanceBurden(f).count}
+ </span>
+ ) : (
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-secondary)]">
+ {f.score.toFixed(1)}
+ </span>
+ )}
+ </span>
+ <span className="truncate font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {f.file_path}
+ </span>
+ {overlay === "performance" ? (
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">
+ {performanceSentence(f)}
+ </span>
+ ) : null}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="tabular-nums">{rows.length}</span> of{" "}
+ <span className="tabular-nums">{ranked.length.toLocaleString()}</span>{" "}
+ {overlay === "performance" ? "files with an open cause" : "drawn files"} listed
+ {overlay === "performance" ? causesOutside(scope) : "."}
+ </p>
+ </div>
+ );
+}
+
+/**
+ * The selected file, described by the active lens.
+ *
+ * Hover is pointer-bound decoding on the canvas; this opens for a click or a
+ * keyboard selection and stays until it is dismissed, which is the difference
+ * between reading a node and inspecting one.
+ */
+export function MapInspector({
+ file,
+ overlay,
+ onOpen,
+ onClose,
+}: {
+ file: CodeHealthMapFile;
+ overlay: CodeHealthOverlay;
+ onOpen: (path: string) => void;
+ onClose: () => void;
+}) {
+ const name = file.file_path.split("/").pop() ?? file.file_path;
+ const burden = performanceBurden(file);
+ return (
+ <section
+ aria-label={`Inspecting ${file.file_path}`}
+ className="flex flex-col gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"
+ >
+ <div className="flex items-center gap-2">
+ {/* The lens decides what leads. Under performance the defect score is
+ not the subject, and putting its coloured badge first told the
+ reader the file was fine while the ring beside it said otherwise. */}
+ {overlay === "performance" ? (
+ <span
+ aria-hidden
+ className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full"
+ style={{
+ border: `2px ${burden.state === "actionable" ? "solid" : "dashed"} ${
+ burden.count > 0 ? RING_TONE[burdenBand(burden.count)] : "var(--color-border-default)"
+ }`,
+ }}
+ />
+ ) : (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center justify-center rounded px-1.5 py-0.5 text-xs font-semibold tabular-nums",
+ scoreBadgeClass(file.score),
+ )}
+ >
+ {file.score.toFixed(1)}
+ </span>
+ )}
+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-[var(--color-text-primary)]">
+ {name}
+ </span>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Clear selection"
+ className="shrink-0 rounded px-1.5 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ ✕
+ </button>
+ </div>
+
+ <div className="truncate font-mono text-xs text-[var(--color-text-tertiary)]">
+ {file.file_path}
+ </div>
+
+ {overlay === "performance" ? (
+ <dl className="flex flex-col gap-1 border-t border-[var(--color-border-default)] pt-2 text-xs">
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-[var(--color-text-tertiary)]">
+ Open {burden.unit}
+ </dt>
+ <dd className="font-mono text-base tabular-nums text-[var(--color-text-primary)]">
+ {burden.count}
+ </dd>
+ </div>
+ {file.performance_observations != null && burden.unit === "opportunities" ? (
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-[var(--color-text-tertiary)]">Observations behind them</dt>
+ <dd className="font-mono tabular-nums text-[var(--color-text-primary)]">
+ {file.performance_observations}
+ </dd>
+ </div>
+ ) : null}
+ <div className="flex items-baseline justify-between gap-3">
+ <dt className="text-[var(--color-text-tertiary)]">State</dt>
+ <dd className="text-right text-[var(--color-text-primary)]">
+ {PERFORMANCE_STATE_LABEL[burden.state]}
+ </dd>
+ </div>
+ </dl>
+ ) : null}
+
+ <div className="flex flex-wrap gap-x-3 gap-y-1 border-t border-[var(--color-border-default)] pt-2 text-xs text-[var(--color-text-secondary)]">
+ {overlay === "performance" ? (
+ // Still available, but as one supporting figure among several rather
+ // than as the headline the lens is not about.
+ <span className="tabular-nums">defect risk {file.score.toFixed(1)}</span>
+ ) : null}
+ <span className="tabular-nums">{file.nloc.toLocaleString()} NLOC</span>
+ {file.line_coverage_pct != null ? (
+ <span className="tabular-nums">{Math.round(file.line_coverage_pct)}% coverage</span>
+ ) : null}
+ <span>{file.has_test_file ? "has tests" : "untested"}</span>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => onOpen(file.file_path)}
+ className="w-full rounded-md border border-[var(--color-border-default)] px-2 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ Open details
+ </button>
+ </section>
+ );
+}
diff --git a/packages/ui/src/health/map/layout.ts b/packages/ui/src/health/map/layout.ts
new file mode 100644
index 000000000..66f597821
--- /dev/null
+++ b/packages/ui/src/health/map/layout.ts
@@ -0,0 +1,103 @@
+/**
+ * Where every node sits, as one pure function of the rows and the canvas size.
+ *
+ * Deterministic on purpose. A reader builds spatial memory of this field, and
+ * that memory is only worth having if the same repository lays out the same
+ * way every time, under every lens. Nothing here reads a lens.
+ */
+
+import * as d3 from "d3-hierarchy";
+import type { CodeHealthMapFile, Galaxy, GalaxyAgg } from "./types";
+
+const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5)); // ~2.39996 rad
+
+/**
+ * Group flat file rows into per-module galaxies, dropping zero-NLOC files
+ * (they cannot be sized). Files come back sorted biggest-first.
+ */
+export function groupByModule(files: CodeHealthMapFile[]): GalaxyAgg[] {
+ const byModule = new Map<string, CodeHealthMapFile[]>();
+ for (const f of files) {
+ if (f.nloc <= 0) continue;
+ const key = f.module ?? "(ungrouped)";
+ const arr = byModule.get(key);
+ if (arr) arr.push(f);
+ else byModule.set(key, [f]);
+ }
+ const out: GalaxyAgg[] = [];
+ for (const [module, group] of byModule) {
+ group.sort((a, b) => b.nloc - a.nloc);
+ out.push({
+ module,
+ files: group,
+ totalNloc: group.reduce((s, f) => s + f.nloc, 0),
+ maxNloc: group[0]?.nloc ?? 1,
+ });
+ }
+ // Biggest galaxies first -> stable z-order (small ones paint on top).
+ out.sort((a, b) => b.totalNloc - a.totalNloc);
+ return out;
+}
+
+/** Stable, well-spread hash so a module maps to a consistent palette family. */
+export function moduleColorId(module: string): number {
+ let h = 0;
+ for (let i = 0; i < module.length; i++) h = (h * 31 + module.charCodeAt(i)) | 0;
+ return Math.abs(h);
+}
+
+/**
+ * Galaxy placement (d3-pack) plus hub-and-spoke file layout (phyllotaxis).
+ *
+ * `S` is the square the field is packed into; the caller centres it in the
+ * container. Returns an empty field for an empty input rather than throwing,
+ * because a host renders before its data lands.
+ */
+export function packGalaxies(files: CodeHealthMapFile[], S: number): Galaxy[] {
+ if (S === 0 || files.length === 0) return [];
+ const aggs = groupByModule(files);
+ const root = d3
+ .hierarchy<{ value?: number; agg?: GalaxyAgg; children?: unknown[] }>(
+ { children: aggs.map((a) => ({ value: a.totalNloc, agg: a })) },
+ (d) => d.children as { value?: number; agg?: GalaxyAgg }[] | undefined,
+ )
+ .sum((d) => d.value ?? 0);
+ d3.pack<{ value?: number; agg?: GalaxyAgg }>().size([S, S]).padding(S * 0.012)(
+ root as d3.HierarchyNode<{ value?: number; agg?: GalaxyAgg }>,
+ );
+ const galaxies: Galaxy[] = [];
+ for (const leaf of root.leaves() as d3.HierarchyCircularNode<{ agg?: GalaxyAgg }>[]) {
+ const agg = leaf.data.agg;
+ if (!agg) continue;
+ const R = leaf.r;
+ const cx = leaf.x;
+ const cy = leaf.y;
+ const n = agg.files.length;
+ const spread = R * 0.84;
+ const maxNodeR = Math.max(2, R * 0.16);
+ galaxies.push({
+ module: agg.module,
+ cx,
+ cy,
+ R,
+ fileCount: n,
+ colorId: moduleColorId(agg.module),
+ nodes: agg.files.map((file, i) => {
+ const rr = spread * Math.sqrt((i + 0.55) / n);
+ const ang = i * GOLDEN_ANGLE;
+ const nodeR = Math.max(
+ 1.2,
+ Math.min(maxNodeR, maxNodeR * Math.sqrt(file.nloc / agg.maxNloc)),
+ );
+ return { file, x: cx + rr * Math.cos(ang), y: cy + rr * Math.sin(ang), r: nodeR };
+ }),
+ });
+ }
+ return galaxies;
+}
+
+/** Deterministic pseudo-random in [0,1) for the static starfield. */
+export function rand(i: number): number {
+ const x = Math.sin(i * 127.1) * 43758.5453;
+ return x - Math.floor(x);
+}
diff --git a/packages/ui/src/health/map/legend.tsx b/packages/ui/src/health/map/legend.tsx
new file mode 100644
index 000000000..10e1d9c1d
--- /dev/null
+++ b/packages/ui/src/health/map/legend.tsx
@@ -0,0 +1,175 @@
+"use client";
+
+/**
+ * The lens switcher and the key, as components a host places around the map
+ * rather than on top of it.
+ *
+ * Both read the same lens specs the canvas does, so an off-canvas key can
+ * never drift from the marks it is describing.
+ */
+
+// Aliased: the bare name would shadow the DOM `KeyboardEvent`.
+import { Fragment } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { OVERLAY_ORDER, OVERLAY_SPECS, type LegendRow, type OverlaySpec } from "./lens";
+import type { CodeHealthOverlay } from "./types";
+
+/** One key swatch: a disc for a fill, an outline for a ring. */
+function Swatch({ row, size }: { row: LegendRow; size: number }) {
+ if (row.mark === "ring") {
+ return (
+ <span
+ aria-hidden
+ className="inline-block shrink-0 rounded-full"
+ style={{
+ width: size,
+ height: size,
+ border: `1.5px ${row.dash ? "dashed" : "solid"} ${row.fill}`,
+ }}
+ />
+ );
+ }
+ return (
+ <span
+ aria-hidden
+ className="inline-block shrink-0 rounded-full"
+ style={{ width: size, height: size, backgroundColor: row.fill }}
+ />
+ );
+}
+
+/** The active lens's key rows, shared by both placements. */
+export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: boolean }) {
+ if (loading) {
+ return (
+ <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
+ <span className="h-2.5 w-2.5 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
+ loading {spec.label.toLowerCase()}…
+ </div>
+ );
+ }
+ return (
+ <div className="flex flex-col gap-1">
+ {spec.legend.map((row, i) => (
+ <Fragment key={row.label}>
+ {row.group && row.group !== spec.legend[i - 1]?.group ? (
+ <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] first:mt-0">
+ {row.group}
+ </span>
+ ) : null}
+ <span className="flex items-center gap-1.5 text-[var(--color-text-tertiary)]">
+ <Swatch row={row} size={10} />
+ {row.label}
+ </span>
+ </Fragment>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * The lens switcher as a real segmented control.
+ *
+ * A radiogroup rather than a row of pressed buttons: picking a lens is one
+ * choice out of a set, and the roving-tabindex arrow-key behaviour comes free
+ * with the role.
+ */
+export function MapLensSwitcher({
+ overlay,
+ onOverlayChange,
+ lenses = OVERLAY_ORDER,
+ className,
+}: {
+ overlay: CodeHealthOverlay;
+ onOverlayChange: (overlay: CodeHealthOverlay) => void;
+ lenses?: CodeHealthOverlay[];
+ className?: string;
+}) {
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ const i = lenses.indexOf(overlay);
+ if (i < 0) return;
+ let next = i;
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % lenses.length;
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
+ next = (i - 1 + lenses.length) % lenses.length;
+ else return;
+ e.preventDefault();
+ const target = lenses[next];
+ if (target) onOverlayChange(target);
+ };
+
+ return (
+ <div
+ role="radiogroup"
+ aria-label="Map lens"
+ onKeyDown={onKeyDown}
+ className={`inline-flex rounded-md border border-[var(--color-border-default)] p-0.5 ${className ?? ""}`}
+ >
+ {lenses.map((mode) => {
+ const active = overlay === mode;
+ return (
+ <button
+ key={mode}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ tabIndex={active ? 0 : -1}
+ onClick={() => onOverlayChange(mode)}
+ className={`rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
+ : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {OVERLAY_SPECS[mode].label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/**
+ * The active lens's key, laid out as a horizontal strip to sit under the map.
+ *
+ * Same content as the on-canvas panel, arranged to read as a caption rather
+ * than as a floating card.
+ */
+export function MapLegend({
+ overlay,
+ loading = false,
+ className,
+}: {
+ overlay: CodeHealthOverlay;
+ loading?: boolean;
+ className?: string;
+}) {
+ const spec = OVERLAY_SPECS[overlay] ?? OVERLAY_SPECS.health;
+ return (
+ <div
+ className={`flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[11px] text-[var(--color-text-tertiary)] ${className ?? ""}`}
+ >
+ {loading ? (
+ <span className="flex items-center gap-1.5">
+ <span className="h-2 w-2 animate-pulse rounded-full bg-[var(--color-text-tertiary)]" />
+ loading {spec.label.toLowerCase()}…
+ </span>
+ ) : (
+ spec.legend.map((row, i) => (
+ <Fragment key={row.label}>
+ {row.group && row.group !== spec.legend[i - 1]?.group ? (
+ <span className="ml-1 font-mono text-[9px] uppercase tracking-[0.12em] first:ml-0">
+ {row.group}
+ </span>
+ ) : null}
+ <span className="flex items-center gap-1.5">
+ <Swatch row={row} size={8} />
+ {row.label}
+ </span>
+ </Fragment>
+ ))
+ )}
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em]">{spec.caption}</span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/map/lens.ts b/packages/ui/src/health/map/lens.ts
new file mode 100644
index 000000000..7b462ceea
--- /dev/null
+++ b/packages/ui/src/health/map/lens.ts
@@ -0,0 +1,343 @@
+/**
+ * What each lens does to a node, as pure functions over one row.
+ *
+ * Nothing here reads layout, state, or the DOM, so a legend and the canvas
+ * cannot drift: both call the same spec.
+ */
+
+import { scoreBand, type ScoreBand } from "../tokens";
+import type { CodeHealthMapFile, CodeHealthOverlay, PerformanceActionability } from "./types";
+
+/* Band -> SVG fill var(). The same ramp as every score pill on the surface. */
+const BAND_FILL: Record<ScoreBand, string> = {
+ critical: "var(--color-error)",
+ poor: "var(--color-warning)",
+ fair: "var(--color-caution)",
+ good: "var(--color-success)",
+};
+
+const BAND_LABEL: { band: ScoreBand; label: string }[] = [
+ { band: "critical", label: "Alert" },
+ { band: "poor", label: "Warning" },
+ { band: "fair", label: "Fair" },
+ { band: "good", label: "Healthy" },
+];
+
+/** Neutral fill for nodes a non-health lens has no signal for. */
+export const NEUTRAL_FILL = "var(--color-text-tertiary)";
+
+/** Quieter still: the file was never looked at, which is not "no signal". */
+export const ABSENT_FILL = "var(--color-border-default)";
+
+export interface LegendRow {
+ fill: string;
+ label: string;
+ /**
+ * How the swatch is drawn. `ring` is an outline rather than a disc, so the
+ * performance key reads as the mark it describes; `dash` mirrors the ring's
+ * stroke pattern, which is the lens's non-colour channel.
+ */
+ mark?: "dot" | "ring";
+ dash?: string;
+ /**
+ * Which channel this row belongs to. The performance lens marks a node on
+ * two independent axes, and a flat list of swatches gives a reader no way to
+ * see that the first three are one axis and the next three another. The key
+ * prints the group once, where it changes.
+ */
+ group?: string;
+}
+
+/** Lens metadata: how to fill a node and what the key reads. */
+export interface OverlaySpec {
+ label: string;
+ /** Caption shown under the legend key. */
+ caption: string;
+ fill: (f: CodeHealthMapFile) => string;
+ /** Per-node opacity, when the lens needs most of the field to sit back. */
+ fillOpacity?: (f: CodeHealthMapFile) => number;
+ legend: LegendRow[];
+}
+
+/** Score band: the health ramp, quiet grey when the pillar is unscored. */
+function scoreFill(score: number | null | undefined): string {
+ if (score == null) return NEUTRAL_FILL;
+ return BAND_FILL[scoreBand(score)];
+}
+
+/** Coverage band: green = well covered, red = uncovered, grey = no data. */
+function coverageFill(pct: number | null | undefined): string {
+ if (pct == null) return NEUTRAL_FILL;
+ if (pct >= 80) return "var(--color-success)";
+ if (pct >= 50) return "var(--color-caution)";
+ if (pct >= 20) return "var(--color-warning)";
+ return "var(--color-error)";
+}
+
+/** Churn band: red = top-decile churn, green = quiet. */
+function churnFill(pctile: number | null | undefined): string {
+ if (pctile == null) return NEUTRAL_FILL;
+ if (pctile >= 90) return "var(--color-error)";
+ if (pctile >= 70) return "var(--color-warning)";
+ if (pctile >= 40) return "var(--color-caution)";
+ return "var(--color-success)";
+}
+
+/* ------------------------------------------------------------------ *
+ * Performance lens
+ *
+ * One mark on the node, one mark beside it, and a field that gets out of
+ * the way.
+ *
+ * A file a detector cleared is a file with no *supported pattern* in it, not a
+ * file measured to be fast, so it is never painted the healthy green. But most
+ * of a repository is that, and the first cut of this lens gave every one of
+ * those files a solid mid-grey disc at nine-tenths opacity. Two thousand of
+ * them tiled into an opaque sheet: node boundaries vanished, and an outline
+ * drawn around one large node read as a lasso thrown over a crowd of small
+ * ones. The burden also rode on that outline, in a colour and a dash pattern,
+ * which at four-pixel radius is a handful of disconnected specks.
+ *
+ * So the quiet files recede to a faint substrate, and colour moves onto the
+ * node, where the eye already is: how many open causes, in three steps. The
+ * outline survives for the one thing worth a second mark, a cause with a
+ * stored plan, and is a plain bright ring rather than a fourth hue. Advisory
+ * and investigate are named in words by the hover card, the inspector and the
+ * ranked list, which is where a distinction this fine belongs.
+ * ------------------------------------------------------------------ */
+
+export type PerformanceNodeState =
+ | "actionable"
+ | "advisory"
+ | "investigate"
+ | "clear"
+ | "unsupported"
+ | "unknown";
+
+/** Which unit the ring is counting, so the copy can say so. */
+export type PerformanceBurdenUnit = "opportunities" | "observations";
+
+export interface PerformanceBurden {
+ state: PerformanceNodeState;
+ count: number;
+ unit: PerformanceBurdenUnit;
+}
+
+const ACTIONABILITY_STATE: Record<PerformanceActionability, PerformanceNodeState> = {
+ plan_ready: "actionable",
+ advisory: "advisory",
+ investigate: "investigate",
+};
+
+/**
+ * Read one row's performance state and the size of its burden.
+ *
+ * A host serving the causal read model gets opportunities. A host that only
+ * has raw observations degrades to counting those and says which it counted,
+ * rather than reporting a number under the other one's name.
+ */
+export function performanceBurden(f: CodeHealthMapFile): PerformanceBurden {
+ const opportunities = f.performance_opportunities;
+ if (opportunities != null) {
+ if (opportunities > 0) {
+ const state = f.performance_actionability
+ ? ACTIONABILITY_STATE[f.performance_actionability]
+ : "investigate";
+ return { state, count: opportunities, unit: "opportunities" };
+ }
+ return {
+ state: f.performance_analyzed === false ? "unsupported" : "clear",
+ count: 0,
+ unit: "opportunities",
+ };
+ }
+ const observations = f.performance_findings;
+ if (observations != null) {
+ if (observations > 0) {
+ return { state: "investigate", count: observations, unit: "observations" };
+ }
+ return {
+ state: f.performance_analyzed === false ? "unsupported" : "clear",
+ count: 0,
+ unit: "observations",
+ };
+ }
+ return {
+ state: f.performance_analyzed === false ? "unsupported" : "unknown",
+ count: 0,
+ unit: "opportunities",
+ };
+}
+
+/** Fill: how many open causes, or a quiet neutral. Never the healthy green. */
+export function performanceFill(f: CodeHealthMapFile): string {
+ const { state, count } = performanceBurden(f);
+ const band = burdenBand(count);
+ if (band !== 0) return BAND_TONE[band];
+ return state === "unsupported" || state === "unknown" ? ABSENT_FILL : NEUTRAL_FILL;
+}
+
+/**
+ * How present a node is.
+ *
+ * A few hundred files out of thousands carry a cause, so the rest sit back far
+ * enough for those to read as figure rather than as more of the ground. A
+ * loaded node is fully present, and its band is carried by the tone: a single
+ * cause is by far the commonest of the three, so the ramp has to quieten it
+ * without making it transparent.
+ */
+export function performanceOpacity(f: CodeHealthMapFile): number {
+ const { state, count } = performanceBurden(f);
+ if (burdenBand(count) !== 0) return 1;
+ return state === "unsupported" || state === "unknown" ? 0.14 : 0.26;
+}
+
+/** Burden band, 0 when the file carries none. Bounded so 40 causes is a step. */
+export function burdenBand(count: number): 0 | 1 | 2 | 3 {
+ if (count <= 0) return 0;
+ if (count === 1) return 1;
+ if (count < 5) return 2;
+ return 3;
+}
+
+/**
+ * The three steps, quietened toward the page rather than toward transparency.
+ *
+ * The nodes overlap by construction, so a translucent ramp is read wrong: two
+ * overlapping one-cause files composite into exactly the tone that means two
+ * to four. Mixing into the background instead keeps every node opaque, so a
+ * colour on this field always means one band and never a pile of them.
+ */
+const BAND_TONE: Record<1 | 2 | 3, string> = {
+ 1: "color-mix(in srgb, var(--color-caution) 60%, var(--color-bg-root))",
+ 2: "color-mix(in srgb, var(--color-warning) 82%, var(--color-bg-root))",
+ 3: "var(--color-error)",
+};
+
+export interface PressureRing {
+ stroke: string;
+ /** Stroke width in user units, before the caller divides by the zoom scale. */
+ width: number;
+}
+
+/**
+ * The ring for one row, or `null`, which is most of them.
+ *
+ * Only a cause with a stored plan takes one: 29 of 768 here. A mark every
+ * coloured node carries is not a mark, and a plain bright ring reads as
+ * "singled out" without competing with the colour underneath it for the same
+ * meaning.
+ */
+export function pressureRing(f: CodeHealthMapFile): PressureRing | null {
+ if (performanceBurden(f).state !== "actionable") return null;
+ return { stroke: "var(--color-text-primary)", width: 1.1 };
+}
+
+export const PERFORMANCE_STATE_LABEL: Record<PerformanceNodeState, string> = {
+ actionable: "Stored plan",
+ advisory: "Advisory",
+ investigate: "Needs investigation",
+ clear: "Analyzed, nothing surfaced",
+ unsupported: "No detector for this language",
+ unknown: "Not analyzed here",
+};
+
+/** One sentence a hover card or inspector can print about a file. */
+export function performanceSentence(f: CodeHealthMapFile): string {
+ const { state, count, unit } = performanceBurden(f);
+ if (count > 0) {
+ const noun = count === 1 ? unit.replace(/s$/, "") : unit;
+ return `${count} open ${noun} · ${PERFORMANCE_STATE_LABEL[state].toLowerCase()}`;
+ }
+ return PERFORMANCE_STATE_LABEL[state];
+}
+
+export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
+ health: {
+ label: "Health",
+ caption: "galaxy = module · size = lines of code",
+ fill: (f) => BAND_FILL[scoreBand(f.score)],
+ legend: BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),
+ },
+ maintainability: {
+ label: "Maintainability",
+ caption: "color = maintainability score · grey = not measured",
+ fill: (f) => scoreFill(f.maintainability_score),
+ legend: [
+ ...BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),
+ { fill: NEUTRAL_FILL, label: "not measured" },
+ ],
+ },
+ performance: {
+ label: "Performance",
+ caption:
+ "galaxy = module · dot = file, sized by lines of code · colour = open causes, never a runtime measurement",
+ fill: performanceFill,
+ fillOpacity: performanceOpacity,
+ legend: [
+ { group: "Open causes", fill: BAND_TONE[3], label: "5 or more" },
+ { group: "Open causes", fill: BAND_TONE[2], label: "2 to 4" },
+ { group: "Open causes", fill: BAND_TONE[1], label: "1" },
+ { group: "Ringed", fill: "var(--color-text-primary)", label: "Stored plan", mark: "ring" },
+ { group: "No cause", fill: NEUTRAL_FILL, label: "Analyzed, nothing surfaced" },
+ { group: "No cause", fill: ABSENT_FILL, label: "Not analyzed" },
+ ],
+ },
+ coverage: {
+ label: "Coverage",
+ caption: "color = line coverage · grey = no coverage data",
+ fill: (f) => coverageFill(f.line_coverage_pct),
+ legend: [
+ { fill: "var(--color-success)", label: "≥80%" },
+ { fill: "var(--color-caution)", label: "50-80%" },
+ { fill: "var(--color-warning)", label: "20-50%" },
+ { fill: "var(--color-error)", label: "<20%" },
+ { fill: NEUTRAL_FILL, label: "no data" },
+ ],
+ },
+ churn: {
+ label: "Churn",
+ caption: "color = 90-day churn percentile",
+ fill: (f) => churnFill(f.churn_percentile),
+ legend: [
+ { fill: "var(--color-error)", label: "Top 10%" },
+ { fill: "var(--color-warning)", label: "Top 30%" },
+ { fill: "var(--color-caution)", label: "Top 60%" },
+ { fill: "var(--color-success)", label: "Quiet" },
+ { fill: NEUTRAL_FILL, label: "no data" },
+ ],
+ },
+ "dead-code": {
+ label: "Dead code",
+ caption: "red = reclaimable lines · grey = clean",
+ fill: (f) => ((f.dead_code_lines ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),
+ legend: [
+ { fill: "var(--color-error)", label: "Has dead code" },
+ { fill: NEUTRAL_FILL, label: "Clean" },
+ ],
+ },
+ security: {
+ label: "Security",
+ caption: "red = open findings · grey = clean",
+ fill: (f) => ((f.security_findings ?? 0) > 0 ? "var(--color-error)" : NEUTRAL_FILL),
+ legend: [
+ { fill: "var(--color-error)", label: "Has findings" },
+ { fill: NEUTRAL_FILL, label: "Clean" },
+ ],
+ },
+};
+
+/**
+ * Default lenses offered in the switcher: the three co-equal health signals,
+ * all backed by a per-file signal that rides on the map payload itself.
+ *
+ * Churn is deliberately not in the default. It colors by `churn_percentile`,
+ * which arrives on a separate request the host has to join in, so offering it
+ * where nobody joined it paints an all-neutral field that reads as "no churn"
+ * rather than "no data". Hosts that do the join pass their own `lenses`.
+ */
+export const OVERLAY_ORDER: CodeHealthOverlay[] = [
+ "health",
+ "maintainability",
+ "performance",
+];
diff --git a/packages/ui/src/health/map/node-layer.tsx b/packages/ui/src/health/map/node-layer.tsx
new file mode 100644
index 000000000..91dd777c9
--- /dev/null
+++ b/packages/ui/src/health/map/node-layer.tsx
@@ -0,0 +1,154 @@
+"use client";
+
+/**
+ * The base field: one circle per file, and the performance lens's rings.
+ *
+ * Both layers are memoized and fed only stable props, so hover, selection and
+ * search - which all re-render the facade - never reconcile these elements.
+ * Everything that moves with the pointer lives in the overlay layer instead.
+ */
+
+import { memo } from "react";
+import { pressureRing } from "./lens";
+import type { CodeHealthMapFile, Galaxy } from "./types";
+
+export interface NodeLayerProps {
+ galaxies: Galaxy[];
+ focusModuleKey: string | null;
+ fill: (f: CodeHealthMapFile) => string;
+ /** Per-node opacity, so a lens can push most of the field into the ground. */
+ fillOpacity?: ((f: CodeHealthMapFile) => number) | undefined;
+ offX: number;
+ offY: number;
+ /**
+ * Stroke in user units, pre-divided by the zoom scale so it lands on half a
+ * device pixel at rest.
+ *
+ * The obvious spelling is `vectorEffect="non-scaling-stroke"`, which is what
+ * this used. Chrome recomputes stroke geometry per element per frame for
+ * that attribute, and these are thousands of elements inside the group whose
+ * transform animates on every galaxy zoom. Dividing by the scale is free.
+ * The trade is that during the transition the browser interpolates the
+ * transform while this value is already at its destination, so strokes are
+ * fractionally off mid-flight, which is invisible on a half-pixel line under
+ * a moving field and correct the instant it settles.
+ */
+ strokeWidth: number;
+ interactive: boolean;
+ onSelect: (path: string) => void;
+ onHoverEnter: (f: CodeHealthMapFile) => void;
+ onHoverLeave: (f: CodeHealthMapFile) => void;
+}
+
+export const FileNodes = memo(function FileNodes({
+ galaxies,
+ focusModuleKey,
+ fill,
+ fillOpacity,
+ offX,
+ offY,
+ strokeWidth,
+ interactive,
+ onSelect,
+ onHoverEnter,
+ onHoverLeave,
+}: NodeLayerProps) {
+ return (
+ <>
+ {galaxies.map((g) => {
+ const faded = focusModuleKey != null && g.module !== focusModuleKey;
+ return (
+ <g key={`nodes-${g.module}`}>
+ {g.nodes.map((nd) => {
+ const f = nd.file;
+ return (
+ /* No <title> child. It was thousands of extra DOM nodes driving
+ a native tooltip that appears on its own delay, in the corner
+ the pointer is in, restating what the hover card already
+ shows the moment you touch a node - two tooltips racing.
+ `data-path` costs no node and gives tests a stable handle. */
+ <circle
+ key={f.file_path}
+ data-path={f.file_path}
+ cx={nd.x + offX}
+ cy={nd.y + offY}
+ r={nd.r}
+ fill={fill(f)}
+ fillOpacity={
+ faded ? 0.18 : ((fillOpacity?.(f) ?? 0.9) as number)
+ }
+ stroke="var(--color-bg-root)"
+ // A quiet node keeps no separating stroke: at a tenth of the
+ // field's opacity the stroke is louder than the node, which
+ // turns a soft substrate back into a grid of rings.
+ strokeWidth={(fillOpacity?.(f) ?? 0.9) < 0.4 ? 0 : strokeWidth}
+ className={interactive ? "cursor-pointer" : undefined}
+ onMouseEnter={() => onHoverEnter(f)}
+ onMouseLeave={() => onHoverLeave(f)}
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelect(f.file_path);
+ }}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </>
+ );
+});
+
+/**
+ * The one extra mark, as its own layer.
+ *
+ * Only a cause with a stored plan takes a ring, so this draws tens of elements
+ * where the node layer draws thousands. The burden itself is the node's
+ * colour; this says "and there is something written down for this one".
+ */
+export const PressureRings = memo(function PressureRings({
+ galaxies,
+ focusModuleKey,
+ offX,
+ offY,
+ scale,
+}: {
+ galaxies: Galaxy[];
+ focusModuleKey: string | null;
+ offX: number;
+ offY: number;
+ /** Zoom scale, so stroke widths land where they were designed. */
+ scale: number;
+}) {
+ return (
+ <g className="pointer-events-none">
+ {galaxies.map((g) => {
+ const faded = focusModuleKey != null && g.module !== focusModuleKey;
+ return (
+ <g key={`rings-${g.module}`} opacity={faded ? 0.2 : 1}>
+ {g.nodes.map((nd) => {
+ const ring = pressureRing(nd.file);
+ if (!ring) return null;
+ const width = ring.width / scale;
+ return (
+ <circle
+ key={nd.file.file_path}
+ data-ring={nd.file.file_path}
+ cx={nd.x + offX}
+ cy={nd.y + offY}
+ // Outside the node, by half the stroke plus a hairline, so
+ // the ring reads as pressure around the file rather than as
+ // a border on it.
+ r={nd.r + width}
+ fill="none"
+ stroke={ring.stroke}
+ strokeWidth={width}
+ />
+ );
+ })}
+ </g>
+ );
+ })}
+ </g>
+ );
+});
diff --git a/packages/ui/src/health/map/overlay.tsx b/packages/ui/src/health/map/overlay.tsx
new file mode 100644
index 000000000..08e6c9414
--- /dev/null
+++ b/packages/ui/src/health/map/overlay.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+/**
+ * Everything that follows the pointer, the keyboard, or the search box.
+ *
+ * Kept off the base field on purpose. Hovering a node used to re-render the
+ * whole node layer, and typing a search query used to re-render it once per
+ * keystroke, because the query dimmed every non-matching circle. Both are now
+ * bounded marks drawn on top: hover paints one circle, and search paints a
+ * ring on the matches instead of touching the thousands that did not match.
+ */
+
+import { performanceSentence } from "./lens";
+import type { CodeHealthMapFile, CodeHealthOverlay, FileNode } from "./types";
+
+/** Match rings drawn at once. Beyond this the field is the answer, not a mark. */
+export const SEARCH_MARK_CAP = 250;
+
+/** The hovered and selected nodes only, drawn on top of the static field. */
+export function NodeHighlight({
+ hovered,
+ selectedPath,
+ nodeIndex,
+ offX,
+ offY,
+ fill,
+}: {
+ hovered: CodeHealthMapFile | null;
+ selectedPath: string | null;
+ nodeIndex: Map<string, FileNode>;
+ offX: number;
+ offY: number;
+ fill: (f: CodeHealthMapFile) => string;
+}) {
+ const sel = selectedPath ? nodeIndex.get(selectedPath) : null;
+ const hov = hovered ? nodeIndex.get(hovered.file_path) : null;
+ return (
+ <g className="pointer-events-none">
+ {sel ? (
+ <circle
+ data-selected={sel.file.file_path}
+ cx={sel.x + offX}
+ cy={sel.y + offY}
+ r={sel.r}
+ fill={fill(sel.file)}
+ fillOpacity={1}
+ stroke="var(--color-accent-primary)"
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ />
+ ) : null}
+ {hov && hov !== sel ? (
+ <circle
+ cx={hov.x + offX}
+ cy={hov.y + offY}
+ r={hov.r + 1.5}
+ fill={fill(hov.file)}
+ fillOpacity={1}
+ stroke="var(--color-bg-root)"
+ strokeWidth={0.5}
+ vectorEffect="non-scaling-stroke"
+ />
+ ) : null}
+ </g>
+ );
+}
+
+/**
+ * A ring on every node whose path matches the query, bounded.
+ *
+ * Marking the matches rather than dimming the rest is what keeps typing off
+ * the base layer: the number of elements this draws tracks the answer, not the
+ * repository, and the field underneath is untouched.
+ */
+export function SearchMatches({
+ paths,
+ nodeIndex,
+ offX,
+ offY,
+}: {
+ paths: string[];
+ nodeIndex: Map<string, FileNode>;
+ offX: number;
+ offY: number;
+}) {
+ if (paths.length === 0) return null;
+ return (
+ <g className="pointer-events-none">
+ {paths.slice(0, SEARCH_MARK_CAP).map((path) => {
+ const nd = nodeIndex.get(path);
+ if (!nd) return null;
+ return (
+ <circle
+ key={path}
+ data-match={path}
+ cx={nd.x + offX}
+ cy={nd.y + offY}
+ r={nd.r + 2.5}
+ fill="none"
+ stroke="var(--color-accent-primary)"
+ strokeWidth={1.5}
+ vectorEffect="non-scaling-stroke"
+ />
+ );
+ })}
+ </g>
+ );
+}
+
+/**
+ * Pointer-bound decoding, in the active lens's terms.
+ *
+ * Hover answers "what is this and what does the current lens say about it".
+ * The lens's own sentence leads, so the card and the inspector describe the
+ * same object the same way.
+ */
+export function HoverCard({
+ file,
+ overlay,
+}: {
+ file: CodeHealthMapFile;
+ overlay: CodeHealthOverlay;
+}) {
+ const cov = file.line_coverage_pct;
+ return (
+ <div className="pointer-events-none absolute bottom-3 left-3 max-w-[75%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs shadow-md">
+ <div className="truncate font-mono text-[var(--color-text-primary)]">
+ {file.file_path}
+ </div>
+ {overlay === "performance" ? (
+ <div className="text-[var(--color-text-secondary)]">
+ {performanceSentence(file)}
+ </div>
+ ) : null}
+ <div className="text-[var(--color-text-tertiary)] tabular-nums">
+ score {file.score.toFixed(1)} · {file.nloc.toLocaleString()} NLOC
+ {cov != null ? ` · ${Math.round(cov)}% cov` : ""}
+ {file.has_test_file ? "" : " · untested"}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/map/types.ts b/packages/ui/src/health/map/types.ts
new file mode 100644
index 000000000..3ac860862
--- /dev/null
+++ b/packages/ui/src/health/map/types.ts
@@ -0,0 +1,109 @@
+/**
+ * The map's data shapes, shared by the pure layers behind the facade.
+ *
+ * Kept apart from the encodings and the layout so neither imports the other:
+ * a fill function should not be able to reach the packing algorithm.
+ */
+
+export interface CodeHealthMapFile {
+ file_path: string;
+ score: number;
+ nloc: number;
+ module: string | null;
+ line_coverage_pct: number | null;
+ has_test_file: boolean;
+ /** Maintainability pillar score (1-10), drives the maintainability lens. */
+ maintainability_score?: number | null;
+ /** Performance-risk pillar score. Never drawn: it compresses to [8,10], so a
+ * score ramp paints the field one colour and hides where the risk is. */
+ performance_score?: number | null;
+ /** Open causal opportunities on this file. The performance lens rings by
+ * this, because an opportunity is one thing a reader could go and do. */
+ performance_opportunities?: number | null;
+ /** Observations behind those opportunities. */
+ performance_observations?: number | null;
+ /** Best next step available on the file: a stored plan beats an advisory
+ * intervention, which beats an investigation. */
+ performance_actionability?: PerformanceActionability | null;
+ /** Best queue rank among the file's opportunities, for ranked lists. */
+ performance_rank?: number | null;
+ /** Open performance observations, from a host that serves no causal read
+ * model. The lens falls back to it and says which unit it is counting. */
+ performance_findings?: number | null;
+ /** Whether a performance detector runs on this file's language at all.
+ * `false` means nothing ever looked, which is not the same as clear. */
+ performance_analyzed?: boolean | null;
+ /** 0-100 churn percentile, drives the churn lens. */
+ churn_percentile?: number | null;
+ /** Reclaimable lines, drives the dead-code lens. */
+ dead_code_lines?: number | null;
+ /** Open security findings, drives the security lens. */
+ security_findings?: number | null;
+}
+
+export type PerformanceActionability = "plan_ready" | "advisory" | "investigate";
+
+/**
+ * Lens applied to the same field. Recolors every node without re-laying the
+ * galaxies, so spatial memory survives a lens change.
+ */
+export type CodeHealthOverlay =
+ | "health"
+ | "maintainability"
+ | "performance"
+ | "coverage"
+ | "churn"
+ | "dead-code"
+ | "security";
+
+/** One module = one galaxy: its files plus size aggregates. */
+export interface GalaxyAgg {
+ module: string;
+ files: CodeHealthMapFile[]; // NLOC-desc
+ totalNloc: number;
+ maxNloc: number;
+}
+
+export interface FileNode {
+ file: CodeHealthMapFile;
+ x: number;
+ y: number;
+ r: number;
+}
+
+export interface Galaxy {
+ module: string;
+ cx: number;
+ cy: number;
+ R: number;
+ fileCount: number;
+ colorId: number;
+ nodes: FileNode[];
+}
+
+/**
+ * What the server drew and what it left out, as one object.
+ *
+ * The field and the sentence describing it come from the same response, so a
+ * caption can never claim a scope the canvas does not have.
+ */
+export interface MapScope {
+ shown: number;
+ /** Files that could be drawn at all. A zero-line file cannot be sized. */
+ eligible: number;
+ repository: number;
+ cap: number;
+ omitted: {
+ files: number;
+ /**
+ * Files carrying an open cause that the cap pushed out. `null` when the
+ * host cannot count them: zero would claim every cause is on screen, which
+ * is the one thing a caption here must never say without knowing it.
+ */
+ performanceFiles: number | null;
+ opportunities: number | null;
+ observations: number | null;
+ };
+ /** Paths the caller pinned that the index holds no drawable row for. */
+ missing?: string[];
+}
diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsx
index 619435a2b..ba6243209 100644
--- a/packages/ui/src/health/performance-view.tsx
+++ b/packages/ui/src/health/performance-view.tsx
@@ -5,6 +5,7 @@ import useSWR from "swr";
import type {
PerformanceContextFilter,
PerformanceOpportunity,
+ PerformanceOpportunityDetail,
PerformanceOpportunityPage,
} from "@repowise-dev/types/health";
import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
@@ -38,6 +39,7 @@ import {
EmptyQueue,
FilteredEmpty,
IgnoredArgumentsNotice,
+ LinkedCauseUnavailable,
QueueError,
QueueSkeleton,
StaleModelNotice,
@@ -61,17 +63,31 @@ export function PerformanceView({
adapter,
initialFilters,
onFiltersChange,
+ openOpportunityId,
+ onOpenOpportunityChange,
}: {
adapter: PerformanceViewAdapter;
/** A serialized filter state, so a shared link opens the same queue. */
initialFilters?: string | undefined;
/** Called with the serialized state whenever a filter moves. */
onFiltersChange?: ((search: string) => void) | undefined;
+ /**
+ * A cause to open on arrival, by its stable id. A link from the map or the
+ * file drawer names one, and it need not be on the page the filters would
+ * have loaded, so it is resolved by id rather than looked for in the queue.
+ */
+ openOpportunityId?: string | null;
+ /** Called with the open cause's id, or null when the drawer closes. */
+ onOpenOpportunityChange?: ((opportunityId: string | null) => void) | undefined;
}) {
const [filters, setFilters] = useState<PerformanceFilterState>(() =>
initialFilters ? parseFilters(initialFilters) : INITIAL_FILTERS,
);
const [selected, setSelected] = useState<PerformanceOpportunity | null>(null);
+ const select = (next: PerformanceOpportunity | null) => {
+ setSelected(next);
+ onOpenOpportunityChange?.(next?.opportunity_id ?? null);
+ };
// The handoff carries the verified plan when the drawer proved one, so a
// plan-ready row hands over the ready payload rather than an instruction to
// re-derive it.
@@ -104,6 +120,29 @@ export function PerformanceView({
if (data) setCollapse(!capabilitiesOf(adapter, data).canonicalContexts);
}, [adapter, data]);
+ // A link naming a cause opens it, whether or not the filters would have
+ // loaded the page it sits on. Resolved by id rather than searched for in the
+ // queue: this repository has 743 causes and a link is allowed to name any of
+ // them. The row shape and the detail shape share their fields, so what comes
+ // back drives the same drawer a click does.
+ const pendingId =
+ openOpportunityId && openOpportunityId !== selected?.opportunity_id
+ ? openOpportunityId
+ : null;
+ const { data: linked, error: linkError } = useSWR<PerformanceOpportunityDetail>(
+ pendingId && adapter.getPerformanceOpportunity
+ ? `performance-opportunity-link:${adapter.cacheKey}:${pendingId}`
+ : null,
+ () => adapter.getPerformanceOpportunity!(pendingId!, { evidenceLimit: 8 }),
+ { revalidateOnFocus: false },
+ );
+ useEffect(() => {
+ // Both branches of the detail carry an id, so the discriminant decides:
+ // an id from a retired model resolves to a state, not to a cause, and
+ // opening a drawer on it would render an empty panel.
+ if (linked?.resolved) setSelected(linked);
+ }, [linked]);
+
if (!load) return <LegacyPerformanceFindings adapter={adapter} />;
if (error && [404, 405].includes(Number((error as { status?: number }).status))) {
return <LegacyPerformanceFindings adapter={adapter} />;
@@ -226,7 +265,7 @@ export function PerformanceView({
adapter={adapter}
showSections={filters.actionability === null}
selectedId={selected?.opportunity_id ?? null}
- onInspect={setSelected}
+ onInspect={select}
/>
)}
@@ -248,12 +287,20 @@ export function PerformanceView({
/>
</section>
+ {pendingId && (linkError || linked?.resolved === false) ? (
+ <LinkedCauseUnavailable
+ opportunityId={pendingId}
+ detail={linked && !linked.resolved ? linked.detail : null}
+ onDismiss={() => onOpenOpportunityChange?.(null)}
+ />
+ ) : null}
+
<OpportunityDrawer
opportunity={selected}
adapter={adapter}
detailEnabled={capabilities.detailById}
planEnabled={capabilities.planById}
- onClose={() => setSelected(null)}
+ onClose={() => select(null)}
onAgentHandoff={(opportunity, plan) => setPromptFor({ opportunity, plan })}
/>
diff --git a/packages/ui/src/health/performance/adapter.ts b/packages/ui/src/health/performance/adapter.ts
index 99d98c36b..02aa1c37a 100644
--- a/packages/ui/src/health/performance/adapter.ts
+++ b/packages/ui/src/health/performance/adapter.ts
@@ -15,6 +15,7 @@ export type PerformanceViewAdapter = Pick<
| "getPerformanceOpportunityFindings"
| "getRefactoringPlan"
| "refactoringPlanHref"
+ | "mapHref"
| "fileHref"
| "symbolHref"
| "navigate"
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index 2af38a6d6..2b8551a02 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -237,6 +237,8 @@ export function OpportunityDrawer({
</p>
) : null}
+ <MapLink adapter={adapter} opportunity={current} />
+
<Section title="What the evidence shows">
<dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
<Field label="Context" value={contextLabel(current.execution_context)} />
@@ -372,3 +374,29 @@ export function OpportunityDrawer({
</AdaptivePanel>
);
}
+
+/**
+ * Where this cause sits on the one map.
+ *
+ * A link rather than a second canvas: the galaxy already exists, it already
+ * knows how to guarantee a file a node, and drawing a small copy of it here
+ * would put two fields with two geometries on one screen.
+ */
+function MapLink({
+ adapter,
+ opportunity,
+}: {
+ adapter: PerformanceViewAdapter;
+ opportunity: PerformanceOpportunity;
+}) {
+ const href = adapter.mapHref?.(opportunity.opportunity_id, opportunity.file_path);
+ if (!href || !opportunity.file_path) return null;
+ return (
+ <a
+ href={href}
+ className="inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ Show this cause on the map
+ </a>
+ );
+}
diff --git a/packages/ui/src/health/performance/states.tsx b/packages/ui/src/health/performance/states.tsx
index 446bc7eca..595616a32 100644
--- a/packages/ui/src/health/performance/states.tsx
+++ b/packages/ui/src/health/performance/states.tsx
@@ -145,3 +145,39 @@ export function IgnoredArgumentsNotice({ ignored }: { ignored: Record<string, st
</Notice>
);
}
+
+/**
+ * A link named a cause this index cannot resolve.
+ *
+ * Says which id, because the link is shareable and the reader may be holding
+ * it somewhere else, and offers the queue rather than leaving the page looking
+ * like it simply ignored them.
+ */
+export function LinkedCauseUnavailable({
+ opportunityId,
+ detail,
+ onDismiss,
+}: {
+ opportunityId: string;
+ detail: string | null;
+ onDismiss: () => void;
+}) {
+ return (
+ <p
+ role="status"
+ className="flex flex-wrap items-baseline gap-x-2 border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"
+ >
+ <span>
+ The link named <span className="break-all font-mono">{opportunityId}</span>, which this
+ index does not hold.{detail ? ` ${detail}` : ""} The queue below is unfiltered.
+ </span>
+ <button
+ type="button"
+ onClick={onDismiss}
+ className="rounded text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ Dismiss
+ </button>
+ </p>
+ );
+}
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index cbe7e10c9..8247b7bf2 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -6,6 +6,7 @@ import { InfoTip } from "../shared/info-tip";
import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
import { type Severity } from "./tokens";
+import { ImpactFigure } from "./impact-figure";
import { SeverityMark } from "./severity-mark";
export type EffortBucket = "S" | "M" | "L" | "XL";
@@ -224,9 +225,7 @@ export function HealthWorkItemCard({
{f.function_name ? (
<span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>
) : null}
- <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">
- −{f.health_impact.toFixed(2)}
- </span>
+ <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>
{onStatusChange ? (
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index e1aab5b78..535863c95 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -5,6 +5,7 @@ import {
type BiomarkerCategory,
} from "./biomarker-glossary";
import { scoreBadgeClass, type Severity } from "./tokens";
+import { ImpactFigure } from "./impact-figure";
import { SeverityMark } from "./severity-mark";
export interface ScoreBreakdownCategoryFinding {
@@ -133,9 +134,7 @@ export function ScoreBreakdown({
{f.function_name}
</span>
) : null}
- <span className="ml-auto tabular-nums text-[var(--color-error)]">
- −{f.applied_impact.toFixed(2)}
- </span>
+ <ImpactFigure impact={f.applied_impact} className="ml-auto" />
</li>
))}
{c.findings.length > 6 ? (
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 0a4ebb54b..f24954aaa 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -222,6 +222,26 @@ export function deltaColor(delta: number | null | undefined): string {
export function formatDelta(delta: number | null | undefined): string {
if (delta == null) return "—";
- const sign = delta > 0 ? "+" : "";
- return `${sign}${delta.toFixed(2)}`;
+ // Rounding decides the sign here, not the raw value: a delta of -0.001 is
+ // "0.00", and printing it as "-0.00" claims a direction the figure on screen
+ // does not have.
+ const rounded = Number(delta.toFixed(2));
+ if (rounded === 0) return "0.00";
+ return `${rounded > 0 ? "+" : ""}${rounded.toFixed(2)}`;
+}
+
+/**
+ * A finding's deduction as a signed string, or `null` when it has none.
+ *
+ * Two different zeros, kept apart. Performance findings carry an impact of
+ * exactly zero by construction, so there is no deduction to print and `null`
+ * tells the caller to print a word instead. A real deduction too small to show
+ * at two places is still a measured cost, so it prints as a bound rather than
+ * as "−0.00", which would claim the finding costs nothing.
+ */
+export function formatHealthImpact(impact: number | null | undefined): string | null {
+ if (impact == null || impact === 0) return null;
+ const rounded = Number(Math.abs(impact).toFixed(2));
+ if (rounded === 0) return "−<0.01";
+ return `−${rounded.toFixed(2)}`;
}
diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsx
index 7d56c6ddb..d6ffcf17d 100644
--- a/packages/ui/src/health/triage-view.tsx
+++ b/packages/ui/src/health/triage-view.tsx
@@ -6,28 +6,29 @@
* The shape is: one lede that leads with the defect score and says in prose
* what it means, then the galaxy map as the page's spine with its inspector
* beside it, then the host's hotspot and trend sections. Grouping is hairlines
- * and vertical rhythm, not boxes — the previous version stacked a collapsible
- * accuracy banner, three bordered signal tiles, a bordered stat strip and a
- * bordered map, then floated three more glass panels on top of the map itself,
- * which is chrome sitting on the one thing the reader came to look at.
+ * and vertical rhythm, not boxes.
*
- * The map's lens switcher and legend now live around the canvas rather than on
- * it (`chrome="none"`), which is also what let the floating panels go: one of
- * them painted `--color-bg-glass`, a token still pinned to the graphite the
- * dark ramp moved off in July, so those panels were rendering a surface colour
- * that exists nowhere else in the app.
+ * The map's lens switcher and key live around the canvas rather than on it
+ * (`chrome="none"`), so the reader is not looking at the field through a stack
+ * of glass panels.
+ *
+ * The rail is an inspector. It used to hold the repository's top findings
+ * permanently, which made it a second findings list: it never described the
+ * object under the cursor and it never changed when the lens did. It now shows
+ * the selection when there is one and the field's ranked list otherwise, and
+ * both follow the active lens. The findings queue lives on its own tab.
*
* Presentation + orchestration only: the host injects data, links, and the
* file-detail drawer through a {@link CodeHealthAdapter}, so web and hosted
* render the same view from different backends.
*/
-import { useCallback, useRef, useState } from "react";
+import { useMemo, useState } from "react";
import type { ReactNode } from "react";
import useSWR from "swr";
import { Search } from "lucide-react";
import type {
- HealthFilesResponse,
+ HealthMapFeed,
HealthOverviewResponse,
HealthTrendResponse,
} from "@repowise-dev/types/health";
@@ -38,34 +39,53 @@ import { toFriendlyMessage } from "../lib/errors";
import { OverviewSection } from "../overview/section";
import { CodeHealthLede } from "./code-health-lede";
-import { BiomarkerList } from "./biomarker-list";
import {
CodeHealthMap,
MapLegend,
MapLensSwitcher,
type CodeHealthMapFile,
type CodeHealthOverlay,
+ type MapScope,
} from "./code-health-map";
-import { FileSpotlight } from "./code-health-controls";
-import { type Severity } from "./tokens";
+import { MapFieldList, MapInspector } from "./map/inspector";
import type { CodeHealthAdapter } from "./code-health-adapter";
export type HealthPillar = "all" | "defect" | "maintainability" | "performance";
-/** Map height. The inspector is height-matched to it so the rail never outgrows
- * the field it is inspecting. */
+/** Map height. The inspector is height-matched so the rail never outgrows the
+ * field it is inspecting. */
const MAP_HEIGHT = 720;
+/** Read the server's own selection totals into the shape the map states. */
+export function scopeFromFeed(feed: HealthMapFeed): MapScope {
+ return {
+ shown: feed.shown,
+ eligible: feed.eligible_total,
+ repository: feed.repository_total,
+ cap: feed.cap,
+ omitted: {
+ files: feed.omitted.files,
+ performanceFiles: feed.omitted.performance_files,
+ opportunities: feed.omitted.opportunities,
+ observations: feed.omitted.observations,
+ },
+ ...(feed.selection.active_missing.length
+ ? { missing: feed.selection.active_missing }
+ : {}),
+ };
+}
+
export function TriageView({
adapter,
trend: _trend,
overlay = "health",
onOverlayChange,
lenses,
- mapFiles,
+ mapFeed,
overlayLoading,
- pillar: controlledPillar,
- onPillarChange,
+ selectedPath,
+ onSelectPath,
+ highlightPaths,
hotspotsSlot,
trendSlot,
}: {
@@ -78,16 +98,18 @@ export function TriageView({
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
/** Lenses offered in the switcher. Hosts that join churn in pass it here. */
lenses?: CodeHealthOverlay[];
- /** Map files fetched once by the host (shared across overlays). */
- mapFiles?: HealthFilesResponse;
+ /** The bounded field, fetched once by the host and shared across lenses. */
+ mapFeed?: HealthMapFeed;
/** The active lens's per-file signal is still loading (e.g. churn). */
overlayLoading?: boolean;
/**
- * Findings pillar filter. Controlled by the host when it wants to URL-sync
- * the value; falls back to local state otherwise.
+ * Selected file. Controlled by the host when it wants the selection in the
+ * URL, so a link can open the map on one file; local otherwise.
*/
- pillar?: HealthPillar;
- onPillarChange?: (pillar: HealthPillar) => void;
+ selectedPath?: string | null;
+ onSelectPath?: (path: string | null) => void;
+ /** Extra paths to mark, for a link into one opportunity's files. */
+ highlightPaths?: string[];
/**
* Sections the host composes and hands in, rather than props this view
* fetches for itself. Hotspots needs git history and trend needs a second
@@ -104,41 +126,34 @@ export function TriageView({
{ revalidateOnFocus: false },
);
- // Severity gates the inspector findings list.
- const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
- const [selectedFile, setSelectedFile] = useState<string | null>(null);
+ const [localSelected, setLocalSelected] = useState<string | null>(null);
+ const selected = selectedPath !== undefined ? selectedPath : localSelected;
+ const setSelected = (path: string | null) => {
+ if (onSelectPath) onSelectPath(path);
+ else setLocalSelected(path);
+ };
- // ---- Map-driven UI: inspector spotlight + filename dim + search ----
- const [hoverFile, setHoverFile] = useState<CodeHealthMapFile | null>(null);
const [mapQuery, setMapQuery] = useState("");
- const [pillarState, setPillarState] = useState<HealthPillar>("all");
- const pillar = controlledPillar ?? pillarState;
- const findingsRef = useRef<HTMLDivElement | null>(null);
- const setPillar = useCallback(
- (next: HealthPillar) => {
- if (onPillarChange) onPillarChange(next);
- else setPillarState(next);
- },
- [onPillarChange],
+ const files = mapFeed?.files as CodeHealthMapFile[] | undefined;
+ const scope = useMemo(() => (mapFeed ? scopeFromFeed(mapFeed) : undefined), [mapFeed]);
+ const selectedFile = useMemo(
+ () => (selected ? files?.find((f) => f.file_path === selected) ?? null : null),
+ [files, selected],
);
- // Severity + pillar drive the findings list; omit unset filters rather than
- // passing `undefined` (strict optional props in the shared lib).
- const sidebarFilter: {
- minSeverity?: Severity;
- dimension?: "defect" | "maintainability" | "performance";
- } = {};
- if (minSeverity !== "all") sidebarFilter.minSeverity = minSeverity;
- if (pillar !== "all") sidebarFilter.dimension = pillar;
-
- // CodeHealthMap's optional props, omitted rather than passed as `undefined`.
+ // CodeHealthMap's optional props, omitted rather than passed as `undefined`
+ // (strict optional props in the shared lib).
const mapExtra: {
lenses?: CodeHealthOverlay[];
overlayLoading?: boolean;
+ scope?: MapScope;
+ highlightPaths?: string[];
} = {};
if (lenses) mapExtra.lenses = lenses;
if (overlayLoading !== undefined) mapExtra.overlayLoading = overlayLoading;
+ if (scope) mapExtra.scope = scope;
+ if (highlightPaths?.length) mapExtra.highlightPaths = highlightPaths;
if (isLoading) {
return (
@@ -176,7 +191,7 @@ export function TriageView({
<OverviewSection
title="Code health map"
- description="Every file as a node, clustered into module galaxies and sized by lines of code. The lens recolors the same field rather than redrawing it. Click a galaxy to zoom, a file to inspect it."
+ description="Every file as a node, clustered into module galaxies and sized by lines of code. The lens re-marks the same field rather than redrawing it. Click a galaxy to zoom, a file to inspect it."
action={
onOverlayChange ? (
<MapLensSwitcher
@@ -189,34 +204,26 @@ export function TriageView({
>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
<div className="flex flex-col gap-2.5">
- {!mapFiles ? (
+ {!files ? (
<Skeleton className="w-full rounded-xl" style={{ height: MAP_HEIGHT }} />
) : (
<CodeHealthMap
- files={mapFiles.files}
+ files={files}
search={mapQuery}
- selectedPath={selectedFile}
- onSelectFile={(p) => setSelectedFile(p)}
- onHoverFile={setHoverFile}
+ selectedPath={selected}
+ onSelectFile={setSelected}
minHeight={MAP_HEIGHT}
overlay={overlay}
chrome="none"
{...mapExtra}
/>
)}
- <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">
- <MapLegend overlay={overlay} loading={overlayLoading ?? false} />
- {mapFiles && (
- <span className="font-mono text-[10px] uppercase tracking-[0.12em] tabular-nums text-[var(--color-text-tertiary)]">
- {mapFiles.total.toLocaleString()} files
- </span>
- )}
- </div>
+ <MapLegend overlay={overlay} loading={overlayLoading ?? false} />
</div>
- {/* Inspector — height-matched to the map. Separated by space, not by
- a rule: a vertical hairline down the side of the canvas would turn
- the map into a trench. */}
+ {/* Inspector, height-matched to the map. Separated by space, not by
+ a rule: a vertical hairline down the side of the canvas would
+ turn the map into a trench. */}
<aside className="flex flex-col gap-3 lg:sticky lg:top-4 lg:h-[772px]">
<div className="relative">
<Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
@@ -229,47 +236,31 @@ export function TriageView({
/>
</div>
- <FileSpotlight file={hoverFile} onOpen={(p) => setSelectedFile(p)} />
-
- <div
- ref={findingsRef}
- className="flex flex-wrap items-center gap-2 border-t border-[var(--color-border-default)] pt-3"
- >
- <h3 className="mr-auto font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Findings
- </h3>
- <select
- value={pillar}
- onChange={(e) => setPillar(e.target.value as HealthPillar)}
- aria-label="Health pillar"
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs"
- >
- <option value="all">All pillars</option>
- <option value="defect">Defect risk</option>
- <option value="maintainability">Maintainability</option>
- <option value="performance">Performance</option>
- </select>
- <select
- value={minSeverity}
- onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
- aria-label="Minimum severity"
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1 text-xs"
- >
- <option value="all">All severities</option>
- <option value="low">Low+</option>
- <option value="medium">Medium+</option>
- <option value="high">High+</option>
- <option value="critical">Critical</option>
- </select>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto pb-1 pr-1 lg:pb-0">
- <BiomarkerList
- findings={overview.top_findings}
- compact
- {...sidebarFilter}
- onSelect={(f) => setSelectedFile(f.file_path)}
+ {selectedFile ? (
+ <MapInspector
+ file={selectedFile}
+ overlay={overlay}
+ onOpen={(p) => setSelected(p)}
+ onClose={() => setSelected(null)}
/>
- </div>
+ ) : selected ? (
+ <p className="rounded-lg border border-dashed border-[var(--color-border-default)] p-3 text-xs text-[var(--color-text-tertiary)]">
+ <span className="font-mono">{selected}</span> is not in the drawn field, so
+ there is no node to inspect. Its details still open below.
+ </p>
+ ) : null}
+
+ {files ? (
+ <div className="min-h-0 flex-1 overflow-hidden border-t border-[var(--color-border-default)] pt-3">
+ <MapFieldList
+ files={files}
+ overlay={overlay}
+ selectedPath={selected}
+ onSelectFile={setSelected}
+ {...(scope ? { scope } : {})}
+ />
+ </div>
+ ) : null}
</aside>
</div>
</OverviewSection>
@@ -278,8 +269,9 @@ export function TriageView({
{trendSlot}
{adapter.renderFileDrawer({
- filePath: selectedFile,
- onClose: () => setSelectedFile(null),
+ filePath: selected,
+ onClose: () => setSelected(null),
+ lens: overlay,
})}
</div>
);
diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.ts
index 08118c2f3..16ce78fbf 100644
--- a/packages/vscode/src/core/webviewApi.ts
+++ b/packages/vscode/src/core/webviewApi.ts
@@ -3,6 +3,7 @@ import {
getChurnComplexity,
getHealthOverview,
getHealthTrend,
+ getHealthMap,
listHealthFiles,
} from "@repowise-dev/api-client/code-health";
import { getArchitectureView } from "@repowise-dev/api-client/c4";
@@ -252,6 +253,8 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostAp
healthOverview: (limit) => cached(`health:overview:${limit ?? ""}`, (id) => getHealthOverview(id, limit)),
healthFiles: (query) =>
cached(`health:files:${JSON.stringify(query ?? {})}`, (id) => listHealthFiles(id, query)),
+ healthMap: (query) =>
+ cached(`health:map:${JSON.stringify(query ?? {})}`, (id) => getHealthMap(id, query)),
healthTrend: (limit) => cached(`health:trend:${limit ?? ""}`, (id) => getHealthTrend(id, limit)),
churnComplexity: (limit) =>
cached(`health:churn:${limit ?? ""}`, (id) => getChurnComplexity(id, limit != null ? { limit } : undefined)),
diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.ts
index eea4917f3..b5c9b9ba9 100644
--- a/packages/vscode/src/shared/webviewMessages.ts
+++ b/packages/vscode/src/shared/webviewMessages.ts
@@ -12,6 +12,8 @@ import type {
ChurnComplexityResponse,
HealthFilesQuery,
HealthFilesResponse,
+ HealthMapFeed,
+ HealthMapQuery,
HealthOverviewResponse,
HealthTrendResponse,
} from "@repowise-dev/types/health";
@@ -124,6 +126,8 @@ export interface HostApi {
// Health dashboard
healthOverview(limit?: number): Promise<HealthOverviewResponse>;
healthFiles(query?: HealthFilesQuery): Promise<HealthFilesResponse>;
+ /** The bounded field the map draws, chosen by the server. */
+ healthMap(query?: HealthMapQuery): Promise<HealthMapFeed>;
healthTrend(limit?: number): Promise<HealthTrendResponse>;
churnComplexity(limit?: number): Promise<ChurnComplexityResponse>;
// Architecture map
diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsx
index 46a05d6c7..e207091bb 100644
--- a/packages/vscode/webview/src/views/health/App.test.tsx
+++ b/packages/vscode/webview/src/views/health/App.test.tsx
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import type {
ChurnComplexityResponse,
- HealthFilesResponse,
+ HealthMapFeed,
HealthOverviewResponse,
HealthTrendResponse,
} from "@repowise-dev/types/health";
@@ -45,10 +45,24 @@ const overview: HealthOverviewResponse = {
top_findings: [],
};
-const files: HealthFilesResponse = {
- total: 128,
- offset: 0,
- limit: 2000,
+const files: HealthMapFeed = {
+ cap: 2000,
+ shown: 2,
+ eligible_total: 128,
+ repository_total: 130,
+ selection: {
+ basis: "active_then_performance_then_nloc",
+ active_requested: [],
+ active_shown: [],
+ active_missing: [],
+ performance_shown: 0,
+ performance_eligible: 0,
+ nloc_shown: 2,
+ },
+ omitted: { files: 126, performance_files: 0, opportunities: 0, observations: 0 },
+ recovery: {},
+ modules: [],
+ performance: null,
files: [
{
file_path: "src/worst.py",
@@ -124,7 +138,7 @@ function makeHost(): { host: WebviewHost; openFile: ReturnType<typeof vi.fn> } {
const host = {
api: {
healthOverview: () => Promise.resolve(overview),
- healthFiles: () => Promise.resolve(files),
+ healthMap: () => Promise.resolve(files),
healthTrend: () => Promise.resolve(trend),
churnComplexity: () => Promise.resolve(churn),
},
@@ -188,7 +202,7 @@ describe("Health dashboard", () => {
const host = {
api: {
healthOverview: () => Promise.reject(new Error("server down")),
- healthFiles: () => Promise.resolve(files),
+ healthMap: () => Promise.resolve(files),
healthTrend: () => Promise.resolve(trend),
churnComplexity: () => Promise.resolve(churn),
},
diff --git a/packages/vscode/webview/src/views/health/App.tsx b/packages/vscode/webview/src/views/health/App.tsx
index 011e52b0d..696520383 100644
--- a/packages/vscode/webview/src/views/health/App.tsx
+++ b/packages/vscode/webview/src/views/health/App.tsx
@@ -27,7 +27,11 @@ import { scoreTextColor } from "@repowise-dev/ui/health/tokens";
import { OverviewSection } from "@repowise-dev/ui/overview";
import type { HealthFileMetric } from "@repowise-dev/types/health";
import type { ViewProps } from "../../runtime/mount";
-import { useChurnLens, useDashboardData, type DashboardData } from "./useDashboardData";
+import {
+ useChurnLens,
+ useDashboardData,
+ type DashboardData,
+} from "./useDashboardData";
import { DashboardError, DashboardSkeleton } from "./chrome";
/**
@@ -130,6 +134,18 @@ function Dashboard({
onSelectFile={(path) => host.openFile(path)}
minHeight={MAP_HEIGHT}
chrome="none"
+ scope={{
+ shown: mapFiles.shown,
+ eligible: mapFiles.eligible_total,
+ repository: mapFiles.repository_total,
+ cap: mapFiles.cap,
+ omitted: {
+ files: mapFiles.omitted.files,
+ performanceFiles: mapFiles.omitted.performance_files,
+ opportunities: mapFiles.omitted.opportunities,
+ observations: mapFiles.omitted.observations,
+ },
+ }}
/>
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">
{/* A key describing bands the field cannot be showing is worse
@@ -143,9 +159,6 @@ function Dashboard({
) : (
<MapLegend overlay={overlay} loading={churnLoading} />
)}
- <span className="font-mono text-[10px] uppercase tracking-[0.12em] tabular-nums text-[var(--color-text-tertiary)]">
- {mapFiles.total.toLocaleString()} files
- </span>
</div>
</div>
</OverviewSection>
diff --git a/packages/vscode/webview/src/views/health/useDashboardData.ts b/packages/vscode/webview/src/views/health/useDashboardData.ts
index 70a061750..bdf792ac6 100644
--- a/packages/vscode/webview/src/views/health/useDashboardData.ts
+++ b/packages/vscode/webview/src/views/health/useDashboardData.ts
@@ -8,7 +8,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import type {
ChurnComplexityResponse,
HealthOverviewResponse,
- HealthFilesResponse,
+ HealthMapFeed,
HealthTrendResponse,
} from "@repowise-dev/types/health";
import type { WebviewHost } from "../../runtime/rpc";
@@ -30,7 +30,7 @@ const CHURN_POINT_LIMIT = 5000;
export interface DashboardData {
overview: HealthOverviewResponse;
- files: HealthFilesResponse;
+ files: HealthMapFeed;
trend: HealthTrendResponse;
}
@@ -58,7 +58,7 @@ export function useDashboardData(host: WebviewHost, refreshToken: number): Dashb
Promise.all([
host.api.healthOverview(OVERVIEW_LIMIT),
- host.api.healthFiles({ limit: MAP_FILE_LIMIT, sort: "nloc", order: "desc" }),
+ host.api.healthMap({ cap: MAP_FILE_LIMIT }),
host.api.healthTrend(TREND_LIMIT),
])
.then(([overview, files, trend]) => {
@@ -95,9 +95,9 @@ export function useDashboardData(host: WebviewHost, refreshToken: number): Dashb
*/
export function useChurnLens(
host: WebviewHost,
- files: HealthFilesResponse,
+ files: HealthMapFeed,
wanted: boolean,
-): { files: HealthFilesResponse; loading: boolean; failed: boolean } {
+): { files: HealthMapFeed; loading: boolean; failed: boolean } {
const [churn, setChurn] = useState<ChurnComplexityResponse | null>(null);
const [failed, setFailed] = useState(false);
// Unmount, not lens-change. Cancelling when the reader switches away would
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 267a4bd39..1e5c66edb 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -58,14 +58,15 @@ import { getDeadCodeSummary } from "@/lib/api/dead-code";
import {
getChurnComplexity,
getHealthCoverage,
+ getHealthMap,
getHealthOverview,
getHealthTrend,
- listHealthFiles,
+ getPerformanceOpportunity,
type ChurnComplexityResponse,
type HealthCoverageResponse,
+ type HealthMapFeed,
type HealthOverviewResponse,
type HealthTrendResponse,
- type HealthFilesResponse,
} from "@/lib/api/code-health";
const TABS = [
@@ -125,8 +126,13 @@ const TAB_ALIASES: Record<string, TabId> = {
*/
const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];
-/** Files pulled for the map: biggest first, capped so the galaxy stays legible. */
-const MAP_FILE_LIMIT = 2000;
+/**
+ * Nodes the map draws. The server chooses which ones: the selected file first,
+ * then every file carrying an open performance cause in rank order, then the
+ * biggest files fill the rest. Ranking by size alone used to push tens of
+ * files with open causes off the field entirely.
+ */
+const MAP_CAP = 2000;
/**
* Churn points pulled for the churn lens. Deliberately larger than
* `MAP_FILE_LIMIT`: the map ranks by NLOC and churn-complexity ranks by
@@ -150,16 +156,33 @@ export default function CodeHealthPage() {
const searchParams = useSearchParams();
const repoId = params.id;
+ // `?pillar=` predates the lens and the performance tab: the Overview health
+ // card still links with it. Performance now has a tab of its own and the
+ // other two are lenses, so the parameter resolves onto whichever surface
+ // actually answers it rather than onto a control that no longer exists.
+ const rawPillar = searchParams.get("pillar");
+
const rawTab = searchParams.get("tab");
const aliased = rawTab ? TAB_ALIASES[rawTab] : undefined;
const activeTab: TabId =
aliased ??
- (rawTab && (TABS as readonly string[]).includes(rawTab) ? (rawTab as TabId) : "triage");
+ (rawTab && (TABS as readonly string[]).includes(rawTab)
+ ? (rawTab as TabId)
+ : rawPillar === "performance"
+ ? "performance"
+ : "triage");
const rawLens = searchParams.get("lens");
const overlay: CodeHealthOverlay = (OVERLAYS as readonly string[]).includes(rawLens ?? "")
? (rawLens as CodeHealthOverlay)
- : "health";
+ : rawPillar === "maintainability"
+ ? "maintainability"
+ : "health";
+
+ // The map's selection and its opportunity highlight live in the URL, so a
+ // link from the performance queue opens this field on the file it is about.
+ const selectedPath = searchParams.get("file");
+ const opportunityId = searchParams.get("opportunity");
// Shares the SWR key with TriageView — the meta line and the findings count
// cost no extra request.
@@ -194,20 +217,39 @@ export default function CodeHealthPage() {
revalidateOnFocus: false,
});
- // Every file (NLOC-first) for the map — one big pull, shared across overlays
- // so switching the lens never refetches. `fields: "summary"` because the map
- // and the spotlight read none of the lead/detail keys: at 2,000 rows the full
- // shape was 1.06 MB, about 432 KB of it keys nobody here touches.
- const { data: mapFiles } = useSWR<HealthFilesResponse>(
- `code-health-map-files:${repoId}`,
+ // The opportunity a link arrived with, so its files can be guaranteed a node
+ // and marked. One bounded request, and only when the link carries an id.
+ const { data: opportunity } = useSWR(
+ opportunityId ? `code-health-map-opportunity:${repoId}:${opportunityId}` : null,
+ () => getPerformanceOpportunity(repoId, opportunityId as string, { evidenceLimit: 25 }),
+ { revalidateOnFocus: false },
+ );
+
+ // The intervention file plus the files its evidence sits in. An id from a
+ // retired model resolves to a state rather than to a row, and that shape
+ // carries no paths, so it simply marks nothing.
+ const highlightPaths = useMemo(() => {
+ if (!opportunity || !("file_path" in opportunity)) return undefined;
+ const paths = [opportunity.file_path, ...opportunity.evidence.map((e) => e.file_path)];
+ return [...new Set(paths.filter(Boolean))];
+ }, [opportunity]);
+
+ // The bounded field: one pull, shared across lenses so switching never
+ // refetches. The paths the page needs on screen ride along as `active`, which
+ // is what makes the guarantee a server-side one rather than a hope that the
+ // size ranking happened to include them.
+ const activePaths = useMemo(
+ () => [...new Set([...(selectedPath ? [selectedPath] : []), ...(highlightPaths ?? [])])],
+ [selectedPath, highlightPaths],
+ );
+ const { data: mapFeed } = useSWR<HealthMapFeed>(
+ `code-health-map:${repoId}:${activePaths.join(",")}`,
() =>
- listHealthFiles(repoId, {
- limit: MAP_FILE_LIMIT,
- sort: "nloc",
- order: "desc",
- fields: "summary",
+ getHealthMap(repoId, {
+ cap: MAP_CAP,
+ ...(activePaths.length ? { active: activePaths } : {}),
}),
- { revalidateOnFocus: false },
+ { revalidateOnFocus: false, keepPreviousData: true },
);
// Churn percentiles for the churn lens. Fetched only once that lens is
@@ -223,17 +265,17 @@ export default function CodeHealthPage() {
// Join churn onto the map rows by path. Until it lands every node would be
// neutral, so the legend is told it is loading rather than letting an
// all-grey field read as "no churn anywhere".
- const mapFilesWithChurn: HealthFilesResponse | undefined = useMemo(() => {
- if (!mapFiles || !churn) return mapFiles;
+ const mapFeedWithChurn: HealthMapFeed | undefined = useMemo(() => {
+ if (!mapFeed || !churn) return mapFeed;
const byPath = new Map(churn.points.map((p) => [p.file_path, p.churn_percentile]));
return {
- ...mapFiles,
- files: mapFiles.files.map((file) => ({
+ ...mapFeed,
+ files: mapFeed.files.map((file) => ({
...file,
churn_percentile: byPath.get(file.file_path) ?? null,
})),
};
- }, [mapFiles, churn]);
+ }, [mapFeed, churn]);
// ---- Tab counts ----
// Dead code uses the same key + fetcher as its own tab, so this is a prefetch
@@ -279,6 +321,17 @@ export default function CodeHealthPage() {
[router, searchParams],
);
+ const setSelectedPath = useCallback(
+ (next: string | null) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next) sp.set("file", next);
+ else sp.delete("file");
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
const setOverlay = useCallback(
(next: CodeHealthOverlay) => {
const sp = new URLSearchParams(searchParams.toString());
@@ -338,8 +391,11 @@ export default function CodeHealthPage() {
overlay={overlay}
onOverlayChange={setOverlay}
lenses={OVERLAYS}
- mapFiles={mapFilesWithChurn}
+ mapFeed={mapFeedWithChurn}
overlayLoading={churnWanted && churnLoading && !churn}
+ selectedPath={selectedPath}
+ onSelectPath={setSelectedPath}
+ highlightPaths={highlightPaths}
hotspotsSlot={<HotspotsSection repoId={repoId} />}
trendSlot={
<OverviewSection
diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsx
index 8433d761e..794fe59ef 100644
--- a/packages/web/src/components/code-health/performance-tab.tsx
+++ b/packages/web/src/components/code-health/performance-tab.tsx
@@ -14,6 +14,8 @@ import { getRefactoringPlan } from "@/lib/api/refactoring";
/** The queue's own filter state, kept out of the page's `tab` and `lens`. */
const FILTER_PARAM = "perf";
+/** Shared with the map, which uses the same name to pin a cause's files. */
+const OPPORTUNITY_PARAM = "opportunity";
export function PerformanceTab({ repoId }: { repoId: string }) {
const router = useRouter();
@@ -33,6 +35,11 @@ export function PerformanceTab({ repoId }: { repoId: string }) {
getRefactoringPlan: (planId) => getRefactoringPlan(repoId, planId),
refactoringPlanHref: (planId) =>
`/repos/${repoId}/refactoring?type=performance_fix&plan=${encodeURIComponent(planId)}`,
+ // Onto the one galaxy, on the performance lens, with the cause's files
+ // pinned. The map guarantees them a node rather than hoping the size
+ // ranking happened to include them.
+ mapHref: (opportunityId, filePath) =>
+ `/repos/${repoId}/code-health?lens=performance&opportunity=${encodeURIComponent(opportunityId)}&file=${encodeURIComponent(filePath)}`,
fileHref: (path) => fileEntityPath(prefix, path),
symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
navigate: (href) => router.push(href),
@@ -52,11 +59,27 @@ export function PerformanceTab({ repoId }: { repoId: string }) {
[router, searchParams],
);
+ // The open cause rides in the URL beside the filters, so the link the map
+ // and the file drawer mint opens it, and so an inspected cause is itself a
+ // link worth sending to somebody.
+ const onOpenOpportunityChange = useCallback(
+ (opportunityId: string | null) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (opportunityId) sp.set(OPPORTUNITY_PARAM, opportunityId);
+ else sp.delete(OPPORTUNITY_PARAM);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
return (
<PerformanceView
adapter={adapter}
initialFilters={searchParams.get(FILTER_PARAM) ?? undefined}
onFiltersChange={onFiltersChange}
+ openOpportunityId={searchParams.get(OPPORTUNITY_PARAM)}
+ onOpenOpportunityChange={onOpenOpportunityChange}
/>
);
}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
index 03abe8cf5..1726b481c 100644
--- a/packages/web/src/components/code-health/triage-tab.tsx
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -7,14 +7,12 @@
* pieces so web and hosted render the same view.
*/
-import { useCallback } from "react";
import type { ReactNode } from "react";
-import { useRouter, useSearchParams } from "next/navigation";
+import { useRouter } from "next/navigation";
import {
TriageView,
type CodeHealthAdapter,
type CodeHealthOverlay,
- type HealthPillar,
} from "@repowise-dev/ui/health";
import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";
import {
@@ -25,7 +23,7 @@ import {
getHealthCoverage,
updateFindingStatus,
type HealthTrendResponse,
- type HealthFilesResponse,
+ type HealthMapFeed,
} from "@/lib/api/code-health";
import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
@@ -35,8 +33,11 @@ export function TriageTab({
overlay = "health",
onOverlayChange,
lenses,
- mapFiles,
+ mapFeed,
overlayLoading,
+ selectedPath,
+ onSelectPath,
+ highlightPaths,
hotspotsSlot,
trendSlot,
}: {
@@ -48,36 +49,20 @@ export function TriageTab({
onOverlayChange?: (overlay: CodeHealthOverlay) => void;
/** Lenses offered in the switcher, including any the page joined in. */
lenses?: CodeHealthOverlay[];
- /** Map files fetched once at the page level (shared across overlays). */
- mapFiles?: HealthFilesResponse;
+ /** The bounded field, fetched once at the page level and shared by lenses. */
+ mapFeed?: HealthMapFeed;
/** The active lens's per-file signal is still loading (e.g. churn). */
overlayLoading?: boolean;
+ /** Selection, URL-synced by the page so a link can open one file. */
+ selectedPath?: string | null;
+ onSelectPath?: (path: string | null) => void;
+ /** Extra paths to mark, for a link into one opportunity's files. */
+ highlightPaths?: string[];
/** Sections composed by the page and rendered under the map. */
hotspotsSlot?: ReactNode;
trendSlot?: ReactNode;
}) {
const router = useRouter();
- const searchParams = useSearchParams();
-
- // Pillar is URL-synced (?pillar=) so the Overview + KPI tiles can deep-link
- // straight into a single dimension's findings.
- const rawPillar = searchParams.get("pillar");
- const pillar: HealthPillar =
- rawPillar === "defect" ||
- rawPillar === "maintainability" ||
- rawPillar === "performance"
- ? rawPillar
- : "all";
- const onPillarChange = useCallback(
- (next: HealthPillar) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "all") sp.delete("pillar");
- else sp.set("pillar", next);
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
const prefix = `/repos/${id}`;
const adapter: CodeHealthAdapter = {
@@ -92,8 +77,13 @@ export function TriageTab({
fileHref: (path) => fileEntityPath(prefix, path),
symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
navigate: (href) => router.push(href),
- renderFileDrawer: ({ filePath, onClose }) => (
- <HealthFileDrawerHost repoId={id} filePath={filePath} onClose={onClose} />
+ renderFileDrawer: ({ filePath, onClose, lens }) => (
+ <HealthFileDrawerHost
+ repoId={id}
+ filePath={filePath}
+ onClose={onClose}
+ {...(lens ? { lens } : {})}
+ />
),
};
@@ -104,10 +94,11 @@ export function TriageTab({
overlay={overlay}
onOverlayChange={onOverlayChange}
lenses={lenses}
- mapFiles={mapFiles}
+ mapFeed={mapFeed}
overlayLoading={overlayLoading}
- pillar={pillar}
- onPillarChange={onPillarChange}
+ selectedPath={selectedPath}
+ onSelectPath={onSelectPath}
+ highlightPaths={highlightPaths}
hotspotsSlot={hotspotsSlot}
trendSlot={trendSlot}
/>
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 3ccf5cf0b..55add4723 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -1,24 +1,49 @@
"use client";
+import useSWR from "swr";
+import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { HealthFileDrawer } from "@repowise-dev/ui/health";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
-import { updateFindingStatus } from "@/lib/api/code-health";
+import {
+ getPerformanceOpportunities,
+ updateFindingStatus,
+} from "@/lib/api/code-health";
import { useFileBreakdown } from "./use-file-breakdown";
+/** Causes listed for one file. A file with more than this is its own queue. */
+const FILE_CAUSE_LIMIT = 10;
+
export function HealthFileDrawerHost({
repoId,
filePath,
onClose,
+ lens,
}: {
repoId: string;
filePath: string | null;
onClose: () => void;
+ /** The surface the file was opened from; drives what the drawer leads with. */
+ lens?: string;
}) {
+ const router = useRouter();
const { data, isLoading } = useFileBreakdown(repoId, filePath);
const prefix = `/repos/${repoId}`;
const filePageHref = filePath ? fileEntityPath(prefix, filePath) : undefined;
+ // Scoped to the one file, by the server. Fetched only from the performance
+ // lens, so opening a file from anywhere else costs the request it always did.
+ const wantsCauses = lens === "performance" && filePath !== null;
+ const { data: causes, isLoading: causesLoading } = useSWR(
+ wantsCauses ? `file-performance-causes:${repoId}:${filePath}` : null,
+ () =>
+ getPerformanceOpportunities(repoId, {
+ file_paths: [filePath as string],
+ limit: FILE_CAUSE_LIMIT,
+ }),
+ { revalidateOnFocus: false },
+ );
+
return (
<HealthFileDrawer
open={filePath !== null}
@@ -38,6 +63,14 @@ export function HealthFileDrawerHost({
suggestions={data?.suggestions ?? {}}
trend={data?.trend ?? null}
signals={data?.signals ?? null}
+ lens={lens}
+ performance={
+ wantsCauses && causes ? { items: causes.items, total: causes.total } : null
+ }
+ performanceLoading={causesLoading}
+ onOpportunitySelect={(opportunityId) =>
+ router.push(`/repos/${repoId}/code-health?tab=performance&opportunity=${encodeURIComponent(opportunityId)}`)
+ }
permalinkHref={filePageHref ? `${filePageHref}?tab=health` : undefined}
fileViewHref={filePageHref}
fileViewHrefFor={
diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
index 35b009080..072a87a6c 100644
--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
@@ -519,7 +519,14 @@ async def test_canonical_emitter_reference_inventory(reference_repo, health_data
"get_change_risk": (get_change_risk, ("HEAD",), {"baseline": 0}),
"get_context": (get_context, (["src/auth/service.py"],), {"include": ["decisions"]}),
"get_dead_code": (get_dead_code, (), {"min_confidence": "low"}),
- "get_health": (get_health, (), {"include": ["biomarkers", "refactoring"]}),
+ # Every block this emitter can produce, so the inventory sees every
+ # reference kind it can mint. The only fixture finding whose function
+ # resolves to a symbol is the performance one.
+ "get_health": (
+ get_health,
+ (),
+ {"include": ["biomarkers", "refactoring", "performance"]},
+ ),
"get_overview": (get_overview, (), {"include": ["decisions"]}),
"get_risk": (get_risk, (["src/auth/service.py"],), {}),
"get_symbol": (get_symbol, ("src/auth/service.py:1-750",), {}),
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 83d2eb83e..712025066 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -27,7 +27,11 @@ async def test_get_health_dashboard(setup_mcp, health_data):
assert "high_leverage_files" in result
assert "worst_files" not in result
assert result["secondary_rankings"]["worst_files"]["total"] == 2
- assert result["secondary_rankings"]["top_findings"]["total"] == 4
+ # Three, not four: the impact ranking carries defect and maintainability
+ # work. The performance finding scores zero impact by construction, and a
+ # row that cannot rank is not a rank. It leads the response instead, in
+ # `performance_directive`.
+ assert result["secondary_rankings"]["top_findings"]["total"] == 3
assert "omitted" not in result["_meta"]
@@ -116,8 +120,9 @@ async def test_get_health_dashboard_surfaces_maintainability(setup_mcp, health_d
assert worst["maintainability_score"] == 6.0
assert worst["performance_score"] == 9.0
# Findings are tagged with their home pillar so they can be filtered.
+ # Performance is not in the impact ranking: it has no impact to rank by.
dims = {f["dimension"] for f in result["top_findings"]}
- assert dims == {"defect", "maintainability", "performance"}
+ assert dims == {"defect", "maintainability"}
@pytest.mark.asyncio
@@ -129,8 +134,10 @@ async def test_get_health_dashboard_surfaces_performance(setup_mcp, health_data)
# Repo-level KPI headline for the performance pillar.
# NLOC-weighted: (9.0*200 + 10.0*50) / 250 = 9.2.
assert result["kpis"]["performance_average"] == 9.2
- # The perf finding carries its boundary kind + cross-function reachability path.
- perf = [f for f in result["top_findings"] if f["dimension"] == "performance"]
+ # The perf finding carries its boundary kind + cross-function reachability
+ # path. Asked for by name, because the impact ranking above excludes it.
+ ranked = await get_health(include=["performance"], only=["top_findings"])
+ perf = [f for f in ranked["top_findings"] if f["dimension"] == "performance"]
assert len(perf) == 1
details = perf[0]["details"]
assert details["boundary_kind"] == "db"
@@ -542,11 +549,11 @@ async def test_get_health_findings_capped_with_honest_total(setup_mcp, health_da
result = await get_health(targets=["src/auth/service.py"], limit=2)
assert len(result["findings"]) == 2
- assert result["findings_total"] == 4
+ assert result["findings_total"] == 3
dash = await get_health(only=["top_findings"], limit=2)
assert len(dash["top_findings"]) == 2
- assert dash["top_findings_total"] == 4
+ assert dash["top_findings_total"] == 3
@pytest.mark.asyncio
@@ -872,7 +879,7 @@ async def test_get_health_biomarkers_block_is_capped(setup_mcp, health_data):
result = await get_health(include=["biomarkers"], limit=2)
assert len(result["findings"]) == 2
# The cap is visible rather than inferred from the length.
- assert result["findings_total"] == 4
+ assert result["findings_total"] == 3
# Impact-ordered, so the cap keeps the findings worth reading.
impacts = [f["health_impact"] for f in result["findings"]]
assert impacts == sorted(impacts, reverse=True)
@@ -890,11 +897,11 @@ async def test_get_health_totals_survive_the_cap(setup_mcp, health_data):
capped = await get_health(only=["top_findings"], limit=1)
assert len(capped["top_findings"]) == 1
- assert capped["top_findings_total"] == 4
+ assert capped["top_findings_total"] == 3
scoped = await get_health(targets=["src/auth/service.py"], limit=1)
assert len(scoped["findings"]) == 1
- assert scoped["findings_total"] == 4
+ assert scoped["findings_total"] == 3
@pytest.mark.asyncio
@@ -1358,10 +1365,12 @@ async def test_test_findings_get_their_own_bucket(setup_mcp, health_data_with_te
assert all(f["file_path"] != "tests/test_service.py" for f in result["top_findings"])
assert result["top_findings"][0]["file_path"] == "src/auth/service.py"
- # Nothing is lost: the two buckets partition the whole open set.
+ # Nothing that ranks is lost: the two buckets partition the impact-ranked
+ # set, which is defect and maintainability work. The fixture's performance
+ # finding is in neither, because it carries no impact to rank by.
assert result["test_findings_total"] == 2
- assert result["top_findings_total"] == 4
- assert result["top_findings_total"] + result["test_findings_total"] == 6
+ assert result["top_findings_total"] == 3
+ assert result["top_findings_total"] + result["test_findings_total"] == 5
@pytest.mark.asyncio
@@ -1378,7 +1387,7 @@ async def test_each_bucket_is_capped_against_its_own_population(setup_mcp, healt
result = await get_health(only=["top_findings", "test_findings"], limit=2)
assert len(result["top_findings"]) == 2
assert len(result["test_findings"]) == 2
- assert result["top_findings_total"] == 4
+ assert result["top_findings_total"] == 3
@pytest.mark.asyncio
@@ -2250,3 +2259,23 @@ async def test_every_growing_collection_has_total_and_emitted_counts(
assert_counted(child)
assert_counted(result)
+
+
+async def test_the_ranked_findings_leave_performance_out_but_asking_returns_it(
+ setup_mcp, health_data
+):
+ """A ranking by impact is not a place to put rows that carry none.
+
+ Every performance finding scores zero impact by construction, so in a mixed
+ list it sorts below every defect row and reads as a tail rather than as a
+ different unit. The dimension answers through its own blocks, and naming it
+ in ``include`` still returns the rows.
+ """
+ from repowise.server.mcp_server import get_health
+
+ default = await get_health(only=["top_findings"])
+ assert all(f["dimension"] != "performance" for f in default["top_findings"])
+
+ asked = await get_health(include=["performance"], only=["top_findings"])
+ assert any(f["dimension"] == "performance" for f in asked["top_findings"])
diff --git a/tests/unit/server/mcp/test_perf_rank.py b/tests/unit/server/mcp/test_perf_rank.py
index e590462e7..8f4946273 100644
--- a/tests/unit/server/mcp/test_perf_rank.py
+++ b/tests/unit/server/mcp/test_perf_rank.py
@@ -251,7 +251,12 @@ async def test_perf_rank_is_absent_from_every_other_dimension(setup_mcp, perf_fi
would read as "measured, and it is nothing"."""
from repowise.server.mcp_server import get_health
- result = await get_health(include=["biomarkers"], limit=50)
+ # Naming the dimension, because the impact-ranked list leaves it out by
+ # default: every performance finding scores zero impact, so a ranking by
+ # impact is not where it belongs.
+ result = await get_health(
+ include=["biomarkers", "defect", "maintainability", "performance"], limit=50
+ )
by_dim = {}
for f in result["findings"]:
by_dim.setdefault(f["dimension"], []).append(f)
diff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.py
index 5b0cb2b67..8b23114d2 100644
--- a/tests/unit/server/mcp/test_performance_levels.py
+++ b/tests/unit/server/mcp/test_performance_levels.py
@@ -422,6 +422,7 @@ async def test_rest_and_the_agent_surface_project_the_same_rows(
actionability=None,
view="detail",
sort="rank",
+ file_paths=None,
limit=6,
offset=0,
session=session,
diff --git a/tests/unit/server/test_findings_performance_exclusion.py b/tests/unit/server/test_findings_performance_exclusion.py
new file mode 100644
index 000000000..7dddcad0f
--- /dev/null
+++ b/tests/unit/server/test_findings_performance_exclusion.py
@@ -0,0 +1,101 @@
+"""Performance stays out of the impact-ranked queues, and reachable on request.
+
+Every performance finding carries a health impact of zero by construction, so a
+list ordered by impact sorts them below every defect row. That is not a ranking
+of performance work, it is a tail nobody reads, and it renders as a deduction
+that rounded away. The dimension answers on its own surfaces instead.
+"""
+
+from __future__ import annotations
+
+from httpx import AsyncClient
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.persistence import crud
+from tests.unit.server.conftest import create_test_repo
+
+
+def _finding(path: str, dimension: str, impact: float) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop" if dimension == "performance" else "complex_method",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=1,
+ line_end=2,
+ details={},
+ health_impact=impact,
+ reason="reason",
+ dimension=dimension,
+ )
+
+
+def _metric(path: str) -> dict:
+ return {
+ "file_path": path,
+ "score": 7.0,
+ "max_ccn": 3,
+ "max_nesting": 2,
+ "nloc": 40,
+ "duplication_pct": 0.0,
+ "has_test_file": False,
+ "line_coverage_pct": None,
+ "branch_coverage_pct": None,
+ "module": "src",
+ }
+
+
+async def _seed(app, client: AsyncClient) -> str:
+ repo = await create_test_repo(client)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(
+ session, repo["id"], [_metric(f"src/{n}.py") for n in "abc"]
+ )
+ await crud.save_health_findings(
+ session,
+ repo["id"],
+ [
+ _finding("src/a.py", "defect", 2.5),
+ _finding("src/b.py", "maintainability", 1.0),
+ _finding("src/c.py", "performance", 0.0),
+ ],
+ )
+ await session.commit()
+ return repo["id"]
+
+
+async def test_the_unfiltered_findings_list_leaves_performance_out(app, client):
+ repo_id = await _seed(app, client)
+ rows = (await client.get(f"/api/repos/{repo_id}/health/findings")).json()
+ assert {r["dimension"] for r in rows} == {"defect", "maintainability"}
+
+
+async def test_asking_for_the_dimension_still_returns_it(app, client):
+ repo_id = await _seed(app, client)
+ rows = (
+ await client.get(
+ f"/api/repos/{repo_id}/health/findings", params={"dimension": "performance"}
+ )
+ ).json()
+ assert [r["file_path"] for r in rows] == ["src/c.py"]
+
+
+async def test_a_null_dimension_still_reads_as_defect_work(app, client):
+ """Rows written before the split carry NULL, and NULL homes under defect."""
+ repo = await create_test_repo(client)
+ async with app.state.session_factory() as session:
+ finding = _finding("src/legacy.py", "defect", 1.5)
+ finding.dimension = None
+ await crud.save_health_findings(session, repo["id"], [finding])
+ await session.commit()
+ rows = (await client.get(f"/api/repos/{repo['id']}/health/findings")).json()
+ assert [r["file_path"] for r in rows] == ["src/legacy.py"]
+
+
+async def test_the_overview_queue_leaves_performance_out_but_still_counts_it(app, client):
+ repo_id = await _seed(app, client)
+ overview = (await client.get(f"/api/repos/{repo_id}/health/overview")).json()
+ assert all(f["dimension"] != "performance" for f in overview["top_findings"])
+ # The rollups above the queue still see every dimension: excluding a row
+ # from a ranking is not the same as pretending it does not exist.
+ assert overview["summary"]["open_findings"] == 3
diff --git a/tests/unit/server/test_health_map_feed.py b/tests/unit/server/test_health_map_feed.py
new file mode 100644
index 000000000..6ecfc84e9
--- /dev/null
+++ b/tests/unit/server/test_health_map_feed.py
@@ -0,0 +1,206 @@
+"""The bounded field the map draws, and what it says about what it left out.
+
+A cap is a claim. These cases pin the two halves of that claim: which files the
+server admits and in which order, and whether the counts it publishes describe
+the rows it actually returned.
+"""
+
+from __future__ import annotations
+
+from httpx import AsyncClient
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.analysis.health.perf.opportunities import link_performance_findings
+from repowise.core.persistence import crud
+from tests.unit.server.conftest import create_test_repo
+
+
+def _metric(path: str, nloc: int, module: str = "src") -> dict:
+ return {
+ "file_path": path,
+ "score": 7.0,
+ "max_ccn": 3,
+ "max_nesting": 2,
+ "nloc": nloc,
+ "duplication_pct": 0.0,
+ "has_test_file": False,
+ "line_coverage_pct": None,
+ "branch_coverage_pct": None,
+ "module": module,
+ }
+
+
+def _perf_finding(path: str, line: int, path_nodes: list[str]) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=line,
+ line_end=line,
+ details={
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": path_nodes,
+ "resolution_basis": "reliable-edge",
+ },
+ health_impact=0.0,
+ reason="Database work repeats for every loop iteration.",
+ dimension="performance",
+ )
+
+
+async def _seed(app, client: AsyncClient) -> str:
+ """One big clean file, and one tiny file carrying the repository's cause.
+
+ The tiny file is the whole point: a size ranking puts it last, and it is
+ where the work is.
+ """
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ metrics = [_metric(f"src/big{i}.py", 1000 - i) for i in range(5)]
+ metrics.append(_metric("src/tiny.py", 3))
+ findings = [
+ _perf_finding("src/tiny.py", 10, ["src/tiny.py::run", "src/db.py::fetch"]),
+ _perf_finding("src/tiny.py", 20, ["src/tiny.py::run", "src/db.py::fetch"]),
+ ]
+ link_performance_findings(findings)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(session, repo_id, metrics)
+ await crud.save_health_findings(session, repo_id, findings)
+ await crud.finalize_performance_opportunities(
+ session, repo_id, analyzed_commit="a" * 40
+ )
+ await session.commit()
+ return repo_id
+
+
+async def _feed(client: AsyncClient, repo_id: str, **params) -> dict:
+ return (await client.get(f"/api/repos/{repo_id}/health/map", params=params)).json()
+
+
+async def test_a_small_file_with_a_cause_outranks_a_large_clean_one(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=2)
+ drawn = [f["file_path"] for f in feed["files"]]
+ assert "src/tiny.py" in drawn
+ assert feed["selection"]["basis"] == "active_then_performance_then_nloc"
+ assert feed["selection"]["performance_shown"] == 1
+ # The remaining slot went to the size sample, in size order.
+ assert feed["selection"]["nloc_shown"] == 1
+ assert "src/big0.py" in drawn
+
+
+async def test_the_active_selection_is_admitted_before_anything_else(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=1, active="src/big4.py")
+ assert [f["file_path"] for f in feed["files"]] == ["src/big4.py"]
+ assert feed["selection"]["active_shown"] == ["src/big4.py"]
+ # The cap is now spent, and the response says what that cost.
+ assert feed["omitted"]["performance_files"] == 1
+ assert feed["omitted"]["opportunities"] >= 1
+
+
+async def test_a_pinned_path_the_index_does_not_hold_is_named_not_faked(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=5, active="src/does-not-exist.py")
+ assert feed["selection"]["active_missing"] == ["src/does-not-exist.py"]
+ assert all(f["file_path"] != "src/does-not-exist.py" for f in feed["files"])
+
+
+async def test_the_counts_describe_the_rows_that_came_back(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=3)
+ assert feed["shown"] == len(feed["files"]) == 3
+ assert feed["eligible_total"] == 6
+ assert feed["omitted"]["files"] == feed["eligible_total"] - feed["shown"]
+
+
+async def test_nothing_is_omitted_once_the_cap_clears_the_repository(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=100)
+ assert feed["omitted"] == {
+ "files": 0,
+ "performance_files": 0,
+ "opportunities": 0,
+ "observations": 0,
+ }
+
+
+async def test_rows_carry_the_burden_the_lens_rings_by(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=100)
+ tiny = next(f for f in feed["files"] if f["file_path"] == "src/tiny.py")
+ assert tiny["performance_opportunities"] >= 1
+ assert tiny["performance_observations"] == 2
+ assert tiny["performance_actionability"] in {"plan_ready", "advisory", "investigate"}
+ big = next(f for f in feed["files"] if f["file_path"] == "src/big0.py")
+ # Present and zero, never absent: absent is how the lens recognizes a
+ # server with no read model, and it must not read that as a clear file.
+ assert big["performance_opportunities"] == 0
+ assert "performance_actionability" not in big
+
+
+async def test_the_repository_block_reports_what_the_lens_can_say(app, client):
+ repo_id = await _seed(app, client)
+ feed = await _feed(client, repo_id, cap=100)
+ perf = feed["performance"]
+ assert perf["files_with_opportunities"] == 1
+ assert perf["opportunities_total"] >= 1
+ assert sum(perf["actionability"].values()) == perf["opportunities_total"]
+ assert perf["analyzed_commit"] == "a" * 40
+
+
+async def test_an_unanalyzed_repository_reports_no_performance_block(app, client):
+ repo = await create_test_repo(client)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(session, repo["id"], [_metric("src/a.py", 10)])
+ await session.commit()
+ feed = await _feed(client, repo["id"], cap=10)
+ # Not an empty rollup: "never analyzed" and "analyzed and clear" are
+ # different answers and the lens draws them differently.
+ assert feed["performance"] is None
+
+
+async def test_the_selection_is_stable_across_two_reads(app, client):
+ repo_id = await _seed(app, client)
+ first = await _feed(client, repo_id, cap=4)
+ second = await _feed(client, repo_id, cap=4)
+ assert [f["file_path"] for f in first["files"]] == [
+ f["file_path"] for f in second["files"]
+ ]
+
+
+async def test_the_cap_is_bounded(app, client):
+ repo_id = await _seed(app, client)
+ assert (
+ await client.get(f"/api/repos/{repo_id}/health/map", params={"cap": 99999})
+ ).status_code == 422
+
+
+async def test_a_cause_on_an_unsizeable_file_is_not_reported_as_capped_out(app, client):
+ """The omission counts describe what raising the cap would recover.
+
+ A file with no lines cannot be drawn at any cap and cannot be pinned into
+ the field either, so counting its cause under ``performance_files`` would
+ attach it to a recovery that does not exist.
+ """
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ metrics = [_metric("src/real.py", 100), _metric("src/empty.py", 0)]
+ findings = [_perf_finding("src/empty.py", 5, ["src/empty.py::run", "src/db.py::fetch"])]
+ link_performance_findings(findings)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(session, repo_id, metrics)
+ await crud.save_health_findings(session, repo_id, findings)
+ await crud.finalize_performance_opportunities(session, repo_id)
+ await session.commit()
+
+ feed = await _feed(client, repo_id, cap=100)
+ assert feed["eligible_total"] == 1
+ assert feed["omitted"]["performance_files"] == 0
+ assert feed["selection"]["performance_eligible"] == 0
+ # The cause still exists and the response still counts it repository-wide,
+ # so it is absent from the field rather than absent from the product.
+ assert feed["performance"]["files_with_opportunities"] == 1
+ assert feed["performance"]["files_with_opportunities_eligible"] == 0
diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.py
index 8e2fabb0c..171470370 100644
--- a/tests/unit/server/test_performance_opportunities.py
+++ b/tests/unit/server/test_performance_opportunities.py
@@ -311,3 +311,29 @@ async def test_a_page_costs_the_page_not_the_repository(app, client: AsyncClient
assert page["total"] == 2
assert len(page["items"]) == 1
assert page["summary"]["total"] == 2
+
+
+async def test_the_queue_scopes_to_one_file_on_the_server(app, client):
+ """A file surface asks about one file rather than filtering a page.
+
+ The drawer that opens from the map's performance lens needs this file's
+ causes and no others. Narrowing a page it already received would show
+ whatever survived the cap, which is not the same question.
+ """
+ repo_id, _ = await _seed(app, client)
+ whole = await _page(client, repo_id, context="all")
+ # Scope to whichever file the grouping named as the place to intervene: the
+ # column is the intervention site, not every file the evidence touches.
+ target = whole["items"][0]["file_path"]
+ scoped = await _page(client, repo_id, context="all", file_paths=target)
+ assert scoped["total"] >= 1
+ assert {item["file_path"] for item in scoped["items"]} == {target}
+ # The whole queue is larger, so the scope is doing the work and not the cap.
+ assert whole["total"] > scoped["total"]
+
+
+async def test_a_file_with_no_cause_scopes_to_an_empty_queue(app, client):
+ repo_id, _ = await _seed(app, client)
+ page = await _page(client, repo_id, context="all", file_paths="src/nothing-here.py")
+ assert page["total"] == 0
+ assert page["items"] == []