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): show what other lenses hold for a file in the health drawers (#2847)

Raghav Chamadiya4ea2da53488b
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index 9b7e5d6b9..aeea7634d 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -25,11 +25,12 @@ import type {
ImpactEffortResponse,
HealthScope,
HealthCounts,
+ RelatedWorkResponse,
} from "@repowise-dev/types/health";
import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";
import type { AgentPromptFlavor, AgentPromptResponse } from "@repowise-dev/types/agent-prompts";
import type { Paginated } from "@repowise-dev/types";
-import { apiGet, apiPatch } from "./client";
+import { apiGet, apiPatch, apiPost } from "./client";
export type {
BiomarkerBreakdownRow,
@@ -79,6 +80,10 @@ export type {
RefactoringQuery,
RefactoringTarget,
RefactoringTargetsResponse,
+ RelatedWorkFile,
+ RelatedWorkItem,
+ RelatedWorkLens,
+ RelatedWorkResponse,
} from "@repowise-dev/types/health";
export async function getHealthOverview(
@@ -318,3 +323,13 @@ export async function getFixFirstItemPrompt(
{ flavor: opts.flavor, scope: opts.scope },
);
}
+
+/** What every other lens holds for these files (1 to 200, repo-relative). */
+export async function getRelatedWork(
+ repoId: string,
+ filePaths: string[],
+): Promise<RelatedWorkResponse> {
+ return apiPost<RelatedWorkResponse>(`/api/repos/${repoId}/health/related-work`, {
+ file_paths: filePaths,
+ });
+}
diff --git a/packages/core/src/repowise/core/analysis/related_work.py b/packages/core/src/repowise/core/analysis/related_work.py
new file mode 100644
index 000000000..4a66d9e2d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/related_work.py
@@ -0,0 +1,301 @@
+"""What the other lenses say about the same files.
+
+Each lens (findings, Fix first, refactoring, performance, dead code) ranks its
+own work; a reader in one drawer has no way to see that the file in front of
+them also has a plan, a performance cause or dead code. This folds rows the
+caller already read into one compact answer per file, so every surface links
+across lenses the same way.
+
+Session-free: rows arrive as ORM rows, SQL rows, dataclasses or wire dicts
+(read through :func:`~repowise.core.analysis.health.rows.field`) and nothing is
+re-derived. ``code_origin`` and ``deprecated`` are copied only when the row
+already carries them.
+
+A lens is one entry in :data:`_LENSES`: how to read a row's file, how to order
+rows, and how to project one onto the item shape. Another lens (migration
+groups, say) is one more entry and one more keyword argument.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterable, Sequence
+from dataclasses import dataclass
+from dataclasses import field as dc_field
+from typing import Any
+
+from repowise.core.analysis.change_health.identity import severity_rank
+from repowise.core.analysis.health.rows import detail_map, field
+
+#: Items kept per file per lens. The total still counts every row, so a hot
+#: file reports "5 of 40" rather than shipping 40.
+DEFAULT_PER_LENS_LIMIT = 5
+
+_LAST = 1 << 30
+
+
+@dataclass(frozen=True, slots=True)
+class RelatedItem:
+ lens: str
+ id: str
+ kind: str | None = None
+ title: str | None = None
+ symbol: str | None = None
+ severity: str | None = None
+ tier: str | None = None
+ rank: int | None = None
+ line: int | None = None
+ code_origin: str | None = None
+ deprecated: bool | None = None
+
+ def as_dict(self) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "lens": self.lens,
+ "id": self.id,
+ "kind": self.kind,
+ "title": self.title,
+ "symbol": self.symbol,
+ "severity": self.severity,
+ "tier": self.tier,
+ "rank": self.rank,
+ "line": self.line,
+ }
+ # Present only when the row carried them, so absent stays absent.
+ if self.code_origin is not None:
+ out["code_origin"] = self.code_origin
+ if self.deprecated is not None:
+ out["deprecated"] = self.deprecated
+ return out
+
+
+@dataclass(frozen=True, slots=True)
+class RelatedLens:
+ items: tuple[RelatedItem, ...]
+ total: int
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"items": [i.as_dict() for i in self.items], "total": self.total}
+
+
+@dataclass(frozen=True, slots=True)
+class RelatedFile:
+ file_path: str
+ #: Only lenses with at least one row, in :data:`LENSES` order.
+ lenses: dict[str, RelatedLens] = dc_field(default_factory=dict)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "file_path": self.file_path,
+ "lenses": {name: lens.as_dict() for name, lens in self.lenses.items()},
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class RelatedWork:
+ files: tuple[RelatedFile, ...]
+ per_lens_limit: int
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "files": [f.as_dict() for f in self.files],
+ "per_lens_limit": self.per_lens_limit,
+ }
+
+
+def _int(value: Any) -> int | None:
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
+
+
+def _or_last(value: Any) -> int:
+ """Sort key for an optional position: absent sorts after every real one."""
+ n = _int(value)
+ return _LAST if n is None else n
+
+
+def _flags(row: Any, details: dict[str, Any]) -> dict[str, Any]:
+ """``code_origin`` / ``deprecated`` from the row or its details, if there."""
+ out: dict[str, Any] = {}
+ origin = field(row, "code_origin", None) or details.get("code_origin")
+ if isinstance(origin, str):
+ out["code_origin"] = origin
+ deprecated = field(row, "deprecated", None)
+ if deprecated is None:
+ deprecated = details.get("deprecated")
+ if isinstance(deprecated, bool):
+ out["deprecated"] = deprecated
+ return out
+
+
+# -- lenses ---------------------------------------------------------------
+
+
+def _finding_item(row: Any) -> RelatedItem:
+ details = detail_map(row)
+ return RelatedItem(
+ lens="findings",
+ id=str(field(row, "id")),
+ kind=field(row, "biomarker_type"),
+ symbol=field(row, "function_name"),
+ severity=field(row, "severity"),
+ line=_int(field(row, "line_start")),
+ **_flags(row, details),
+ )
+
+
+def _finding_key(row: Any) -> tuple[Any, ...]:
+ return (
+ -severity_rank(field(row, "severity", "")),
+ _or_last(field(row, "line_start")),
+ str(field(row, "id", "")),
+ )
+
+
+def _fix_first_file(item: Any) -> str | None:
+ return field(field(item, "target"), "file_path")
+
+
+def _fix_first_item(item: Any) -> RelatedItem:
+ target = field(item, "target")
+ return RelatedItem(
+ lens="fix_first",
+ id=str(field(item, "id")),
+ kind=field(item, "kind"),
+ title=field(item, "title"),
+ symbol=field(target, "symbol"),
+ tier=field(item, "tier"),
+ rank=_int(field(item, "rank")),
+ line=_int(field(target, "line_start")),
+ )
+
+
+def _fix_first_key(item: Any) -> tuple[Any, ...]:
+ return (_or_last(field(item, "rank")), str(field(item, "id", "")))
+
+
+def _refactoring_item(row: Any) -> RelatedItem:
+ details = detail_map(row)
+ return RelatedItem(
+ lens="refactoring",
+ id=str(field(row, "opportunity_id")),
+ kind=field(row, "lead_refactoring_type"),
+ tier=field(row, "effort_bucket"),
+ rank=_int(field(row, "rank_position")),
+ **_flags(row, details),
+ )
+
+
+def _rank_key(row: Any) -> tuple[Any, ...]:
+ return (_or_last(field(row, "rank_position")), str(field(row, "opportunity_id", "")))
+
+
+def _performance_item(row: Any) -> RelatedItem:
+ details = detail_map(row)
+ return RelatedItem(
+ lens="performance",
+ id=str(field(row, "opportunity_id")),
+ kind=field(row, "biomarker_type"),
+ symbol=field(row, "intervention_symbol"),
+ tier=field(row, "actionability_state"),
+ rank=_int(field(row, "rank_position")),
+ **_flags(row, details),
+ )
+
+
+def _dead_code_item(row: Any) -> RelatedItem:
+ return RelatedItem(
+ lens="dead_code",
+ id=str(field(row, "id")),
+ kind=field(row, "kind"),
+ symbol=field(row, "symbol_name"),
+ tier="safe_to_delete" if field(row, "safe_to_delete", False) else "review",
+ line=_int(field(row, "start_line")),
+ **_flags(row, {}),
+ )
+
+
+def _dead_code_key(row: Any) -> tuple[Any, ...]:
+ return (
+ -float(field(row, "confidence", 0.0) or 0.0),
+ _or_last(field(row, "start_line")),
+ str(field(row, "id", "")),
+ )
+
+
+def _file_path(row: Any) -> str | None:
+ return field(row, "file_path")
+
+
+@dataclass(frozen=True, slots=True)
+class _Lens:
+ file_of: Callable[[Any], str | None]
+ order: Callable[[Any], tuple[Any, ...]]
+ project: Callable[[Any], RelatedItem]
+
+
+_LENSES: dict[str, _Lens] = {
+ "findings": _Lens(_file_path, _finding_key, _finding_item),
+ "fix_first": _Lens(_fix_first_file, _fix_first_key, _fix_first_item),
+ "refactoring": _Lens(_file_path, _rank_key, _refactoring_item),
+ "performance": _Lens(_file_path, _rank_key, _performance_item),
+ "dead_code": _Lens(_file_path, _dead_code_key, _dead_code_item),
+}
+
+#: Every lens, in the order a surface lists them.
+LENSES: tuple[str, ...] = tuple(_LENSES)
+
+
+def related_work(
+ file_paths: Sequence[str],
+ *,
+ findings: Iterable[Any] = (),
+ fix_first: Iterable[Any] = (),
+ refactoring: Iterable[Any] = (),
+ performance: Iterable[Any] = (),
+ dead_code: Iterable[Any] = (),
+ per_lens_limit: int = DEFAULT_PER_LENS_LIMIT,
+) -> RelatedWork:
+ """Group each lens's rows under the requested files, capped per lens.
+
+ Rows for files not in *file_paths* are ignored, so a caller may pass a
+ wider read. Files come back in request order, each listing only the lenses
+ that have something for it.
+ """
+ inputs = {
+ "findings": findings,
+ "fix_first": fix_first,
+ "refactoring": refactoring,
+ "performance": performance,
+ "dead_code": dead_code,
+ }
+ wanted = list(dict.fromkeys(file_paths))
+ grouped: dict[str, dict[str, list[Any]]] = {path: {} for path in wanted}
+ for name, rows in inputs.items():
+ lens = _LENSES[name]
+ for row in rows:
+ bucket = grouped.get(lens.file_of(row) or "")
+ if bucket is not None:
+ bucket.setdefault(name, []).append(row)
+
+ limit = max(per_lens_limit, 0)
+ files = []
+ for path in wanted:
+ lenses = {}
+ for name in LENSES:
+ rows = grouped[path].get(name)
+ if not rows:
+ continue
+ lens = _LENSES[name]
+ kept = sorted(rows, key=lens.order)[:limit]
+ lenses[name] = RelatedLens(tuple(lens.project(r) for r in kept), len(rows))
+ files.append(RelatedFile(path, lenses))
+ return RelatedWork(tuple(files), limit)
+
+
+__all__ = [
+ "DEFAULT_PER_LENS_LIMIT",
+ "LENSES",
+ "RelatedFile",
+ "RelatedItem",
+ "RelatedLens",
+ "RelatedWork",
+ "related_work",
+]
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index 043e1361a..28c431978 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+from collections.abc import Sequence
from typing import Any
from sqlalchemy import select, text
@@ -228,6 +229,7 @@ async def get_dead_code_findings(
safe_to_delete: bool | None = None,
limit: int | None = None,
include_withheld: bool = False,
+ file_paths: Sequence[str] | None = None,
) -> list[DeadCodeFinding]:
"""Return dead code findings filtered by kind, confidence, and status.
@@ -237,7 +239,8 @@ async def get_dead_code_findings(
``safe_to_delete`` and ``limit`` exist so a caller that wants a short
preview does not have to load every open finding in the repository and
then throw most of them away in Python. Overview does exactly that for a
- five-row list.
+ five-row list. ``file_paths`` scopes to a set of files (an empty sequence
+ matches nothing), on the repository/path index.
"""
q = select(DeadCodeFinding).where(
DeadCodeFinding.repository_id == repository_id,
@@ -250,6 +253,8 @@ async def get_dead_code_findings(
q = q.where(DeadCodeFinding.kind.not_in(excluded_types(requested=[kind] if kind else ())))
if safe_to_delete is not None:
q = q.where(DeadCodeFinding.safe_to_delete.is_(safe_to_delete))
+ if file_paths is not None:
+ q = q.where(DeadCodeFinding.file_path.in_(list(file_paths)))
q = q.order_by(DeadCodeFinding.confidence.desc())
if limit is not None:
q = q.limit(limit)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
index a71d32eb1..cbbb701f9 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
@@ -22,6 +22,7 @@ one aggregate read.
from __future__ import annotations
from collections import OrderedDict, namedtuple
+from dataclasses import replace
from typing import Any
from sqlalchemy import and_, case, func, or_, select
@@ -404,24 +405,51 @@ async def load_fix_first(
"""The Fix-first queue for one repository, from its stored analysis.
``item_id`` keeps only that item, at its rank, for a lookup by id.
+
+ The full queue is built once per store write and every ``limit`` and id
+ is a slice of it: the reads are the same whatever is kept, and writing
+ every item costs little next to them.
"""
- key = (
+ base = (
str(session.bind.url) if session.bind is not None else None,
repository_id,
- limit,
scope,
- item_id,
await _stamp(session, repository_id),
)
- cached = _cache.get(key)
- if cached is not None:
+ key = (*base, limit, item_id)
+ queue = _cached(key)
+ if queue is not None:
+ return queue
+ full = _cached((*base, None, None))
+ if full is None:
+ full = await _build(session, repository_id, limit=None, scope=scope, item_id=None)
+ _remember((*base, None, None), full)
+ queue = full if key[-2:] == (None, None) else _view(full, limit=limit, item_id=item_id)
+ _remember(key, queue)
+ return queue
+
+
+def _cached(key: tuple[Any, ...]) -> FixFirstQueue | None:
+ queue = _cache.get(key)
+ if queue is not None:
_cache.move_to_end(key)
- return cached
- queue = await _build(session, repository_id, limit=limit, scope=scope, item_id=item_id)
+ return queue
+
+
+def _remember(key: tuple[Any, ...], queue: FixFirstQueue) -> None:
_cache[key] = queue
while len(_cache) > CACHE_SIZE:
_cache.popitem(last=False)
- return queue
+
+
+def _view(full: FixFirstQueue, *, limit: int | None, item_id: str | None) -> FixFirstQueue:
+ """What ``build_fix_first`` returns for this limit or id, from the full
+ queue: the same items at the same ranks, ``shown`` recounted."""
+ if item_id is not None:
+ items = tuple(i for i in full.items if i.id == item_id)
+ else:
+ items = full.items if limit is None else full.items[: max(limit, 0)]
+ return replace(full, items=items, totals=replace(full.totals, shown=len(items)))
async def _build(
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 0f34c43f1..c993cfca1 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -4,6 +4,7 @@
from __future__ import annotations
import json
+from collections.abc import Sequence
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple
@@ -432,10 +433,12 @@ async def get_health_findings(
min_severity: str | None = None,
severity: str | None = None,
file_path: str | None = None,
+ file_paths: Sequence[str] | None = None,
dimension: str | None = None,
exclude_dimensions: tuple[str, ...] | None = None,
status: str = "open",
include_withheld: bool = False,
+ limit: int | None = None,
) -> list[HealthFinding]:
"""Findings for one repository, ordered by health impact.
@@ -455,6 +458,9 @@ async def get_health_findings(
``open`` / ``acknowledged`` / ``resolved`` / ``false_positive``, or ``all``
to drop the filter, so a triage surface can show what it has already
reviewed without a second read.
+
+ ``file_paths`` scopes to a set of files in one read; an empty sequence
+ matches nothing. ``limit`` caps the rows read, highest impact first.
"""
q = select(HealthFinding).where(HealthFinding.repository_id == repository_id)
statuses = [s.strip() for s in status.split(",") if s.strip()]
@@ -477,6 +483,8 @@ async def get_health_findings(
q = q.where(HealthFinding.biomarker_type.not_in(excluded_types(requested=types)))
if file_path is not None:
q = q.where(HealthFinding.file_path == file_path)
+ if file_paths is not None:
+ q = q.where(HealthFinding.file_path.in_(list(file_paths)))
if dimension is not None:
# Older rows predate the split and carry a NULL dimension that homes
# under "defect"; fold those in so a defect filter never drops them.
@@ -496,6 +504,8 @@ async def get_health_findings(
allowed = [k for k, v in order.items() if v >= threshold]
q = q.where(HealthFinding.severity.in_(allowed))
q = q.order_by(HealthFinding.health_impact.desc())
+ if limit is not None:
+ q = q.limit(limit)
result = await session.execute(q)
return _filter_excluded_paths(
list(result.scalars().all()),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index 98a5ff29e..66fadc53f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -23,6 +23,7 @@ from repowise.server.mcp_server._helpers import (
filter_dicts_by_key,
is_excluded,
)
+from repowise.server.repo_paths import normalize_target_path
#: A file carrying this many counted bug fixes reads as bug-prone. Same trigger
#: the PR bot uses for prior defects, so the two surfaces agree on "a lot".
@@ -37,46 +38,6 @@ _TOP_FIX_SYMBOLS = 3
_RELATIONSHIP_LIMIT = 5
-def normalize_target_path(target: str, repo_root: str | None = None) -> str:
- """Normalize a caller-supplied file path to the POSIX-relative form stored
- in ``git_metadata.file_path``.
-
- ``get_risk`` matches ``file_path`` by exact string equality, but callers
- reach it through git tools, shell completion, or editors that hand over a
- backslash form (Windows), a leading ``./``, an absolute path, or a trailing
- separator. Any of those makes the row lookup miss, and ``_assess_one_target``
- then reports the indistinguishable ``no git metadata available`` card
- (hotspot_score=0, primary_owner=None, empty co_change_partners) even though
- the row exists — issue #1279. Normalizing the caller's side closes that gap.
- """
- normalized = target.replace("\\", "/")
- # Make a repo-absolute path (``/abs/repo/src/x.py``) relative to the repo
- # root when we know it. Uses a prefix check on the normalized forms, so a
- # path that is already repo-relative is left untouched.
- if repo_root:
- root_path = Path(repo_root).resolve()
- try:
- # Resolve against the repo root, not the process cwd: the MCP
- # server's cwd is not the repo, so a relative path that happens
- # to exist there could resolve somewhere unrelated.
- candidate = Path(normalized)
- resolved = (candidate if candidate.is_absolute() else root_path / candidate).resolve()
- normalized = resolved.relative_to(root_path).as_posix()
- except (OSError, ValueError):
- # Resolution can fail for malformed paths; relative_to() also
- # rejects absolute paths outside the selected repository.
- pass
- # Strip a leading cwd-relative prefix and any leading slash left over.
- # A prefix strip, not lstrip: lstrip takes a character set, so it would
- # eat every leading dot (``.github/...`` -> ``github/...``).
- if normalized.startswith("./"):
- normalized = normalized[2:]
- normalized = normalized.lstrip("/")
- # Collapse duplicate slashes and any trailing separator.
- parts = [p for p in normalized.split("/") if p]
- return "/".join(parts)
-
-
def _derive_change_pattern(categories: dict[str, int]) -> str:
"""Derive a human-readable change pattern from commit category counts."""
if not categories:
diff --git a/packages/server/src/repowise/server/repo_paths.py b/packages/server/src/repowise/server/repo_paths.py
new file mode 100644
index 000000000..7b1de7e04
--- /dev/null
+++ b/packages/server/src/repowise/server/repo_paths.py
@@ -0,0 +1,49 @@
+"""Caller-supplied file paths, reduced to the repo-relative form the stores key on.
+
+Shared by every surface that matches a path by exact string equality: the MCP
+risk tool and the code-health routes.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+def normalize_target_path(target: str, repo_root: str | None = None) -> str:
+ """Normalize a caller-supplied file path to the POSIX-relative form stored
+ in ``git_metadata.file_path``.
+
+ ``get_risk`` matches ``file_path`` by exact string equality, but callers
+ reach it through git tools, shell completion, or editors that hand over a
+ backslash form (Windows), a leading ``./``, an absolute path, or a trailing
+ separator. Any of those makes the row lookup miss, and ``_assess_one_target``
+ then reports the indistinguishable ``no git metadata available`` card
+ (hotspot_score=0, primary_owner=None, empty co_change_partners) even though
+ the row exists — issue #1279. Normalizing the caller's side closes that gap.
+ """
+ normalized = target.replace("\\", "/")
+ # Make a repo-absolute path (``/abs/repo/src/x.py``) relative to the repo
+ # root when we know it. Uses a prefix check on the normalized forms, so a
+ # path that is already repo-relative is left untouched.
+ if repo_root:
+ root_path = Path(repo_root).resolve()
+ try:
+ # Resolve against the repo root, not the process cwd: the MCP
+ # server's cwd is not the repo, so a relative path that happens
+ # to exist there could resolve somewhere unrelated.
+ candidate = Path(normalized)
+ resolved = (candidate if candidate.is_absolute() else root_path / candidate).resolve()
+ normalized = resolved.relative_to(root_path).as_posix()
+ except (OSError, ValueError):
+ # Resolution can fail for malformed paths; relative_to() also
+ # rejects absolute paths outside the selected repository.
+ pass
+ # Strip a leading cwd-relative prefix and any leading slash left over.
+ # A prefix strip, not lstrip: lstrip takes a character set, so it would
+ # eat every leading dot (``.github/...`` -> ``github/...``).
+ if normalized.startswith("./"):
+ normalized = normalized[2:]
+ normalized = normalized.lstrip("/")
+ # Collapse duplicate slashes and any trailing separator.
+ parts = [p for p in normalized.split("/") if p]
+ return "/".join(parts)
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 037baadde..84b2840a2 100644
--- a/packages/server/src/repowise/server/routers/code_health/__init__.py
+++ b/packages/server/src/repowise/server/routers/code_health/__init__.py
@@ -25,6 +25,7 @@ from . import (
overview_routes, # noqa: F401
performance_routes, # noqa: F401
refactoring_routes, # noqa: F401
+ related_work_routes, # noqa: F401
trends_routes, # noqa: F401
)
from ._router import router
diff --git a/packages/server/src/repowise/server/routers/code_health/related_work_routes.py b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
new file mode 100644
index 000000000..91a09e5e1
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
@@ -0,0 +1,113 @@
+"""What every other lens holds for a set of files, for a drawer's see-also.
+
+A thin adapter: one read per lens, scoped to the files in the body, then
+``related_work`` in core groups and caps them. Fix first comes from its cached
+loader, so asking costs a queue build at most once per store write.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import Depends, HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.related_work import related_work
+from repowise.core.persistence import crud
+from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
+from repowise.core.persistence.crud.analysis.performance import (
+ list_performance_opportunities,
+)
+from repowise.server.deps import get_db_session
+from repowise.server.repo_paths import normalize_target_path
+from repowise.server.schemas import RelatedWorkRequest, RelatedWorkResponse
+
+from ._router import router
+
+MAX_FILES = 200
+"""Files one request may name. A drawer asks about one; a selection, a few."""
+
+_ROWS_CEILING = 10_000
+"""Ceiling on the rows any one lens read returns for the whole request.
+
+The per-file totals need every row for the named files, so each read is
+bounded here rather than per file. 200 files never come near it on a real
+index; past it the totals undercount. Upgrade path: a grouped count per file.
+"""
+
+
+def _validated(raw: list[str]) -> list[str]:
+ """Repo-relative slash paths, unique, 1..MAX_FILES; 422 on anything else.
+
+ The shared normalizer would quietly make an absolute path relative, so
+ absolute, drive-qualified and ``..`` paths are refused before it runs.
+ """
+ if not 1 <= len(raw) <= MAX_FILES:
+ raise HTTPException(status_code=422, detail=f"file_paths must name 1 to {MAX_FILES} files")
+ paths: list[str] = []
+ for value in raw:
+ slashed = value.strip().replace("\\", "/")
+ path = normalize_target_path(slashed)
+ if (
+ not path
+ or slashed.startswith("/")
+ or slashed[1:2] == ":"
+ or ".." in path.split("/")
+ ):
+ raise HTTPException(
+ status_code=422, detail=f"not a repo-relative file path: {value!r}"
+ )
+ paths.append(path)
+ if len(set(paths)) != len(paths):
+ raise HTTPException(status_code=422, detail="file_paths must be unique")
+ return paths
+
+
+ "/api/repos/{repo_id}/health/related-work",
+ response_model=RelatedWorkResponse,
+ # An item states only what its lens knows; a null would claim a field.
+ response_model_exclude_none=True,
+)
+async def get_related_work(
+ repo_id: str,
+ payload: RelatedWorkRequest,
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """Per file, what findings, Fix first, refactoring, performance and dead
+ code each hold, capped per lens with the full count beside it."""
+ paths = _validated(payload.file_paths)
+ findings = await crud.get_health_findings(
+ session,
+ repo_id,
+ file_paths=paths,
+ # Performance findings are the evidence behind the performance lens's
+ # opportunities; listing them as findings would show one cause twice.
+ exclude_dimensions=("performance",),
+ limit=_ROWS_CEILING,
+ )
+ # Production scope, unlike the other lenses: the link lands on the default
+ # Fix-first view, which is production scope.
+ queue = await load_fix_first(session, repo_id, limit=None)
+ refactoring, _ = await crud.list_refactoring_opportunities(
+ session, repo_id, file_paths=paths, order="rank", limit=_ROWS_CEILING
+ )
+ # Every execution context: the reader opened these files, so the question
+ # is what was found in them, not whether they are production code.
+ performance, _ = await list_performance_opportunities(
+ session, repo_id, file_paths=tuple(paths), limit=_ROWS_CEILING
+ )
+ dead_code = await crud.get_dead_code_findings(
+ session, repo_id, file_paths=paths, limit=_ROWS_CEILING
+ )
+ return related_work(
+ paths,
+ findings=findings,
+ fix_first=queue.items,
+ refactoring=refactoring,
+ performance=performance,
+ dead_code=dead_code,
+ ).as_dict()
+
+
+__all__ = ["get_related_work"]
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 2e01c708a..5df76167c 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -68,6 +68,11 @@ if TYPE_CHECKING:
HealthWorkQueueResponse,
ImpactEffortPoint,
ImpactEffortResponse,
+ RelatedWorkFile,
+ RelatedWorkItem,
+ RelatedWorkLens,
+ RelatedWorkRequest,
+ RelatedWorkResponse,
)
from .code_quality import (
DeadCodeAnalyzeResponse,
@@ -375,6 +380,11 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"HealthWorkQueueResponse",
"ImpactEffortPoint",
"ImpactEffortResponse",
+ "RelatedWorkFile",
+ "RelatedWorkItem",
+ "RelatedWorkLens",
+ "RelatedWorkRequest",
+ "RelatedWorkResponse",
),
"code_quality": (
"DeadCodeAnalyzeResponse",
@@ -786,6 +796,11 @@ __all__ = [
"RefactoringOpportunityStatusResponse",
"RefactoringPlanStatusResponse",
"RefactoringRollupResponse",
+ "RelatedWorkFile",
+ "RelatedWorkItem",
+ "RelatedWorkLens",
+ "RelatedWorkRequest",
+ "RelatedWorkResponse",
"RepoCreate",
"RepoDeletedResponse",
"RepoResponse",
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index a096071a3..6ae175e85 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -7,7 +7,7 @@ nullable; where it coerces to a number they are not.
from __future__ import annotations
-from typing import Any
+from typing import Any, Literal
from pydantic import BaseModel
@@ -245,3 +245,48 @@ class ImpactEffortResponse(BaseModel):
gain_midline_points: float = 0.0
#: Files left out because every finding on them is a history marker.
history_only_excluded: int = 0
+
+
+class RelatedWorkRequest(BaseModel):
+ """The files to look up, repo-relative. Validated by the route."""
+
+ file_paths: list[str]
+
+
+class RelatedWorkItem(BaseModel):
+ """One row another lens holds for the file, compact enough to list."""
+
+ lens: Literal["findings", "fix_first", "refactoring", "performance", "dead_code"]
+ id: str
+ #: Biomarker, refactoring type, Fix-first kind or dead-code kind.
+ kind: str | None = None
+ title: str | None = None
+ symbol: str | None = None
+ severity: str | None = None
+ #: Fix-first tier, refactoring effort, performance actionability, or the
+ #: dead-code verdict (``safe_to_delete`` / ``review``).
+ tier: str | None = None
+ rank: int | None = None
+ line: int | None = None
+ #: Sent only when the stored row carries them.
+ code_origin: str | None = None
+ deprecated: bool | None = None
+
+
+class RelatedWorkLens(BaseModel):
+ items: list[RelatedWorkItem] = []
+ #: Every row the lens holds for the file; ``items`` stops at the limit.
+ total: int = 0
+
+
+class RelatedWorkFile(BaseModel):
+ file_path: str
+ #: Keyed by lens; a lens with nothing for the file is absent.
+ lenses: dict[str, RelatedWorkLens] = {}
+
+
+class RelatedWorkResponse(BaseModel):
+ """``RelatedWork.as_dict()``: files in request order."""
+
+ files: list[RelatedWorkFile] = []
+ per_lens_limit: int = 0
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 62a4007b6..a31cf095e 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2784,6 +2784,42 @@ export interface RefactoringTypeCount {
count: number;
}
+export interface RelatedWorkFile {
+ file_path: string;
+ lenses?: Record<string, RelatedWorkLens>;
+}
+
+/** One row another lens holds for the file, compact enough to list. */
+export interface RelatedWorkItem {
+ lens: "findings" | "fix_first" | "refactoring" | "performance" | "dead_code";
+ id: string;
+ kind?: string | null;
+ title?: string | null;
+ symbol?: string | null;
+ severity?: string | null;
+ tier?: string | null;
+ rank?: number | null;
+ line?: number | null;
+ code_origin?: string | null;
+ deprecated?: boolean | null;
+}
+
+export interface RelatedWorkLens {
+ items?: RelatedWorkItem[];
+ total?: number;
+}
+
+/** The files to look up, repo-relative. Validated by the route. */
+export interface RelatedWorkRequest {
+ file_paths: string[];
+}
+
+/** ``RelatedWork.as_dict()``: files in request order. */
+export interface RelatedWorkResponse {
+ files?: RelatedWorkFile[];
+ per_lens_limit?: number;
+}
+
export interface RepoCreate {
name: string;
local_path: string;
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 8645270b9..a1c0f8196 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -1079,6 +1079,18 @@ export type {
CoverageSummaryFreshness,
} from "./generated/http.js";
+/**
+ * What the other lenses hold for the same files: per file, findings, Fix
+ * first, refactoring, performance and dead code, each capped with its total.
+ * A lens with nothing for a file is absent from `lenses`.
+ */
+export type {
+ RelatedWorkFile,
+ RelatedWorkItem,
+ RelatedWorkLens,
+ RelatedWorkResponse,
+} from "./generated/http.js";
+
/**
* Which signal answered "is this tested". `measured` is a coverage report: it
* records the lines a test really executed. `inferred` is the dependency graph:
diff --git a/packages/ui/__tests__/health/related-work.test.tsx b/packages/ui/__tests__/health/related-work.test.tsx
new file mode 100644
index 000000000..72984ac90
--- /dev/null
+++ b/packages/ui/__tests__/health/related-work.test.tsx
@@ -0,0 +1,129 @@
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
+import type { RelatedWorkFile, RelatedWorkItem } from "@repowise-dev/types/health";
+import { RelatedWork, useRelatedWork } from "../../src/health/related-work.js";
+import { HealthFileDrawer } from "../../src/health/health-file-drawer.js";
+
+const FILE: RelatedWorkFile = {
+ file_path: "src/repo.py",
+ lenses: {
+ findings: {
+ items: [
+ { lens: "findings", id: "f1", kind: "complex_method", severity: "high", symbol: "load", line: 12 },
+ ],
+ total: 1,
+ },
+ refactoring: {
+ items: [{ lens: "refactoring", id: "refop_1", kind: "extract_method", tier: "M", rank: 1 }],
+ total: 1,
+ },
+ performance: {
+ items: [
+ { lens: "performance", id: "perf_1", kind: "io_in_loop", symbol: "src/repo.py::load_all", tier: "advisory" },
+ ],
+ total: 7,
+ },
+ dead_code: {
+ items: [{ lens: "dead_code", id: "d1", kind: "unused_export", symbol: "old_helper", tier: "review", line: 40 }],
+ total: 1,
+ },
+ },
+};
+
+const href = (item: RelatedWorkItem) => `/go/${item.lens}/${item.id}`;
+
+describe("RelatedWork", () => {
+ it("renders nothing without data or with nothing outside its own lens", () => {
+ const { container, rerender } = render(<RelatedWork related={undefined} />);
+ expect(container).toBeEmptyDOMElement();
+ rerender(<RelatedWork related={{ file_path: "a.py", lenses: {} }} />);
+ expect(container).toBeEmptyDOMElement();
+ rerender(
+ <RelatedWork
+ related={{ file_path: "a.py", lenses: { findings: FILE.lenses!.findings! } }}
+ exclude={["findings"]}
+ />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("leaves out the lens it sits in and links the rest", () => {
+ render(<RelatedWork related={FILE} exclude={["refactoring"]} relatedWorkHref={href} />);
+ expect(screen.queryByText("Refactoring")).not.toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /Unused export: old_helper/ })).toHaveAttribute(
+ "href",
+ "/go/dead_code/d1",
+ );
+ expect(screen.getByRole("link", { name: /load_all/ })).toHaveAttribute(
+ "href",
+ "/go/performance/perf_1",
+ );
+ // A capped lens says how much it is showing.
+ expect(screen.getByText("1 of 7")).toBeInTheDocument();
+ });
+
+ it("is plain text without an href and routes through the host when asked", () => {
+ const { rerender } = render(<RelatedWork related={FILE} />);
+ expect(screen.queryAllByRole("link")).toHaveLength(0);
+ const onNavigate = vi.fn();
+ rerender(<RelatedWork related={FILE} relatedWorkHref={href} onNavigate={onNavigate} />);
+ fireEvent.click(screen.getByRole("link", { name: /Extract method/i }));
+ expect(onNavigate).toHaveBeenCalledWith("/go/refactoring/refop_1");
+ });
+});
+
+describe("HealthFileDrawer related work", () => {
+ it("lists the other lenses but never repeats the drawer's own findings", () => {
+ const onNavigate = vi.fn();
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={{
+ file_path: "src/repo.py",
+ score: 5,
+ max_ccn: 10,
+ max_nesting: 3,
+ nloc: 100,
+ module: "src",
+ has_test_file: false,
+ }}
+ related={FILE}
+ relatedWorkHref={href}
+ onNavigate={onNavigate}
+ />,
+ );
+ expect(screen.getByText("Elsewhere for this file")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("link", { name: /Unused export/ }));
+ expect(onNavigate).toHaveBeenCalledWith("/go/dead_code/d1");
+ expect(screen.getByRole("link", { name: /Extract method/i })).toHaveAttribute(
+ "href",
+ "/go/refactoring/refop_1",
+ );
+ expect(screen.queryByRole("link", { name: /\/go\/findings/ })).not.toBeInTheDocument();
+ expect(screen.queryAllByRole("link").map((a) => a.getAttribute("href"))).not.toContain(
+ "/go/findings/f1",
+ );
+ });
+});
+
+describe("useRelatedWork", () => {
+ it("asks once per set of paths and not at all without a fetcher or a path", async () => {
+ const fetcher = vi.fn(async (paths: string[]) => ({
+ files: paths.map((file_path) => ({ file_path, lenses: {} })),
+ per_lens_limit: 5,
+ }));
+ const { result, rerender } = renderHook(
+ ({ paths }: { paths: (string | null)[] }) => useRelatedWork(fetcher, paths),
+ { initialProps: { paths: ["a.py"] as (string | null)[] } },
+ );
+ await waitFor(() => expect(result.current?.files?.[0]?.file_path).toBe("a.py"));
+ rerender({ paths: ["a.py"] });
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ rerender({ paths: [null] });
+ expect(result.current).toBeUndefined();
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ const none = renderHook(() => useRelatedWork(undefined, ["a.py"]));
+ expect(none.result.current).toBeUndefined();
+ });
+});
diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.ts
index 5a42383be..3f35e20c3 100644
--- a/packages/ui/src/health/code-health-adapter.ts
+++ b/packages/ui/src/health/code-health-adapter.ts
@@ -13,10 +13,12 @@ import type {
PerformanceOpportunityDetail,
PerformanceOpportunityPage,
PerformanceOpportunityQuery,
+ RelatedWorkResponse,
TestsReachingFile,
} from "@repowise-dev/types/health";
import type { Paginated } from "@repowise-dev/types";
import type { CodeHealthOverlay } from "./map/types";
+import type { RelatedWorkHref } from "./related-work";
import type {
RefactoringOpportunity,
RefactoringPlan,
@@ -134,6 +136,13 @@ export interface CodeHealthAdapter {
getFileOpportunity?(filePath: string): Promise<RefactoringOpportunity | null>;
/** Deep link into the refactoring surface for one opportunity. */
refactoringOpportunityHref?(opportunityId: string): string;
+ /**
+ * What every lens holds for these files. Optional: a host without it shows
+ * no "elsewhere" section rather than an empty one.
+ */
+ getRelatedWork?(filePaths: string[]): Promise<RelatedWorkResponse>;
+ /** Where one related item lives, or null when it has nowhere to go. */
+ relatedWorkHref?: RelatedWorkHref;
/**
* Where this cause lives on the one map. Optional: a host without a galaxy
* offers no link rather than a second map.
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 7805dff86..d1f95cd0b 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -25,6 +25,7 @@ import { AiPromptModal } from "./ai-prompt-modal";
import { buildFileHealthAiPrompt } from "./ai-prompt-builder";
import { FileSignalsPanel } from "./file-signals-panel";
import { FindingOpportunityLink } from "./file-opportunity";
+import { RelatedWork, type RelatedWorkSlotProps } from "./related-work";
import { CollapsibleSection } from "../shared/collapsible-section";
import { formatRelativeTimeOrNull } from "../lib/format";
import { Sparkline } from "./sparkline";
@@ -90,7 +91,7 @@ export interface HealthDrawerMetric {
total_deduction?: number | null;
}
-export interface HealthFileDrawerProps {
+export interface HealthFileDrawerProps extends RelatedWorkSlotProps {
open: boolean;
onClose: () => void;
loading?: boolean;
@@ -169,6 +170,9 @@ export function HealthFileDrawer({
suggestions = {},
opportunity,
refactoringOpportunityHref,
+ related,
+ relatedWorkHref,
+ onNavigate,
trend,
signals,
fileViewHref,
@@ -566,6 +570,15 @@ export function HealthFileDrawer({
<BugHistorySection signals={signals} />
+ {/* Findings are this drawer's own list, and the performance lens
+ already leads with the file's causes. */}
+ <RelatedWork
+ related={related}
+ relatedWorkHref={relatedWorkHref}
+ onNavigate={onNavigate}
+ exclude={lens === "performance" ? ["findings", "performance"] : ["findings"]}
+ />
+
{/* Collapsed by default. This is the audit trail for a number
the drawer already states at the top, beside a leading cause
that names the biggest contributor in words. A reader who
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index 35ac3390e..0b1498a0a 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -39,6 +39,7 @@ export * from "./patch-coverage-summary";
export * from "./severity-mark";
export * from "./code-health-adapter";
export * from "./file-opportunity";
+export * from "./related-work";
export * from "./triage-view";
export * from "./findings-view";
export * from "./performance-view";
diff --git a/packages/ui/src/health/performance/adapter.ts b/packages/ui/src/health/performance/adapter.ts
index 01fa9747a..0fd842fde 100644
--- a/packages/ui/src/health/performance/adapter.ts
+++ b/packages/ui/src/health/performance/adapter.ts
@@ -15,6 +15,8 @@ export type PerformanceViewAdapter = Pick<
| "getPerformanceOpportunityFindings"
| "getRefactoringPlan"
| "refactoringPlanHref"
+ | "getRelatedWork"
+ | "relatedWorkHref"
| "mapHref"
| "readSource"
| "fileHref"
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index 251dd4df1..7f4768b70 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -19,6 +19,7 @@ import { performancePlanDetail } from "../../refactoring/types";
import { SourceExcerpt } from "../../refactoring/source-excerpt";
import { ValidationSummary } from "../../refactoring/validation-summary";
import { EFFORT_LABEL, WORK_UNIT_LABEL } from "../labels";
+import { RelatedWork, useRelatedWork } from "../related-work";
import type { PerformanceViewAdapter } from "./adapter";
import { RawObservations } from "./evidence";
import {
@@ -522,6 +523,8 @@ export function OpportunityDrawer({
plan={plan}
/>
+ <RelatedSection adapter={adapter} filePath={current.file_path} />
+
{current.evidence.some((item) => item.path.length > 0) ? (
<Section title="Caller to sink paths">
<ProvenancePathList
@@ -666,6 +669,26 @@ function CodeSection({
);
}
+/** What the other lenses hold for the file this cause is fixed in. */
+function RelatedSection({
+ adapter,
+ filePath,
+}: {
+ adapter: PerformanceViewAdapter;
+ filePath: string;
+}) {
+ const data = useRelatedWork(adapter.getRelatedWork, [filePath]);
+ return (
+ <RelatedWork
+ related={data?.files?.[0]}
+ relatedWorkHref={adapter.relatedWorkHref}
+ onNavigate={adapter.navigate}
+ exclude={["performance"]}
+ headingLevel="h4"
+ />
+ );
+}
+
/**
* Where this cause sits on the one map.
*
diff --git a/packages/ui/src/health/related-work.tsx b/packages/ui/src/health/related-work.tsx
new file mode 100644
index 000000000..6c9c1e584
--- /dev/null
+++ b/packages/ui/src/health/related-work.tsx
@@ -0,0 +1,244 @@
+"use client";
+
+/**
+ * What the other lenses hold for the file in front of the reader.
+ *
+ * The general form of {@link FindingOpportunityLink}: a drawer in one lens
+ * (findings, refactoring, performance) lists what findings, Fix first,
+ * refactoring, performance and dead code each say about the same file, and
+ * links to where that item lives. The host fetches (`useRelatedWork`) and says
+ * where each item goes; this renders. It never repeats the lens it sits in,
+ * and renders nothing at all when there is nothing else to say or the host
+ * supplied no data, so an absent section is never read as "clean elsewhere".
+ */
+
+import * as React from "react";
+
+import type {
+ RelatedWorkFile,
+ RelatedWorkItem,
+ RelatedWorkLens,
+ RelatedWorkResponse,
+} from "@repowise-dev/types/health";
+import { typeMeta } from "../refactoring/meta";
+import { biomarkerLabel } from "./biomarker-glossary";
+import { TIER_LABEL } from "./fix-first/scope";
+import { EFFORT_LABEL } from "./labels";
+import { ACTIONABILITY_LABEL, humanizeToken } from "./performance/presentation";
+import { SEVERITY_LABEL, type Severity } from "./tokens";
+
+export type RelatedLensName = RelatedWorkItem["lens"];
+
+/** Where one related item lives, or null when it has nowhere to go. */
+export type RelatedWorkHref = (item: RelatedWorkItem, filePath: string) => string | null;
+
+/** What a drawer takes to show the section: the data, the links, the router. */
+export interface RelatedWorkSlotProps {
+ /** The file's entry from `useRelatedWork`. Absent: no section. */
+ related?: RelatedWorkFile | null | undefined;
+ /** Omit and the items are plain text. */
+ relatedWorkHref?: RelatedWorkHref | undefined;
+ /** Host navigation, for a surface that routes rather than follows an anchor. */
+ onNavigate?: ((href: string) => void) | undefined;
+}
+
+/**
+ * Fetch what every lens holds for these files, once per set of paths.
+ *
+ * Same contract as `useFileOpportunity`: `undefined` while not asked, when
+ * the host cannot ask, or when the lookup failed, so a caller never renders a
+ * claim it has not established. Pass a stable `fetcher`.
+ */
+export function useRelatedWork(
+ fetcher: ((filePaths: string[]) => Promise<RelatedWorkResponse>) | undefined,
+ filePaths: readonly (string | null | undefined)[],
+): RelatedWorkResponse | undefined {
+ const [value, setValue] = React.useState<RelatedWorkResponse | undefined>(undefined);
+ // The one key: the paths in order. A new array with the same paths is the
+ // same request.
+ const key = filePaths.filter((p): p is string => Boolean(p)).join("\n");
+
+ React.useEffect(() => {
+ setValue(undefined);
+ if (!fetcher || !key) return;
+ let live = true;
+ void fetcher(key.split("\n"))
+ .then((result) => {
+ if (live) setValue(result);
+ })
+ .catch(() => {
+ if (live) setValue(undefined);
+ });
+ return () => {
+ live = false;
+ };
+ }, [fetcher, key]);
+
+ return value;
+}
+
+/** Every lens, in the order the server lists them. */
+export const RELATED_LENSES: readonly RelatedLensName[] = [
+ "findings",
+ "fix_first",
+ "refactoring",
+ "performance",
+ "dead_code",
+];
+
+export const RELATED_LENS_LABEL: Record<RelatedLensName, string> = {
+ findings: "Findings",
+ fix_first: "Fix first",
+ refactoring: "Refactoring",
+ performance: "Performance",
+ dead_code: "Dead code",
+};
+
+function lookup<K extends string>(table: Record<K, string>, key: string | null | undefined) {
+ return key && key in table ? table[key as K] : null;
+}
+
+/** An item's label and the plain-word facts beside it. */
+function describe(item: RelatedWorkItem): { label: string; facts: string[] } {
+ const kind = item.kind ?? "";
+ let label: string;
+ let facts: (string | null)[];
+ switch (item.lens) {
+ case "findings":
+ label = biomarkerLabel(kind);
+ facts = [lookup<Severity>(SEVERITY_LABEL, item.severity), item.symbol ?? null];
+ break;
+ case "fix_first":
+ label = item.title ?? "Ranked fix";
+ facts = [
+ item.rank != null ? `#${(item.rank + 1).toLocaleString()} in Fix first` : null,
+ lookup(TIER_LABEL, item.tier),
+ ];
+ break;
+ case "refactoring": {
+ label = typeMeta(kind).label;
+ const effort = lookup(EFFORT_LABEL, item.tier);
+ facts = [effort ? `${effort} effort` : null];
+ break;
+ }
+ case "performance":
+ label = biomarkerLabel(kind);
+ facts = [
+ item.symbol ? (item.symbol.split("::").pop() ?? item.symbol) : null,
+ lookup(ACTIONABILITY_LABEL, item.tier),
+ ];
+ break;
+ case "dead_code":
+ label = item.symbol ? `${humanizeToken(kind)}: ${item.symbol}` : humanizeToken(kind);
+ facts = [item.tier === "safe_to_delete" ? "Safe to delete" : "Needs review"];
+ break;
+ }
+ if (item.line != null) facts.push(`line ${item.line}`);
+ if (item.deprecated) facts.push("deprecated");
+ if (item.code_origin) facts.push(humanizeToken(item.code_origin).toLowerCase());
+ return { label, facts: facts.filter((v): v is string => Boolean(v)) };
+}
+
+export interface RelatedWorkProps extends RelatedWorkSlotProps {
+ /** Lenses this surface already shows; their items are never repeated here. */
+ exclude?: readonly RelatedLensName[] | undefined;
+ /** Heading level, so the section nests under the drawer's own headings. */
+ headingLevel?: "h3" | "h4" | undefined;
+}
+
+export function RelatedWork({
+ related,
+ relatedWorkHref,
+ onNavigate,
+ exclude = [],
+ headingLevel = "h3",
+}: RelatedWorkProps) {
+ const lenses = RELATED_LENSES.filter((name) => !exclude.includes(name))
+ .map((name) => [name, related?.lenses?.[name]] as const)
+ .filter((entry): entry is readonly [RelatedLensName, RelatedWorkLens] =>
+ Boolean(entry[1]?.items?.length),
+ );
+ if (!related || lenses.length === 0) return null;
+
+ const Heading = headingLevel;
+ return (
+ <section className="flex flex-col gap-2" aria-label="Elsewhere for this file">
+ <Heading className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Elsewhere for this file
+ </Heading>
+ <div className="flex flex-col gap-3">
+ {lenses.map(([name, lens]) => {
+ const items = lens.items ?? [];
+ const total = lens.total ?? items.length;
+ return (
+ <div key={name} className="flex flex-col gap-1">
+ <p className="text-[11px] font-medium text-[var(--color-text-secondary)]">
+ {RELATED_LENS_LABEL[name]}{" "}
+ <span className="font-normal tabular-nums text-[var(--color-text-tertiary)]">
+ {items.length < total
+ ? `${items.length} of ${total.toLocaleString()}`
+ : total.toLocaleString()}
+ </span>
+ </p>
+ <ul className="flex flex-col">
+ {items.map((item) => (
+ <RelatedRow
+ key={`${item.lens}:${item.id}`}
+ item={item}
+ target={relatedWorkHref?.(item, related.file_path) ?? null}
+ onNavigate={onNavigate}
+ />
+ ))}
+ </ul>
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
+function RelatedRow({
+ item,
+ target,
+ onNavigate,
+}: {
+ item: RelatedWorkItem;
+ target: string | null;
+ onNavigate?: ((href: string) => void) | undefined;
+}) {
+ const { label, facts } = describe(item);
+ const text = (
+ <>
+ <span className="min-w-0 truncate">{label}</span>
+ {facts.length > 0 ? (
+ <span className="shrink-0 font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {facts.join(" · ")}
+ </span>
+ ) : null}
+ </>
+ );
+ return (
+ <li className="py-0.5 text-xs">
+ {target ? (
+ <a
+ href={target}
+ onClick={
+ onNavigate
+ ? (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onNavigate(target);
+ }
+ : (e) => e.stopPropagation()
+ }
+ className="flex items-baseline gap-2 rounded text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {text}
+ </a>
+ ) : (
+ <span className="flex items-baseline gap-2 text-[var(--color-text-primary)]">{text}</span>
+ )}
+ </li>
+ );
+}
diff --git a/packages/ui/src/refactoring/opportunity-drawer.tsx b/packages/ui/src/refactoring/opportunity-drawer.tsx
index 22267b1fa..9b6636b8d 100644
--- a/packages/ui/src/refactoring/opportunity-drawer.tsx
+++ b/packages/ui/src/refactoring/opportunity-drawer.tsx
@@ -34,6 +34,7 @@ import { ValidationSummary } from "./validation-summary";
import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
import { CodeBlock } from "./plan-detail";
import { SourceExcerpt } from "./source-excerpt";
+import { RelatedWork, type RelatedWorkSlotProps } from "../health/related-work";
import { GenerateCodePanel } from "./generate-code-panel";
import { extractHelperDetail } from "./types";
import {
@@ -60,7 +61,7 @@ export function opportunityHandoffCall(opportunityId: string): string {
return `get_health(opportunity_id="${opportunityId}")`;
}
-export interface OpportunityDrawerProps {
+export interface OpportunityDrawerProps extends RelatedWorkSlotProps {
detail: RefactoringOpportunityDetail | null;
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -97,6 +98,9 @@ export function OpportunityDrawer({
fileHref,
readSource,
onGenerateCode,
+ related,
+ relatedWorkHref,
+ onNavigate,
}: OpportunityDrawerProps) {
const resolved = detail?.found ? detail : null;
return (
@@ -115,6 +119,9 @@ export function OpportunityDrawer({
fileHref={fileHref}
readSource={readSource}
onGenerateCode={onGenerateCode}
+ related={related}
+ relatedWorkHref={relatedWorkHref}
+ onNavigate={onNavigate}
/>
) : loading ? (
<>
@@ -169,6 +176,9 @@ function DrawerBody({
fileHref,
readSource,
onGenerateCode,
+ related,
+ relatedWorkHref,
+ onNavigate,
}: {
detail: RefactoringOpportunityDetailResolved;
onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;
@@ -182,7 +192,7 @@ function DrawerBody({
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
readSource?: ((path: string) => Promise<string>) | undefined;
onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
-}) {
+} & RelatedWorkSlotProps) {
const meta = typeMeta(detail.lead_refactoring_type || "");
const plansById = React.useMemo(
() => new Map(detail.plans.map((plan) => [plan.id, plan])),
@@ -374,6 +384,14 @@ function DrawerBody({
)}
</section>
+ <RelatedWork
+ related={related?.file_path === detail.file_path ? related : null}
+ relatedWorkHref={relatedWorkHref}
+ onNavigate={onNavigate}
+ exclude={["refactoring"]}
+ headingLevel="h4"
+ />
+
{detail.evidence.length > 0 ? (
<section>
<h4 className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index 7e1b9c628..a85b0c5d0 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -15,6 +15,7 @@
import { use, useCallback, useDeferredValue, useMemo, useState } from "react";
import useSWR from "swr";
+import { useRouter } from "next/navigation";
import { parseAsString, parseAsStringLiteral, useQueryState } from "nuqs";
import { Wrench, RotateCw } from "lucide-react";
import { PageShell } from "@repowise-dev/ui/shared/page-shell";
@@ -45,6 +46,7 @@ import type {
RefactoringScope,
} from "@repowise-dev/types/refactoring";
import {
+ useRelatedWork,
AiPromptModal,
buildRefactoringOpportunityPrompt,
buildRefactoringPlanPrompt,
@@ -59,6 +61,7 @@ import {
type RefactoringSettings,
} from "@/lib/api/refactoring";
import { getFileContent } from "@/lib/api/files";
+import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";
const TYPE_VALUES = ["all", "structural", ...TYPE_ORDER] as const;
type TypeFilter = (typeof TYPE_VALUES)[number];
@@ -75,6 +78,7 @@ function leadTypeFor(type: TypeFilter): string | undefined {
export default function RefactoringPage({ params }: { params: Promise<{ id: string }> }) {
const { id: repoId } = use(params);
+ const router = useRouter();
const [type, setType] = useQueryState(
"type",
parseAsStringLiteral(TYPE_VALUES).withDefault("all"),
@@ -156,6 +160,15 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
+ // What the other lenses hold for the open opportunity's file.
+ const openFile = openDetail?.found ? openDetail.file_path : null;
+ const fetchRelated = useCallback(
+ (paths: string[]) => getRelatedWork(repoId, paths),
+ [repoId],
+ );
+ const related = useRelatedWork(fetchRelated, [openFile]);
+ const toRelated = useMemo(() => relatedWorkHref(repoId), [repoId]);
+
const { data: openPlan } = useSWR<RefactoringPlan>(
openPlanId ? ["refactoring-plan", repoId, openPlanId] : null,
() => getRefactoringPlan(repoId, openPlanId!),
@@ -348,6 +361,9 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
fileHref={fileHref}
readSource={readSource}
onGenerateCode={onGenerateCode}
+ related={related?.files?.[0]}
+ relatedWorkHref={toRelated}
+ onNavigate={(href) => router.push(href)}
/>
<RefactoringDrawer
diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsx
index ed6417a82..309e20162 100644
--- a/packages/web/src/components/code-health/performance-tab.tsx
+++ b/packages/web/src/components/code-health/performance-tab.tsx
@@ -12,6 +12,7 @@ import {
} from "@/lib/api/code-health";
import { getRefactoringPlan } from "@/lib/api/refactoring";
import { getFileContent } from "@/lib/api/files";
+import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";
/** The queue's own filter state, kept out of the page's `tab` and `lens`. */
const FILTER_PARAM = "perf";
@@ -44,6 +45,8 @@ export function PerformanceTab({ repoId }: { repoId: string }) {
fileHref: (path) => fileEntityPath(prefix, path),
symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),
readSource: (path) => getFileContent(repoId, path),
+ getRelatedWork: (filePaths) => getRelatedWork(repoId, filePaths),
+ relatedWorkHref: relatedWorkHref(repoId),
navigate: (href) => router.push(href),
};
}, [repoId, router]);
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 eeb2f2d17..06de30338 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -1,9 +1,10 @@
"use client";
+import { useCallback, useMemo } from "react";
import useSWR from "swr";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
-import { HealthFileDrawer } from "@repowise-dev/ui/health";
+import { HealthFileDrawer, useRelatedWork } from "@repowise-dev/ui/health";
import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import {
getPerformanceOpportunities,
@@ -13,6 +14,7 @@ import {
getFileOpportunity,
refactoringOpportunityHref,
} from "@/lib/api/file-opportunity";
+import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";
import { useFileBreakdown } from "./use-file-breakdown";
import type { HealthCounts } from "@repowise-dev/types/health";
@@ -65,11 +67,22 @@ export function HealthFileDrawerHost({
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
+ // What the other lenses hold for this file. One request, one read per lens.
+ const fetchRelated = useCallback(
+ (paths: string[]) => getRelatedWork(repoId, paths),
+ [repoId],
+ );
+ const related = useRelatedWork(fetchRelated, [filePath]);
+ const toRelated = useMemo(() => relatedWorkHref(repoId), [repoId]);
+
return (
<HealthFileDrawer
open={filePath !== null}
opportunity={opportunity}
refactoringOpportunityHref={(id) => refactoringOpportunityHref(repoId, id)}
+ related={related?.files?.[0]}
+ relatedWorkHref={toRelated}
+ onNavigate={(href) => router.push(href)}
onClose={onClose}
loading={isLoading}
metric={data?.metric ?? null}
diff --git a/packages/web/src/lib/api/related-work.ts b/packages/web/src/lib/api/related-work.ts
new file mode 100644
index 000000000..e07f78bce
--- /dev/null
+++ b/packages/web/src/lib/api/related-work.ts
@@ -0,0 +1,30 @@
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import type { RelatedWorkHref } from "@repowise-dev/ui/health";
+import { refactoringOpportunityHref } from "./file-opportunity";
+
+export { getRelatedWork } from "./code-health";
+
+/**
+ * Where one related item lives in this app. Each lens opens on its own surface:
+ * a refactoring plan or performance cause in its drawer, a finding on the
+ * file's health tab, Fix first on the Code Health overview that leads with it,
+ * dead code on its tab (it has no per-item drawer to open). Every id in a URL
+ * is encoded, here or by the helper that builds it.
+ */
+export function relatedWorkHref(repoId: string): RelatedWorkHref {
+ const prefix = `/repos/${repoId}`;
+ return (item, filePath) => {
+ switch (item.lens) {
+ case "refactoring":
+ return refactoringOpportunityHref(repoId, item.id);
+ case "performance":
+ return `${prefix}/code-health?tab=performance&opportunity=${encodeURIComponent(item.id)}`;
+ case "findings":
+ return `${fileEntityPath(prefix, filePath)}?tab=health`;
+ case "fix_first":
+ return `${prefix}/code-health`;
+ case "dead_code":
+ return `${prefix}/code-health?tab=dead-code`;
+ }
+ };
+}
diff --git a/tests/unit/analysis/test_related_work.py b/tests/unit/analysis/test_related_work.py
new file mode 100644
index 000000000..b9bde6d4d
--- /dev/null
+++ b/tests/unit/analysis/test_related_work.py
@@ -0,0 +1,90 @@
+"""``related_work``: rows from every lens grouped under the files asked about."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.health.fix_first.model import FixTarget
+from repowise.core.analysis.related_work import LENSES, related_work
+
+
+def _finding(fid: str, path: str, severity: str, line: int | None, **details) -> dict:
+ return {
+ "id": fid,
+ "file_path": path,
+ "biomarker_type": "complex_method",
+ "severity": severity,
+ "function_name": "run",
+ "line_start": line,
+ "details": details,
+ }
+
+
+def test_groups_by_file_in_request_order_and_drops_other_files() -> None:
+ out = related_work(
+ ["b.py", "a.py"],
+ findings=[_finding("f1", "a.py", "high", 3), _finding("f2", "elsewhere.py", "high", 1)],
+ dead_code=[{"id": "d1", "file_path": "b.py", "kind": "unused_export",
+ "symbol_name": "x", "start_line": 9, "confidence": 0.9,
+ "safe_to_delete": True}],
+ ).as_dict()
+ assert [f["file_path"] for f in out["files"]] == ["b.py", "a.py"]
+ b, a = out["files"]
+ assert list(b["lenses"]) == ["dead_code"]
+ assert b["lenses"]["dead_code"]["items"][0] == {
+ "lens": "dead_code", "id": "d1", "kind": "unused_export", "title": None,
+ "symbol": "x", "severity": None, "tier": "safe_to_delete", "rank": None, "line": 9,
+ }
+ assert [i["id"] for i in a["lenses"]["findings"]["items"]] == ["f1"]
+
+
+def test_findings_order_by_severity_then_line_and_cap_keeps_the_total() -> None:
+ rows = [
+ _finding("low", "a.py", "low", 1),
+ _finding("high_late", "a.py", "high", 50),
+ _finding("crit", "a.py", "critical", 99),
+ _finding("high_early", "a.py", "high", 5),
+ ]
+ lens = related_work(["a.py"], findings=rows, per_lens_limit=3).files[0].lenses["findings"]
+ assert [i.id for i in lens.items] == ["crit", "high_early", "high_late"]
+ assert lens.total == 4
+
+
+def test_flags_are_copied_only_when_the_row_carries_them() -> None:
+ out = related_work(
+ ["a.py"],
+ findings=[_finding("plain", "a.py", "high", 1),
+ _finding("old", "a.py", "high", 2, deprecated=True)],
+ ).as_dict()
+ plain, old = out["files"][0]["lenses"]["findings"]["items"]
+ assert "deprecated" not in plain and "code_origin" not in plain
+ assert old["deprecated"] is True
+
+
+def test_reads_orm_shaped_rows_and_fix_first_items() -> None:
+ refactoring = SimpleNamespace(
+ opportunity_id="refop_a", file_path="a.py", lead_refactoring_type="extract_method",
+ effort_bucket="M", rank_position=2, details_json="{}",
+ )
+ perf = [
+ SimpleNamespace(opportunity_id=f"perf_{r}", file_path="a.py", biomarker_type="io_in_loop",
+ intervention_symbol="a.py::load", actionability_state="fix",
+ rank_position=r, details_json="{}")
+ for r in (7, 0)
+ ]
+ item = SimpleNamespace(id="fix1_x", kind="refactor", title="Split run", tier="now", rank=4,
+ target=FixTarget(file_path="a.py", symbol="run", line_start=10))
+ lenses = related_work(
+ ["a.py"], refactoring=[refactoring], performance=perf, fix_first=[item]
+ ).files[0].lenses
+ assert list(lenses) == ["fix_first", "refactoring", "performance"]
+ assert [i.id for i in lenses["performance"].items] == ["perf_0", "perf_7"]
+ fix = lenses["fix_first"].items[0]
+ assert (fix.title, fix.rank, fix.tier, fix.line, fix.symbol) == ("Split run", 4, "now", 10, "run")
+ assert lenses["refactoring"].items[0].kind == "extract_method"
+
+
+def test_nothing_in_nothing_out() -> None:
+ out = related_work(["a.py"]).as_dict()
+ assert out == {"files": [{"file_path": "a.py", "lenses": {}}], "per_lens_limit": 5}
+ assert LENSES == ("findings", "fix_first", "refactoring", "performance", "dead_code")
diff --git a/tests/unit/persistence/test_file_paths_filters.py b/tests/unit/persistence/test_file_paths_filters.py
new file mode 100644
index 000000000..a51e09a8d
--- /dev/null
+++ b/tests/unit/persistence/test_file_paths_filters.py
@@ -0,0 +1,42 @@
+"""``file_paths`` on the findings and dead-code reads: an ``IN`` over files."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.crud.analysis import get_dead_code_findings, get_health_findings
+from repowise.core.persistence.models import DeadCodeFinding, HealthFinding
+from tests.unit.persistence.helpers import insert_repo
+
+_PATHS = ("a.py", "b.py", "c.py")
+
+
+async def test_health_findings_file_paths(async_session) -> None:
+ rid = (await insert_repo(async_session)).id
+ async_session.add_all(
+ HealthFinding(repository_id=rid, file_path=p, biomarker_type="complex_method",
+ severity="high")
+ for p in _PATHS
+ )
+ await async_session.commit()
+
+ scoped = await get_health_findings(async_session, rid, file_paths=["a.py", "c.py"])
+ assert sorted(f.file_path for f in scoped) == ["a.py", "c.py"]
+ assert await get_health_findings(async_session, rid, file_paths=[]) == []
+ assert len(await get_health_findings(async_session, rid)) == 3
+
+
+async def test_dead_code_findings_file_paths(async_session) -> None:
+ rid = (await insert_repo(async_session)).id
+ async_session.add_all(
+ DeadCodeFinding(repository_id=rid, kind="unused_export", file_path=p, symbol_name="x")
+ for p in _PATHS
+ )
+ await async_session.commit()
+
+ scoped = await get_dead_code_findings(async_session, rid, file_paths=("b.py",))
+ assert [f.file_path for f in scoped] == ["b.py"]
+ assert await get_dead_code_findings(async_session, rid, file_paths=[]) == []
+ assert len(await get_dead_code_findings(async_session, rid)) == 3
diff --git a/tests/unit/persistence/test_fix_first_loader.py b/tests/unit/persistence/test_fix_first_loader.py
index e2e9291dd..7878d67d1 100644
--- a/tests/unit/persistence/test_fix_first_loader.py
+++ b/tests/unit/persistence/test_fix_first_loader.py
@@ -214,3 +214,31 @@ async def test_loader_reads_extractions_for_a_finding_without_a_plan(async_sessi
plans=[*PLANS, extraction],
)
assert (loaded.items, loaded.totals) == (built.items, built.totals)
+
+
+async def test_every_limit_and_id_is_a_slice_of_one_build(async_session, monkeypatch) -> None:
+ from repowise.core.persistence.crud.analysis import fix_first as loader
+
+ rid = await seed_fix_first(async_session)
+ builds = 0
+ original = loader._build
+
+ async def counting(*args, **kwargs):
+ nonlocal builds
+ builds += 1
+ return await original(*args, **kwargs)
+
+ monkeypatch.setattr(loader, "_build", counting)
+ loader.clear_fix_first_cache()
+ rows = {"metrics": METRICS, "findings": FINDINGS, "refactoring": REFACTORING,
+ "performance": PERFORMANCE, "plans": PLANS}
+
+ full = await load_fix_first(async_session, rid, limit=None)
+ assert full == build_fix_first(**rows, limit=None)
+ assert await load_fix_first(async_session, rid, limit=1) == build_fix_first(**rows, limit=1)
+ assert await load_fix_first(async_session, rid) == build_fix_first(**rows)
+ second = full.items[1].id
+ assert await load_fix_first(async_session, rid, item_id=second) == build_fix_first(
+ **rows, item_id=second
+ )
+ assert builds == 1
diff --git a/tests/unit/server/test_related_work_route.py b/tests/unit/server/test_related_work_route.py
new file mode 100644
index 000000000..212c18b4e
--- /dev/null
+++ b/tests/unit/server/test_related_work_route.py
@@ -0,0 +1,80 @@
+"""POST /health/related-work: one read per lens, grouped by core, validated."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.crud import upsert_repository
+from repowise.core.persistence.models import DeadCodeFinding
+from repowise.server.routers.code_health import related_work_routes
+from tests.unit.persistence.test_fix_first_loader import seed_fix_first
+
+from .conftest import create_test_repo
+
+_LOADERS = (
+ ("crud", "get_health_findings"),
+ (None, "load_fix_first"),
+ ("crud", "list_refactoring_opportunities"),
+ (None, "list_performance_opportunities"),
+ ("crud", "get_dead_code_findings"),
+)
+
+
+async def _seeded(client, session, tmp_path) -> str:
+ repo = await create_test_repo(client, tmp_path)
+ await upsert_repository(session, name="r", local_path=repo["local_path"])
+ rid = repo["id"]
+ await seed_fix_first(session, rid)
+ session.add(DeadCodeFinding(repository_id=rid, kind="unused_export", file_path="src/repo.py",
+ symbol_name="old_helper", start_line=40, confidence=0.9))
+ await session.commit()
+ return rid
+
+
+def _url(rid: str) -> str:
+ return f"/api/repos/{rid}/health/related-work"
+
+
+async def test_every_lens_for_the_named_files_one_read_each(
+ client, session, tmp_path, monkeypatch
+) -> None:
+ rid = await _seeded(client, session, tmp_path)
+ calls: dict[str, int] = {}
+ for owner, name in _LOADERS:
+ target = related_work_routes.crud if owner else related_work_routes
+ original = getattr(target, name)
+
+ def spy(*args, _name=name, _original=original, **kwargs):
+ calls[_name] = calls.get(_name, 0) + 1
+ return _original(*args, **kwargs)
+
+ monkeypatch.setattr(target, name, spy)
+
+ resp = await client.post(_url(rid), json={"file_paths": ["src/repo.py", ".\\src\\core.py"]})
+ assert resp.status_code == 200, resp.text
+ assert calls == {name: 1 for _, name in _LOADERS}
+
+ body = resp.json()
+ assert [f["file_path"] for f in body["files"]] == ["src/repo.py", "src/core.py"]
+ repo, core = body["files"]
+ assert {"performance", "dead_code", "refactoring"} <= set(repo["lenses"])
+ assert repo["lenses"]["dead_code"]["items"][0]["symbol"] == "old_helper"
+ assert {"findings", "refactoring"} <= set(core["lenses"])
+ assert core["lenses"]["refactoring"]["items"][0]["id"] == "refop2_core"
+ assert "fix_first" in core["lenses"] or "fix_first" in repo["lenses"]
+ # The performance dimension is the performance lens's evidence, not a finding.
+ assert all(
+ i["kind"] != "io_in_loop" for f in body["files"] for i in f["lenses"].get("findings", {}).get("items", [])
+ )
+
+
+ "paths",
+ [[], ["a.py", "a.py"], ["/abs/a.py"], ["C:/a.py"], ["../a.py"], [""], [f"f{i}.py" for i in range(201)]],
+)
+async def test_rejects_what_is_not_1_to_200_unique_relative_paths(
+ client, session, tmp_path, paths
+) -> None:
+ rid = await _seeded(client, session, tmp_path)
+ resp = await client.post(_url(rid), json={"file_paths": paths})
+ assert resp.status_code == 422