Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): the last five dogfooding items — perf ranking key, fixed-cost profile, map payload, card paging, walk symlink shadowing (#1415)
Raghav Chamadiya282de05a7b42
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 173a25084..15be87f06 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -633,6 +633,30 @@ The opt-in enrichments:`file_weighted_deficit`. Full shapes in [`docs/layers/REFACTORING.md`](../layers/REFACTORING.md).- **dimension filter** narrows the returned findings to one pillar, e.g.`include=["biomarkers", "performance"]`.++**Performance findings rank on `perf_rank`, not on `health_impact`.** Every+performance finding carries `health_impact: 0` — the pillar is deliberately+never blended into the score — so ranking them by impact ordered them by nothing+and the cap kept whichever the tie broke to. Each performance row now carries an+integer `perf_rank` (absent on defect and maintainability rows, which rank on+`weighted_deficit`), and the returned list is ordered by it *within* each impact+tier, so the defect ordering is untouched. It is an ordering key, not a score:+nothing is blended into `score` / `performance_score`. It adds three signals the+row already carries, so you can re-rank on your own weights from the same+payload:++| signal | reads | why |+|---|---|---|+| the marker | `biomarker_type` | superlinear (`nested_loop_quadratic` 5) > N×M or lock-serialized (4) > one crossing per iteration, or one crossing proven on a hot path (3) > in-loop CPU/allocation (2) > cheap in-loop idioms (1) |+| the boundary | `details.boundary_kind` | `subprocess` 4 > `network` 3 > `db`/`lock` 2 > `filesystem` 1 — a process spawn in a loop is not a stat in a loop |+| the call shape | `details.cross_function` | +1. An intra-function loop is usually visibly bounded at the call site; a cross-function N+1 is the one nobody sees by reading the loop |++Request-reachability is read off the marker rather than a column:+`hot_path_sync_io` and `nested_loop_quadratic` are only ever emitted for a+function the perf ranker called hot (top-quintile call-graph in-degree, or a+churny/hotspot file), so their presence is already the proof. Deliberately not+`severity` — that column grades `hot_path_sync_io` below `io_in_loop` and takes+only two values across a whole repo's perf findings.- **`refactoring`** also emits `suggestion_legend`: `biomarker_type` → the prosesuggestion for that type, once per response rather than per finding. Join on`biomarker_type`. It is keyed off the ranked finding head and does not varydiff --git a/packages/core/alembic/versions/0051_graph_nodes_repo_type_index.py b/packages/core/alembic/versions/0051_graph_nodes_repo_type_index.pynew file mode 100644index 000000000..8bd05662e--- /dev/null+++ b/packages/core/alembic/versions/0051_graph_nodes_repo_type_index.py@@ -0,0 +1,54 @@+"""Index ``graph_nodes`` on ``(repository_id, node_type)``.++``node_type == "file"`` is the most-issued predicate on this table — the health+dashboard's language map and test-path set, the overview and stats routes, the+C4 builder, the answer pipeline's PageRank lookups — and nothing covered it. The+only index on the pair was the one behind ``uq_graph_node``, keyed+``(repository_id, node_id)``, so a ``node_type``-filtered read seeked on the+repository and then filtered the rest in memory: on the repowise index that is+36,480 rows scanned to return 3,449.++Measured there for the two reads ``get_health`` issues per dashboard call:+the language map 29.0ms -> 9.2ms and the test-path set 27.2ms -> 8.4ms.++The LIMIT-without-ORDER-BY hazard 0046 records applies to any new index and was+audited here: every ``node_type``-filtered query in the tree that carries a+``LIMIT`` also carries an ``ORDER BY`` (pagerank or in_degree), so no answer can+change with the plan.++Declared in ``GraphNode.__table_args__`` too. Local stores are created by+``init_db`` (whose additive reconciler back-fills declared indexes) and never+run Alembic, while hosted only ever sees Alembic, so both declarations are+needed and they converge on the same index. Same split as 0045 and 0046.++Revision ID: 0051+Revises: 0050+Create Date: 2026-08-11+"""++from __future__ import annotations++from collections.abc import Sequence++from alembic import op++# revision identifiers+revision: str = "0051"+down_revision: str | None = "0050"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_INDEX_NAME = "ix_graph_nodes_repo_type"+++def upgrade() -> None:+ op.create_index(+ _INDEX_NAME,+ "graph_nodes",+ ["repository_id", "node_type"],+ if_not_exists=True,+ )+++def downgrade() -> None:+ op.drop_index(_INDEX_NAME, table_name="graph_nodes", if_exists=True)diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.pyindex d63952465..9a7e63aac 100644--- a/packages/core/src/repowise/core/analysis/health/trends.py+++ b/packages/core/src/repowise/core/analysis/health/trends.py@@ -19,7 +19,9 @@ Two alert kinds are emitted, matching plan §4 Phase 4 P4.1:The module is intentionally state-free. Callers pass in the snapshothistory (oldest → newest) and receive a list of alerts back. No DBaccess lives here so trend logic stays unit-testable without an engine-or a session.+or a session. The one exception is ``_parsed_map`` below, a bounded+content-keyed cache over ``json.loads`` of a snapshot's per-file map — a pure+cache with no observable effect on any return value."""from __future__ import annotations@@ -27,6 +29,7 @@ from __future__ import annotationsimport jsonfrom dataclasses import dataclass, fieldfrom datetime import datetime+from functools import lru_cachefrom typing import Anyfrom .scoring import SCORE_FLOOR, SCORE_MAX@@ -301,6 +304,30 @@ class FileTrend:unclamped_delta: float | None = None+# A snapshot's ``{path: value}`` map is a per-*repo* blob — one JSON object+# holding every file's score — and this module reads it one file at a time. So a+# caller asking about N files paid ``N x len(history)`` parses of the same few+# blobs: the cross-function N+1 the health pillar's own ``json_parse_in_loop``+# biomarker exists to flag, in the health pillar. Measured on the repowise index+# (20 snapshots averaging 186 KB each), ``get_health`` on a ``module:`` target+# expanding to 822 files spent **13.0s** here; memoized, 0.4s.+#+# Keyed on the raw JSON **text**, not on the snapshot object. Content-keying+# makes staleness impossible by construction (different bytes are a different+# key), needs no hashable/weak-referenceable snapshot — a plain dataclass in a+# test is neither — and lets two callers holding different rows for the same+# stored snapshot share one parse. The window a caller reads is 20 snapshots x 2+# maps, so ``maxsize`` covers a full window with headroom; the ceiling is that a+# long-lived server holds up to 64 parsed maps, which is what bounds it.+@lru_cache(maxsize=64)+def _parsed_map(raw: str) -> Any:+ """``json.loads(raw)``, memoized. ``None`` when the text will not parse."""+ try:+ return json.loads(raw)+ except (ValueError, TypeError):+ return None++def _value_in_snapshot(snap: Any, column: str, file_path: str) -> float | None:"""Read one float out of a snapshot's compact ``{path: value}`` JSON map.@@ -311,10 +338,7 @@ def _value_in_snapshot(snap: Any, column: str, file_path: str) -> float | None:raw = getattr(snap, column, None)if not raw:return None- try:- parsed = json.loads(raw)- except (ValueError, TypeError):- return None+ parsed = _parsed_map(raw)val = parsed.get(file_path) if isinstance(parsed, dict) else Noneif val is None:return Nonediff --git a/packages/core/src/repowise/core/fs_walk.py b/packages/core/src/repowise/core/fs_walk.pyindex 4b9c3a3d4..4ddfeb2ea 100644--- a/packages/core/src/repowise/core/fs_walk.py+++ b/packages/core/src/repowise/core/fs_walk.py@@ -27,6 +27,11 @@ Guarantees:Detection is free: ``.git`` appears in ``os.walk``'s own listings.- Symlinks are never followed; junction/hard-link cycles are detected viarealpath tracking (Windows ``os.walk`` can't see them via inodes).+ - A link (symlink or junction) whose target is **inside** the walk root is+ pruned, so the target's subtree is walked exactly once and under its own+ name. Recording the target as visited instead let whichever of the pair+ sorted first win, and a link sorted ahead of its target silently removed+ the target from the walk.- Depth is capped as a final safety net."""@@ -103,6 +108,24 @@ PRUNED_DIRS_DERIVED: frozenset[str] = PRUNED_DIRS | frozenset({"dist", "build",_MAX_WALK_DEPTH = 64+def _normcase(p: str) -> str:+ """Path in the filesystem's own case convention (a no-op off Windows)."""+ return os.path.normcase(p)+++def _is_within(candidate: str, root_real: str) -> bool:+ """True when *candidate* is *root_real* or sits underneath it.++ String-prefixed on purpose: both sides are already ``realpath`` output, so+ there is nothing left to resolve, and ``commonpath`` raises across drives+ (a junction to ``D:\\`` from a walk rooted on ``C:\\`` is the normal case+ this has to answer ``False`` for, not raise on).+ """+ root = _normcase(root_real.rstrip(os.sep))+ cand = _normcase(candidate.rstrip(os.sep))+ return cand == root or cand.startswith(root + os.sep)++def walk_repo(root: Path | str,*,@@ -154,6 +177,22 @@ def walk_repo(# Windows junctions and other cycles ``os.walk`` can't detect via# inode (Windows doesn't expose real inodes outside NTFS proper).cycle_pruned: list[str] = []+ # The resolved form of *this* directory, so "is the child itself a link"+ # can be asked without the answer depending on the path the caller+ # happened to pass in. Comparing ``realpath(child)`` against+ # ``abspath(child)`` looks equivalent and is not: ``abspath`` resolves+ # nothing, so a symlink anywhere in the *root's own prefix* makes every+ # child at every depth compare unequal, and the walk prunes the entire+ # tree. That is not exotic — macOS ``/tmp`` is a symlink to+ # ``/private/tmp``, container bind mounts and mapped drives do the same,+ # and a repo checked out under one would have indexed as empty.+ # Resolving the parent once per directory keeps both sides of the+ # comparison resolved to the same depth, so only a genuine reparse point+ # differs.+ try:+ parent_real = os.path.realpath(dirpath)+ except OSError:+ parent_real = str(dirpath)for d in dirnames:child = os.path.join(dirpath, d)try:@@ -161,6 +200,28 @@ def walk_repo(except OSError:cycle_pruned.append(d)continue+ # A reparse point — symlink, junction, bind mount — resolving+ # somewhere else. Its target is NOT territory this entry owns, and+ # recording it as visited is what let a link *delete* its target's+ # subtree from the walk: whichever of the two sorted first won, and+ # a link sorted ahead of its target removed the target entirely+ # (measured on a synthetic tree: ``linked -> svc`` took ``svc`` and+ # ``svc/api`` out of the result, 6 directories down to 4).+ #+ # In-tree targets are pruned instead: the walk reaches them under+ # their real name, and descending the link as well would either+ # duplicate the subtree or — for a junction, which ``followlinks``+ # does not suppress because Windows tags it a mount point rather+ # than a symlink — report every file under the *link's* path+ # instead of its own. Out-of-tree targets keep the old behaviour;+ # they are a genuine external tree, and cycle protection still+ # needs their realpath because ``os.walk`` will descend a junction+ # into one.+ if _normcase(child_real) != _normcase(+ os.path.join(parent_real, d)+ ) and _is_within(child_real, root_real):+ cycle_pruned.append(d)+ continueif child_real in visited_real:cycle_pruned.append(d)continuediff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex a60f62aca..36a3cf6fa 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -7,6 +7,7 @@ every public name, so existing imports are unaffected.from __future__ import annotationsimport json+from collections.abc import Sequencefrom sqlalchemy import and_, delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -613,6 +614,7 @@ async def get_graph_nodes_by_ids(async def get_test_file_paths(session: AsyncSession,repository_id: str,+ paths: Sequence[str] | None = None,) -> set[str]:"""Relative paths of every file the ingester classified as test material.@@ -626,9 +628,18 @@ async def get_test_file_paths(``is_test`` too and their ``node_id`` is a ``"<path>::<name>"`` composite,which would never match a file path but would inflate the read.- Narrow in columns, not in rows — no index covers ``node_type`` or- ``is_test``, so this scans the repo's nodes (~55 ms on a 35k-node index).- A caller serializing no file row and no finding should skip it.+ *paths* narrows the read to "which of **these** are tests". A caller that+ only ever asks ``path in result`` for a known path set — ``get_health`` in+ targeted mode, where the caller named the files — pays for a keyed seek on+ ``uq_graph_node`` instead of the repo-wide read. ``None`` keeps the+ repo-wide answer, which is what the dashboard's production/test *split*+ needs (it partitions a finding list whose paths are not known up front).+ Passing an empty sequence means "no paths asked about" and returns an empty+ set without a query — not the same thing as ``None``.++ Narrow in columns, and now optionally in rows. The repo-wide form seeks on+ ``ix_graph_nodes_repo_type`` (0051); before that index it scanned every node+ the repo has (~27 ms on this 36k-node index, ~8 ms after).Degrades to "nothing is test material" when the graph is missing or lagsthe health pass. That is the safe direction: a caller sees the unsplit@@ -636,13 +647,25 @@ async def get_test_file_paths(Censused on this repo's index — 1,030 test file nodes, none of them absentfrom ``health_file_metrics``."""- result = await session.execute(- select(GraphNode.node_id).where(- GraphNode.repository_id == repository_id,- GraphNode.node_type == "file",- GraphNode.is_test.is_(True),- )+ if paths is not None and not paths:+ return set()+ q = select(GraphNode.node_id).where(+ GraphNode.repository_id == repository_id,+ GraphNode.node_type == "file",+ GraphNode.is_test.is_(True),)+ if paths is not None:+ # Chunked like ``get_graph_nodes_bulk`` above — a ``module:`` target+ # expands to every file in the module, which on a monorepo is more+ # bind parameters than SQLite's limit allows in one statement.+ out: set[str] = set()+ ordered = list(paths)+ for i in range(0, len(ordered), _BATCH_SIZE):+ batch = ordered[i : i + _BATCH_SIZE]+ rows = await session.execute(q.where(GraphNode.node_id.in_(batch)))+ out |= {row[0] for row in rows.all()}+ return out+ result = await session.execute(q)return {row[0] for row in result.all()}diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 0b1839f4a..505269892 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -240,7 +240,18 @@ class GraphNode(Base):DateTime(timezone=True), nullable=False, default=_now_utc)- __table_args__ = (UniqueConstraint("repository_id", "node_id", name="uq_graph_node"),)+ __table_args__ = (+ UniqueConstraint("repository_id", "node_id", name="uq_graph_node"),+ # ``node_type == "file"`` is the most-issued predicate on this table and+ # nothing covered it: ``uq_graph_node`` is keyed ``(repository_id,+ # node_id)``, so every "all the file nodes" read seeked on the repo and+ # then filtered ~36k rows in memory to return ~3.4k. Measured on the+ # repowise index, the two reads ``get_health`` issues per dashboard call+ # (language map, test-path set): 29.0ms -> 9.2ms and 27.2ms -> 8.4ms.+ # Audited for the LIMIT-without-ORDER-BY hazard 0046 records — every+ # ``node_type``-filtered query in the tree that limits also orders.+ Index("ix_graph_nodes_repo_type", "repository_id", "node_type"),+ )class ExternalSystem(Base):diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex c3c1f44d4..447c9c981 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -48,12 +48,151 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_meta+# How much a single execution of each I/O boundary costs, as an order of+# magnitude rather than a measurement: a process spawn is milliseconds, a wire+# round-trip is hundreds of microseconds up, a pooled local query is tens, and a+# filesystem call is usually a page-cache hit. "A subprocess spawn in a loop is+# not a filesystem stat in a loop" is the whole point of ranking on this.+_PERF_BOUNDARY_POINTS = {"subprocess": 4, "network": 3, "db": 2, "lock": 2, "filesystem": 1}++# What the marker itself proves about *how often* the boundary cost is paid.+# Two independent proofs, and neither dominates — which is why the three signals+# are added rather than multiplied:+#+# * a **multiplier** — the cost repeats per iteration (N), per nested pair+# (N x M), or quadratically. Every ``*_in_loop`` marker carries this.+# * **hotness** — the cost is paid on a request-reachable path.+# ``hot_path_sync_io`` and ``nested_loop_quadratic`` are the request-+# reachability signal, and it needs no new column: both are emitted **only**+# for a function ``perf.ranking.PerfRanker`` called hot (top-quintile+# call-graph in-degree, or a churny/hotspot file), so their presence is+# already a proof. ``blocking_io_under_lock`` proves something adjacent —+# every thread serializes behind the wait.+#+# ``hot_path_sync_io`` therefore sits level with a plain loop marker, not above+# it: it proves hotness and no multiplier, and a loop proves a multiplier and no+# hotness. Boundary kind is what separates them in practice.+#+# Deliberately not ``severity``: the column disagrees with this ordering and+# cannot be fixed from here without a re-score. ``hot_path_sync_io`` is written+# ``LOW`` and ``io_in_loop`` ``MEDIUM``, so the marker carrying a hotness proof+# is graded *below* the ungated one — and on this repo severity takes exactly+# two values across all 697 perf findings (522 medium, 175 low), which is not+# an ordering.+#+# Exhaustive over the 20 detectors declaring ``category = "performance"``;+# ``test_perf_rank.py`` fails if a new one is added without a weight, so the+# default below is a guard rather than a resting place.+_PERF_MARKER_POINTS = {+ # Superlinear, and gated on hotness.+ "nested_loop_quadratic": 5,+ # N x M round-trips, or a wait every thread queues behind.+ "nested_loop_with_io": 4,+ "blocking_io_under_lock": 4,+ "sql_cartesian_join": 4,+ # One boundary crossing per iteration — the N+1 family.+ "io_in_loop": 3,+ "serial_await_in_loop": 3,+ "lock_in_loop": 3,+ "goroutine_in_unbounded_loop": 3,+ "resource_construction_in_loop": 3,+ # One crossing, but proven to sit on a hot path.+ "hot_path_sync_io": 3,+ # In-loop CPU/allocation costs: real, and orders below a round-trip.+ "blocking_sync_in_async": 2,+ "pandas_iterrows_in_loop": 2,+ "pd_concat_in_loop": 2,+ "json_parse_in_loop": 2,+ "array_spread_in_reduce": 2,+ "defer_in_loop": 2,+ "regex_compile_in_loop": 1,+ "string_concat_in_loop": 1,+ "membership_test_against_list_in_loop": 1,+ "list_insert_zero_in_loop": 1,+}++# Unknown marker. Deliberately the floor, not the middle: a detector added+# without a weight should under-rank rather than jump the queue, the same+# degrade-to-no-signal direction the perf gate itself takes.+_PERF_UNKNOWN_MARKER_POINTS = 1++# A hit whose loop and whose sink are in different functions. Worth a point on+# its own: an intra-function loop is often visibly bounded at the call site,+# while a cross-function N+1 is the one nobody sees by reading the loop.+_PERF_CROSSFN_POINTS = 1+++def _perf_rank(biomarker_type: str | None, details: Any) -> int:+ """Order-of-magnitude ranking key for one ``performance`` finding.++ The performance dimension had none. Every finding carries+ ``health_impact: 0`` by construction — the dimension is deliberately never+ blended into the score — so the list came back in whatever order the impact+ tie broke, which is file order. "Which of these 697 matters" was+ unanswerable from the payload, and worse, the *cap* was arbitrary too: with+ ``include=['performance']`` the head is 20 of 697 chosen by nothing.++ Additive over three signals the payload already carries, in points rather+ than a calibrated scale, because it is an **ordering key and not a score**.+ Nothing here is blended into ``score`` / ``performance_score``, and nothing+ here was fitted against the defect corpus — the frozen weights this file+ documents stay frozen. A caller who disagrees can re-rank: every input is in+ ``biomarker_type`` and ``details`` on the same row.+ """+ if not isinstance(details, dict):+ details = {}+ points = _PERF_MARKER_POINTS.get(biomarker_type or "", _PERF_UNKNOWN_MARKER_POINTS)+ points += _PERF_BOUNDARY_POINTS.get(details.get("boundary_kind") or "", 0)+ if details.get("cross_function"):+ points += _PERF_CROSSFN_POINTS+ return points+++def _rank_emitted(rows: list[Any]) -> list[Any]:+ """Break the ``health_impact`` ties that the performance dimension is made of.++ Rows arrive impact-ordered from SQL, which decides nothing among the+ performance findings: they all carry ``0``, so the head was whatever the tie+ broke to — file order. This re-sorts **within** each impact tier, so the+ defect ordering every other block is built on is untouched (identical+ impacts were already interchangeable) and the perf tier stops being+ alphabetical.++ ``file_path`` is the final key so the order is total and reproducible; two+ findings that rank the same used to swap places between calls on nothing.+ Rows with no ``details_json`` attribute — the narrow dashboard read, unless+ the caller filtered to ``performance`` — rank on the marker alone, which is+ exactly the tier where the rank cannot move a row anyway.+ """+ if not rows:+ return rows++ def key(r: Any) -> tuple[float, int, str]:+ impact = float(getattr(r, "health_impact", 0.0) or 0.0)+ dimension = getattr(r, "dimension", None) or "defect"+ if dimension != "performance":+ return (-impact, 0, getattr(r, "file_path", "") or "")+ raw = getattr(r, "details_json", None)+ try:+ details = json.loads(raw) if raw else {}+ except Exception:+ details = {}+ return (+ -impact,+ -_perf_rank(getattr(r, "biomarker_type", None), details),+ getattr(r, "file_path", "") or "",+ )++ return sorted(rows, key=key)+def _serialize_finding(f: HealthFinding) -> dict[str, Any]:try:details = json.loads(f.details_json) if f.details_json else {}except Exception:details = {}+ dimension = getattr(f, "dimension", None) or "defect"+ rank = {"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {}return {"biomarker_type": f.biomarker_type,"severity": f.severity,@@ -67,7 +206,11 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:"status": f.status,# Health pillar this finding homes under (defect / maintainability /# performance) for per-dimension filtering.- "dimension": getattr(f, "dimension", None) or "defect",+ "dimension": dimension,+ # Performance rows only — see ``_perf_rank``. Absent everywhere else+ # rather than zero: a defect finding ranks on ``weighted_deficit`` and a+ # 0 here would read as "measured, and it is nothing".+ **rank,}@@ -782,11 +925,6 @@ async def get_health(HealthFileMetric.repository_id == repository.id)exclude_spec = _get_exclude_spec(ctx.path)- # Test material, from the flag ingestion already decided per file.- # Gated on ``needs_test_paths`` — see the note at its definition.- test_paths: set[str] = set()- if needs_test_paths:- test_paths = await get_test_file_paths(session, repository.id)indexed_rows = list((await session.execute(all_metrics_q)).scalars().all())all_metrics = filter_rows_by_attr(indexed_rows, "file_path", exclude_spec)# Paths the index knows about but the exclude config drops. Kept so an@@ -812,6 +950,22 @@ async def get_health(effective_targets = file_targets if scoped else []nothing_resolved = scoped and not effective_targets+ # Test material, from the flag ingestion already decided per file.+ # Gated on ``needs_test_paths`` — see the note at its definition — and+ # placed after the ``module:`` expansion so targeted mode can scope it.+ #+ # Targeted mode only ever asks ``path in test_paths`` for paths the+ # caller named, so it reads exactly those; dashboard mode partitions a+ # ranked finding list whose paths are not known until the read below+ # runs, so it keeps the repo-wide answer. Measured on this repo, that+ # is 32.9ms -> 0.6ms on a single-file target — a quarter of the whole+ # call, paid to answer "is this one file a test".+ test_paths: set[str] = set()+ if needs_test_paths:+ test_paths = await get_test_file_paths(+ session, repository.id, effective_targets if scoped else None+ )+open_findings = (HealthFinding.repository_id == repository.id,HealthFinding.status == "open",@@ -853,7 +1007,9 @@ async def get_health(exclude_spec,)lead_rows: list[Any] = finding_rows- emitted = [f for f in finding_rows if _in_dimensions(f, dimension_filter)]+ emitted = _rank_emitted(+ [f for f in finding_rows if _in_dimensions(f, dimension_filter)]+ )finding_rows = emitted[:limit]legend_rows: list[Any] = finding_rowselse:@@ -862,17 +1018,29 @@ async def get_health(# and ``id`` to fetch the head. SQLAlchemy ``Row`` exposes these as# attributes, so the reduction and the exclude filter both run# against it unchanged.+ #+ # ``details_json`` joins them only when the caller asked for the+ # performance dimension, because that is the only case where a perf+ # finding can reach the head at all: every one carries+ # ``health_impact: 0``, so in a mixed list all ~10k defect findings+ # sort above them and the rank could not move a row. Measured on+ # this repo the column costs 6.6ms on the read (parsing the 697 perf+ # rows out of 10,740 costs a further 1.2ms), which is worth paying+ # for the one call it changes and not worth paying for the default.+ lite_cols = [+ HealthFinding.id,+ HealthFinding.file_path,+ HealthFinding.health_impact,+ HealthFinding.biomarker_type,+ HealthFinding.reason,+ HealthFinding.dimension,+ ]+ if "performance" in dimension_filter:+ lite_cols.append(HealthFinding.details_json)lite_rows = list((await session.execute(- select(- HealthFinding.id,- HealthFinding.file_path,- HealthFinding.health_impact,- HealthFinding.biomarker_type,- HealthFinding.reason,- HealthFinding.dimension,- )+ select(*lite_cols).where(*open_findings).order_by(HealthFinding.health_impact.desc()))@@ -882,7 +1050,7 @@ 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 = [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, dimension_filter)])# 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 ofdiff --git a/packages/server/src/repowise/server/routers/code_health/files_routes.py b/packages/server/src/repowise/server/routers/code_health/files_routes.pyindex 9a57d4036..8968f2275 100644--- a/packages/server/src/repowise/server/routers/code_health/files_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/files_routes.py@@ -48,6 +48,16 @@ async def list_health_files(only_hotspots: bool = Query(False),only_untested: bool = Query(False),only_failing: bool = Query(False, description="score < 7"),+ fields: str = Query(+ "full",+ pattern="^(full|summary)$",+ description=(+ "'summary' omits the optional per-row keys only the file table and "+ "drawer read (duplication_pct, defect_score, and the "+ "primary_biomarker / primary_reason / total_deduction lead), and "+ "narrows the finding read that produces them."+ ),+ ),session: AsyncSession = Depends(get_db_session),) -> dict:if sort not in _SORT_FIELDS:@@ -86,11 +96,23 @@ async def list_health_files(total = len(filtered)page = filtered[offset : offset + limit]- # Leads only for the page's files — enough to carry the top-reason chip and- # the magnitude tiebreak without loading every finding for every row.- page_paths = {m.file_path for m in page}- findings = await crud.get_health_findings(session, repo_id)- leads = _leads_by_file([f for f in findings if f.file_path in page_paths])+ summary = fields == "summary"+ # Two reads, and ``summary`` needs only the narrow one. The full row's+ # dominant-cause lead is reduced from *every* open finding (this repo: 10,740+ # rows, 1.66 MB of ``details_json`` hydrated to reach four attributes), while+ # the performance lens needs only the perf dimension (697 rows). A caller+ # that does not print the lead should not pay for the wide read to compute+ # it — the map is exactly that caller, and it is the biggest request the+ # page makes.+ leads: dict[str, dict] = {}+ if summary:+ findings = await crud.get_health_findings(session, repo_id, dimension="performance")+ else:+ findings = await crud.get_health_findings(session, repo_id)+ # Leads only for the page's files — enough to carry the top-reason chip+ # and the magnitude tiebreak without loading every finding for every row.+ page_paths = {m.file_path for m in page}+ leads = _leads_by_file([f for f in findings if f.file_path in page_paths])# Per-file performance signal for the map's performance lens: open perf-# finding counts + whether a perf detector ran on the file's language. Colors# the lens by findings/coverage instead of the narrow-band [8,10] score.@@ -110,6 +132,7 @@ async def list_health_files(leads.get(m.file_path),perf_findings=perf_counts.get(m.file_path, 0),perf_analyzed=lang_by_path.get(m.file_path) in perf_langs,+ summary=summary,)for m in page],diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.pyindex 9e191850c..20b7ea5dc 100644--- a/packages/server/src/repowise/server/routers/code_health/serializers.py+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py@@ -77,35 +77,56 @@ def _metric_to_dict(*,perf_findings: int = 0,perf_analyzed: bool | None = None,+ summary: bool = False,) -> dict:- return {+ """One file row. ``summary=True`` omits the keys only the table and drawer read.++ Not "nulled" — **omitted**. Measured over the code-health map's 2,000-row+ request, the three lead keys and the two detail keys dropped here are+ 432,081 B of a 1,060,095 B payload, and only 177,527 B of that is lead+ *values*: the key names are the rest, so a row that nulls them saves a+ fraction of what a row that drops them saves.++ **Exactly the keys already declared optional on ``HealthFileMetric``**, which+ is the line that keeps this safe rather than a judgement about who reads+ what: every consumer already handles them absent or null (they *are* null on+ any row whose findings were not loaded), and the wire type needs no change.+ ``max_ccn`` / ``max_nesting`` are unread by the map too and stay anyway —+ they are required on the type, they are 56 KB of the 488 KB, and dropping+ them would trade the whole safety argument for 5%.+ """+ # Built in the historical key order so the full row stays byte-identical.+ out: dict = {"file_path": m.file_path,"score": round(m.score, 2),"max_ccn": m.max_ccn,"max_nesting": m.max_nesting,- "nloc": m.nloc,- "has_test_file": m.has_test_file,- "line_coverage_pct": m.line_coverage_pct,- "module": m.module,- "duplication_pct": getattr(m, "duplication_pct", None),+ }+ out["nloc"] = m.nloc+ out["has_test_file"] = m.has_test_file+ out["line_coverage_pct"] = m.line_coverage_pct+ out["module"] = m.module+ if not summary:+ out["duplication_pct"] = getattr(m, "duplication_pct", None)# Per-dimension scores from the three-signal split. ``score`` above stays# the overall surfaced number (== defect_score for now).- # ``performance_score`` is computed but not yet surfaced as its own pillar.- "defect_score": _round_opt(getattr(m, "defect_score", None)),- "maintainability_score": _round_opt(getattr(m, "maintainability_score", None)),- "performance_score": _round_opt(getattr(m, "performance_score", None)),- # Performance lens inputs for the code-health map: the open perf-finding- # count colors the heat, and ``perf_analyzed`` (did a detector run on this- # language?) separates green ("analyzed, none found") from grey ("never- # looked"). Presentation only — the score above is untouched.- "performance_findings": perf_findings,- "performance_analyzed": perf_analyzed,+ out["defect_score"] = _round_opt(getattr(m, "defect_score", None))+ # ``performance_score`` is computed but not yet surfaced as its own pillar.+ out["maintainability_score"] = _round_opt(getattr(m, "maintainability_score", None))+ out["performance_score"] = _round_opt(getattr(m, "performance_score", None))+ # Performance lens inputs for the code-health map: the open perf-finding+ # count colors the heat, and ``perf_analyzed`` (did a detector run on this+ # language?) separates green ("analyzed, none found") from grey ("never+ # looked"). Presentation only — the score above is untouched.+ out["performance_findings"] = perf_findings+ out["performance_analyzed"] = perf_analyzed+ if not summary:# Dominant-cause lead + pre-clamp magnitude (null when findings weren't# loaded for this row, or the file is clean). Additive; readers degrade.- "primary_biomarker": lead.get("primary_biomarker") if lead else None,- "primary_reason": lead.get("primary_reason") if lead else None,- "total_deduction": lead.get("total_deduction") if lead else None,- }+ out["primary_biomarker"] = lead.get("primary_biomarker") if lead else None+ out["primary_reason"] = lead.get("primary_reason") if lead else None+ out["total_deduction"] = lead.get("total_deduction") if lead else None+ return outdef _file_trend_to_dict(t: FileTrend) -> dict:diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex f99b02616..31f9c8b12 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -326,6 +326,16 @@ export interface HealthFilesQuery {only_hotspots?: boolean;only_untested?: boolean;only_failing?: boolean;+ /**+ * `"summary"` returns rows without the optional keys only the file table and+ * drawer read — `duplication_pct`, `defect_score`, and the+ * `primary_biomarker` / `primary_reason` / `total_deduction` lead — and lets+ * the server skip the repo-wide finding read that produces the lead. Measured+ * on the code-health map's 2,000-row request: 1,060,095 B -> 628,014 B.+ * Every omitted key is optional on {@link HealthFileMetric}, so a `summary`+ * row parses as one; ask for `"full"` (the default) if you print any of them.+ */+ fields?: "full" | "summary";}/* ------------------------------------------------------------------ *diff --git a/packages/ui/__tests__/health/refactoring-target-list.test.tsx b/packages/ui/__tests__/health/refactoring-target-list.test.tsxnew file mode 100644index 000000000..0e59eac56--- /dev/null+++ b/packages/ui/__tests__/health/refactoring-target-list.test.tsx@@ -0,0 +1,89 @@+import { describe, it, expect } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import {+ RefactoringTargetList,+ type RefactoringTarget,+} from "../../src/health/refactoring-target-list.js";++const CARD_PAGE = 50;++function targets(n: number): RefactoringTarget[] {+ return Array.from({ length: n }, (_, i) => ({+ file_path: `src/f${String(i).padStart(3, "0")}.py`,+ score: 1.0,+ nloc: 900 - i,+ primary_biomarker: "brain_method",+ primary_severity: "high" as const,+ primary_reason: "Oversized, deeply-nested function.",+ primary_function: "_run",+ primary_line_start: 10,+ primary_line_end: 400,+ total_impact: 6.2,+ finding_count: 3,+ biomarkers: ["brain_method"],+ effort_bucket: "XL" as const,+ impact_per_effort: 1.24,+ }));+}++function renderedPaths(): string[] {+ return Array.from(document.querySelectorAll("[data-refactoring-card]")).map(+ (el) => el.getAttribute("data-refactoring-card") ?? "",+ );+}++describe("RefactoringTargetList paging", () => {+ it("mounts a page of cards, not the whole queue", () => {+ // The queue's own "Load more" raises the fetch to QUEUE_MAX = 500, and+ // every one of those used to be mounted as a full card in one commit.+ render(<RefactoringTargetList targets={targets(500)} />);+ expect(renderedPaths()).toHaveLength(CARD_PAGE);+ expect(renderedPaths()[0]).toBe("src/f000.py");+ });++ it("says how many are left and reveals another page per click", () => {+ render(<RefactoringTargetList targets={targets(120)} />);+ expect(screen.getByRole("button", { name: /Show 50 more \(70 remaining\)/ })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: /Show 50 more/ }));+ expect(renderedPaths()).toHaveLength(100);++ // The last page is short, and the control says so rather than over-promising.+ fireEvent.click(screen.getByRole("button", { name: /Show 20 more \(20 remaining\)/ }));+ expect(renderedPaths()).toHaveLength(120);+ expect(screen.queryByRole("button", { name: /Show .* more/ })).not.toBeInTheDocument();+ });++ it("shows a short list whole, with no control", () => {+ render(<RefactoringTargetList targets={targets(3)} />);+ expect(renderedPaths()).toHaveLength(3);+ expect(screen.queryByRole("button", { name: /remaining/ })).not.toBeInTheDocument();+ });++ it("opens enough pages to reach a highlighted target past the window", () => {+ // The quadrant highlights by file path and the card carries the only DOM+ // anchor for it, so a click on a deep dot would otherwise scroll to a node+ // that was never mounted — a silent no-op, and the failure a naive cap+ // introduces.+ render(<RefactoringTargetList targets={targets(300)} highlightedPath="src/f210.py" />);+ expect(renderedPaths()).toContain("src/f210.py");+ // Rounded up to a whole page, not "everything up to it".+ expect(renderedPaths()).toHaveLength(250);+ });++ it("returns to the first page when the list changes", () => {+ // Re-filtering is a new question; leaving the reader three pages deep in+ // results they have not seen is worse than the scroll they lose.+ const { rerender } = render(<RefactoringTargetList targets={targets(300)} />);+ fireEvent.click(screen.getByRole("button", { name: /Show 50 more/ }));+ expect(renderedPaths()).toHaveLength(100);++ rerender(<RefactoringTargetList targets={targets(300).slice(10)} />);+ expect(renderedPaths()).toHaveLength(CARD_PAGE);+ });++ it("still shows the empty state", () => {+ render(<RefactoringTargetList targets={[]} emptyMessage="Nothing here." />);+ expect(screen.getByText("Nothing here.")).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsxindex 8a2335ec9..252f2df60 100644--- a/packages/ui/src/health/refactoring-target-list.tsx+++ b/packages/ui/src/health/refactoring-target-list.tsx@@ -1,3 +1,6 @@+"use client";++import { useEffect, useMemo, useState } from "react";import {RefactoringCard,type RefactoringTarget,@@ -5,6 +8,17 @@ import {type FindingStatus,} from "./refactoring-card";+/**+ * Cards rendered per page. Matches the files view's `PAGE_SIZE`, deliberately:+ * the queue's "Load more" raises the *fetch* to `QUEUE_MAX = 500`, and every one+ * of those was previously mounted as a full `RefactoringCard` — tens of+ * thousands of DOM nodes in one commit, on top of the payload they arrived in.+ * Paging here rather than in the caller fixes it for every consumer of this+ * list at once, and it works per *group* when the queue is grouped, which a cap+ * applied to the fetched array could not do.+ */+const CARD_PAGE = 50;+export interface RefactoringTargetListProps {targets: RefactoringTarget[];onSelect?: ((target: RefactoringTarget) => void) | undefined;@@ -28,6 +42,28 @@ export function RefactoringTargetList({emptyMessage = "No refactoring targets match the current filters.",highlightedPath,}: RefactoringTargetListProps) {+ const [visible, setVisible] = useState(CARD_PAGE);++ // A new list is a new question — re-filtering or re-sorting must not leave+ // the reader several pages deep in results they have not seen.+ useEffect(() => {+ setVisible(CARD_PAGE);+ }, [targets]);++ // A highlighted target past the window would be invisible *and* unscrollable:+ // the quadrant highlights by file path and the card carries the only DOM+ // anchor for it, so a click on a deep dot would silently do nothing. Open+ // enough pages to include it.+ const highlightIndex = useMemo(+ () =>+ highlightedPath ? targets.findIndex((t) => t.file_path === highlightedPath) : -1,+ [targets, highlightedPath],+ );+ const shown = Math.max(+ visible,+ highlightIndex >= 0 ? Math.ceil((highlightIndex + 1) / CARD_PAGE) * CARD_PAGE : 0,+ );+if (targets.length === 0) {return (<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">@@ -35,20 +71,32 @@ export function RefactoringTargetList({</div>);}+ const remaining = targets.length - shown;return (- <div className="grid gap-3">- {targets.map((t) => (- <RefactoringCard- key={t.file_path}- target={t}- onSelect={onSelect}- onStatusChange={onStatusChange}- onGeneratePrompt={onGeneratePrompt}- onLoadFindings={onLoadFindings}- highlighted={highlightedPath === t.file_path}- />- ))}- </div>+ <>+ <div className="grid gap-3">+ {targets.slice(0, shown).map((t) => (+ <RefactoringCard+ key={t.file_path}+ target={t}+ onSelect={onSelect}+ onStatusChange={onStatusChange}+ onGeneratePrompt={onGeneratePrompt}+ onLoadFindings={onLoadFindings}+ highlighted={highlightedPath === t.file_path}+ />+ ))}+ </div>+ {remaining > 0 ? (+ <button+ type="button"+ onClick={() => setVisible(shown + CARD_PAGE)}+ className="mt-3 w-full rounded-md border border-[var(--color-border-default)] px-3 py-2 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ >+ Show {Math.min(CARD_PAGE, remaining)} more ({remaining} remaining)+ </button>+ ) : null}+ </>);}diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 4bcc0ac7b..1908202cb 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -156,10 +156,18 @@ export default function CodeHealthPage() {);// Every file (NLOC-first) for the map — one big pull, shared across overlays- // so switching the lens never refetches.+ // 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}`,- () => listHealthFiles(repoId, { limit: MAP_FILE_LIMIT, sort: "nloc", order: "desc" }),+ () =>+ listHealthFiles(repoId, {+ limit: MAP_FILE_LIMIT,+ sort: "nloc",+ order: "desc",+ fields: "summary",+ }),{ revalidateOnFocus: false },);diff --git a/tests/unit/health/test_trends.py b/tests/unit/health/test_trends.pyindex dc5e2b98a..251b00aa0 100644--- a/tests/unit/health/test_trends.py+++ b/tests/unit/health/test_trends.py@@ -414,3 +414,84 @@ def test_snapshot_file_maps_round_trips_into_the_reader():t = file_trend(snaps, "a.py")assert t.delta == 0.0assert t.unclamped_delta == 2.0+++# --------------------------------------------------------------------------- #+# The per-snapshot parse memo+# --------------------------------------------------------------------------- #+#+# The per-file maps are per-*repo* blobs read one file at a time, so asking+# about N files re-parsed the same few blobs N times. Measured on the repowise+# index (20 snapshots averaging 186 KB each), ``get_health`` on a ``module:``+# target expanding to 822 files spent 13.0s in ``json.loads``; memoized, 0.4s.+++def _counting_loads(monkeypatch) -> list[int]:+ """Count ``json.loads`` calls made by ``trends``, without changing them.++ Clears the memo first: it is content-keyed and process-wide, so a blob an+ earlier test already parsed would otherwise make this one pass for the+ wrong reason.+ """+ import repowise.core.analysis.health.trends as trends_mod++ trends_mod._parsed_map.cache_clear()+ calls = [0]+ real = json.loads++ def counted(s, *a, **kw):+ calls[0] += 1+ return real(s, *a, **kw)++ monkeypatch.setattr(trends_mod.json, "loads", counted)+ return calls+++def test_each_snapshot_map_is_parsed_once_however_many_files_are_asked_about(monkeypatch):+ paths = [f"f{i}.py" for i in range(40)]+ snaps = _file_series([{p: 9.0 for p in paths}, {p: 8.0 for p in paths}])+ calls = _counting_loads(monkeypatch)++ for p in paths:+ assert file_trend(snaps, p).delta == -1.0++ # One parse per distinct blob: two score maps, and the one empty deduction+ # map both snapshots share. Unmemoized this is 40x that, and it is the shape+ # that made a ``module:`` target take 13 seconds.+ assert calls[0] <= 3, f"re-parsed per file: {calls[0]} loads"+++def test_the_memo_is_keyed_on_content_so_it_cannot_serve_a_stale_map():+ """Different bytes are a different key.++ A memo keyed on ``(snapshot, column)`` would keep answering with the first+ map it ever saw. These are historical rows so a rewrite is not expected —+ but a cache that *cannot* notice one is a different promise from a cache+ that re-parses when the bytes change.+ """+ snaps = _file_series([{"a.py": 9.0}, {"a.py": 8.0}])+ assert file_trend(snaps, "a.py").current == 8.0++ snaps[-1].per_file_scores_json = json.dumps({"a.py": 3.0})+ assert file_trend(snaps, "a.py").current == 3.0+++def test_the_memo_needs_nothing_of_the_snapshot_object():+ """Content-keying is what lets an unhashable row through.++ The obvious memo — a ``WeakKeyDictionary`` on the snapshot — silently+ degrades to no caching for any snapshot type that is unhashable or not+ weak-referenceable, which is every ``@dataclass`` row (``eq=True`` sets+ ``__hash__`` to ``None``) and every ``__slots__`` stub.+ """++ class _Slotted:+ __slots__ = ("per_file_deductions_json", "per_file_scores_json", "taken_at")++ def __init__(self, taken_at, scores):+ self.taken_at = taken_at+ self.per_file_scores_json = json.dumps(scores)+ self.per_file_deductions_json = "{}"++ snaps = [_Slotted(_ts(0), {"a.py": 9.0}), _Slotted(_ts(1), {"a.py": 7.0})]+ assert file_trend(snaps, "a.py").delta == -2.0diff --git a/tests/unit/ingestion/test_fs_walk.py b/tests/unit/ingestion/test_fs_walk.pyindex 4362427f7..0ea022a88 100644--- a/tests/unit/ingestion/test_fs_walk.py+++ b/tests/unit/ingestion/test_fs_walk.py@@ -11,9 +11,14 @@ Every repo-wide scan must go through ``fs_walk``.from __future__ import annotations+import osimport re+import subprocess+import sysfrom pathlib import Path+import pytest+from repowise.core.fs_walk import PRUNED_DIRS, PRUNED_DIRS_DERIVED, iter_glob, walk_repo@@ -181,6 +186,233 @@ class TestWalkRepo:assert tmp_path / "other" not in yielded_dirs+# ---------------------------------------------------------------------------+# Links: a link must never delete its target's subtree+# ---------------------------------------------------------------------------+++def _walked(root: Path) -> tuple[list[str], list[str]]:+ """``(dirs, files)`` of one walk, root-relative and posix, sorted."""+ dirs: list[str] = []+ files: list[str] = []+ for dirpath, _dirnames, filenames in walk_repo(root):+ rel = dirpath.relative_to(root).as_posix()+ dirs.append(rel)+ files.extend(f"{rel}/{f}".removeprefix("./") for f in filenames)+ return sorted(dirs), sorted(files)+++def _seed_tree(root: Path) -> None:+ _write(root, "svc/svc.py")+ _write(root, "svc/api/main.py")+ _write(root, "zz/z.py")+++def _symlink(link: Path, target: Path) -> None:+ try:+ os.symlink(target, link, target_is_directory=True)+ except (OSError, NotImplementedError) as exc: # pragma: no cover - env dependent+ pytest.skip(f"cannot create a directory symlink here: {exc}")+++def _junction(link: Path, target: Path) -> None:+ if sys.platform != "win32": # pragma: no cover - platform dependent+ pytest.skip("junctions are Windows-only")+ r = subprocess.run(+ ["cmd", "/c", "mklink", "/J", str(link), str(target)],+ capture_output=True,+ text=True,+ )+ if r.returncode: # pragma: no cover - env dependent+ pytest.skip(f"mklink /J unavailable: {r.stderr.strip()}")+++_EXPECTED_DIRS = [".", "svc", "svc/api", "zz"]+_EXPECTED_FILES = ["svc/api/main.py", "svc/svc.py", "zz/z.py"]+++class TestLinksDoNotShadowTheirTarget:+ """``visited_real`` recorded a link's *target* as visited, and+ ``followlinks=False`` meant the walk then never went there — so whichever+ of the pair sorted first won, and a link sorted ahead of its target removed+ the target's whole subtree from the result.++ The walk is shared by module attribution (a persisted, user-visible column),+ package-root discovery, the manifest scan, the TS/.NET resolvers and the+ workspace service-boundary extractor, so a shadowed subtree is silently+ wrong in all of them at once.+ """++ def test_a_symlink_sorted_ahead_of_its_target_keeps_the_target(+ self, tmp_path: Path+ ) -> None:+ _seed_tree(tmp_path)+ # "linked" sorts before "svc", so os.walk reaches the link first.+ _symlink(tmp_path / "linked", tmp_path / "svc")++ dirs, files = _walked(tmp_path)+ assert dirs == _EXPECTED_DIRS+ assert files == _EXPECTED_FILES++ def test_a_symlink_sorted_after_its_target_is_still_not_duplicated(+ self, tmp_path: Path+ ) -> None:+ """The order that always worked has to keep working — and the subtree+ must appear once, under its real name, not twice."""+ _seed_tree(tmp_path)+ _symlink(tmp_path / "zzz_linked", tmp_path / "svc")++ dirs, files = _walked(tmp_path)+ assert dirs == _EXPECTED_DIRS+ assert files == _EXPECTED_FILES++ def test_a_junction_reports_files_under_their_real_path(self, tmp_path: Path) -> None:+ """Junctions are the worse half and were filed as merely "the same+ shape". ``followlinks=False`` does not suppress them — Windows tags a+ junction a mount point rather than a symlink — so the walk descended+ the link, claimed the target as visited, and then reported every file+ under ``linked/...`` instead of ``svc/...``: not a missing subtree but+ a wrongly-named one, which is worse for a persisted path column.+ """+ _seed_tree(tmp_path)+ _junction(tmp_path / "linked", tmp_path / "svc")++ dirs, files = _walked(tmp_path)+ assert dirs == _EXPECTED_DIRS+ assert files == _EXPECTED_FILES++ def test_an_unlinked_tree_is_untouched(self, tmp_path: Path) -> None:+ """The fix must be invisible on a tree with no links in it, which is+ every repo this has ever been run against."""+ _seed_tree(tmp_path)+ assert _walked(tmp_path) == (_EXPECTED_DIRS, _EXPECTED_FILES)+++class TestALinkedWalkRootStillSeesItsOwnTree:+ """The topology every other test in this file happens to avoid.++ Found by adversarial review, and it is the interesting kind of miss: the+ first fix asked "is this child a link?" as ``realpath(child) !=+ abspath(child)``. ``abspath`` resolves nothing, so a symlink anywhere in the+ **root's own prefix** makes every child at every depth compare unequal, and+ the walk prunes the whole tree — ``walk_repo(linked_root)`` returned the+ root and nothing under it.++ Not exotic: macOS ``/tmp`` is a symlink to ``/private/tmp``, container bind+ mounts and mapped drives do the same, and ``walk_repo`` is shared by module+ attribution, package-root discovery, both resolvers and the CLI scanner —+ a repo checked out under one would have indexed as empty. Every link test+ above seeds a real ``tmp_path`` and links only *inside* it, so all of them+ passed on the broken version.+ """++ def test_a_symlinked_root_walks_the_same_tree_as_the_real_one(+ self, tmp_path: Path+ ) -> None:+ real = tmp_path / "real"+ real.mkdir()+ _seed_tree(real)+ _symlink(tmp_path / "via_link", real)++ assert _walked(tmp_path / "via_link") == _walked(real)+ assert _walked(real) == (_EXPECTED_DIRS, _EXPECTED_FILES)++ def test_a_junctioned_root_walks_the_same_tree_as_the_real_one(+ self, tmp_path: Path+ ) -> None:+ real = tmp_path / "real"+ real.mkdir()+ _seed_tree(real)+ _junction(tmp_path / "via_junction", real)++ assert _walked(tmp_path / "via_junction") == _walked(real)++ def test_an_in_tree_link_is_still_caught_under_a_linked_root(+ self, tmp_path: Path+ ) -> None:+ """Both halves at once — the prefix must not mask a real reparse point."""+ real = tmp_path / "real"+ real.mkdir()+ _seed_tree(real)+ _symlink(real / "linked", real / "svc")++ assert _walked(real) == (_EXPECTED_DIRS, _EXPECTED_FILES)+ _symlink(tmp_path / "via_link", real)+ assert _walked(tmp_path / "via_link") == (_EXPECTED_DIRS, _EXPECTED_FILES)+++class TestLinkCyclesStillTerminate:+ """The guard the fix had to preserve. ``visited_real`` exists because+ ``os.walk`` cannot detect a junction cycle by inode on Windows; pruning+ in-tree link targets must not give that up.+ """++ def test_a_self_referential_link_does_not_recurse(self, tmp_path: Path) -> None:+ _seed_tree(tmp_path)+ _symlink(tmp_path / "svc" / "loop", tmp_path / "svc")++ dirs, files = _walked(tmp_path)+ assert dirs == _EXPECTED_DIRS+ assert files == _EXPECTED_FILES++ def test_a_junction_to_an_ancestor_does_not_recurse(self, tmp_path: Path) -> None:+ _seed_tree(tmp_path)+ _junction(tmp_path / "svc" / "api" / "up", tmp_path)++ dirs, files = _walked(tmp_path)+ assert dirs == _EXPECTED_DIRS+ assert files == _EXPECTED_FILES++ def test_a_junction_to_an_external_tree_is_still_walked(self, tmp_path: Path) -> None:+ """Only *in-tree* targets are pruned. A link out of the tree is a+ genuine external mount the caller asked to include, and it is also the+ case that still needs its realpath recorded — ``os.walk`` will descend+ a junction into it, so a cycle inside that tree has to be caught.+ """+ outside = tmp_path.parent / f"{tmp_path.name}_external"+ (outside / "pkg").mkdir(parents=True)+ (outside / "pkg" / "ext.py").write_text("x", encoding="utf-8")+ root = tmp_path / "repo"+ root.mkdir()+ _seed_tree(root)+ _junction(root / "vendored", outside)++ _dirs, files = _walked(root)+ assert "vendored/pkg/ext.py" in files+ assert set(_EXPECTED_FILES) <= set(files)++ def test_a_cycle_inside_an_out_of_tree_target_is_still_caught(+ self, tmp_path: Path+ ) -> None:+ """``visited_real`` is still load-bearing, and only here.++ In-tree links never reach it now — they are pruned first — so it would+ be easy to conclude it is dead and delete it. It is not: an out-of-tree+ junction is *descended*, and a link inside that external tree pointing+ back at the external tree's own root is outside the walk root, so the+ in-tree rule does not fire. Without the realpath set the walk re-enters+ it until ``max_depth`` and reports the same files 60-odd times.++ Mutation-checked: neutering ``visited_real`` passes every other test in+ this file.+ """+ outside = tmp_path.parent / f"{tmp_path.name}_ext_cycle"+ (outside / "pkg").mkdir(parents=True)+ (outside / "pkg" / "ext.py").write_text("x", encoding="utf-8")+ _junction(outside / "pkg" / "back", outside)+ root = tmp_path / "repo"+ root.mkdir()+ _seed_tree(root)+ _junction(root / "vendored", outside)++ _dirs, files = _walked(root)+ # Every re-entry yields a *new* relative path+ # (``vendored/pkg/back/pkg/ext.py`` and so on down to ``max_depth``), so+ # asserting uniqueness or a per-path count proves nothing — the total is+ # what moves. Four files: the three seeded plus the external one, once.+ assert files == sorted([*_EXPECTED_FILES, "vendored/pkg/ext.py"]), files[:8]++# ---------------------------------------------------------------------------# --include-submodules plumbing — scanners must honor prune_nested_git=False# ---------------------------------------------------------------------------diff --git a/tests/unit/persistence/test_graph_nodes_type_index.py b/tests/unit/persistence/test_graph_nodes_type_index.pynew file mode 100644index 000000000..16a99d418--- /dev/null+++ b/tests/unit/persistence/test_graph_nodes_type_index.py@@ -0,0 +1,105 @@+"""``graph_nodes`` must be seekable by ``(repository_id, node_type)``.++``node_type == "file"`` is the most-issued predicate on the table, and the only+index covering the pair was ``uq_graph_node``'s, keyed ``(repository_id,+node_id)`` — so every "all the file nodes" read seeked on the repo and filtered+the rest in memory. On the repowise index that is 36,480 rows scanned to return+3,449.++Declared on the model *and* shipped as Alembic 0051. Local stores come from+``init_db`` and never run Alembic; hosted only ever runs Alembic. This pins the+model half, which is what ``init_db`` builds from.++Also covers the ``paths=`` scoping ``get_test_file_paths`` grew for it, since+that read is the reason the index was measured in the first place.+"""++from __future__ import annotations++from sqlalchemy import text++from repowise.core.persistence.crud import get_test_file_paths+from repowise.core.persistence.models import GraphNode+from tests.unit.persistence.helpers import insert_repo++_INDEX_NAME = "ix_graph_nodes_repo_type"+++def test_index_is_declared_on_the_model() -> None:+ by_name = {ix.name: ix for ix in GraphNode.__table__.indexes}+ assert _INDEX_NAME in by_name, "init_db-created stores would lack the index"+ assert [c.name for c in by_name[_INDEX_NAME].columns] == ["repository_id", "node_type"]+++async def test_a_file_node_read_seeks_instead_of_scanning(async_session) -> None:+ """The plan, not the timing — a wall-clock assert would be flaky in CI."""+ plan = (+ await async_session.execute(+ text(+ "EXPLAIN QUERY PLAN SELECT node_id FROM graph_nodes "+ "WHERE repository_id = :r AND node_type = 'file'"+ ),+ {"r": "repo"},+ )+ ).all()++ detail = " ".join(str(row[-1]) for row in plan)+ assert _INDEX_NAME in detail, f"expected a seek on {_INDEX_NAME}, got: {detail}"+ assert "node_type" in detail, f"index used but not keyed on node_type: {detail}"+++async def _seed_nodes(session) -> str:+ repo = await insert_repo(session)+ session.add_all(+ [+ GraphNode(repository_id=repo.id, node_id="a_test.py", node_type="file", is_test=True),+ GraphNode(repository_id=repo.id, node_id="b_test.py", node_type="file", is_test=True),+ GraphNode(repository_id=repo.id, node_id="prod.py", node_type="file", is_test=False),+ # A symbol node whose composite id embeds a test path — the+ # ``node_type`` filter is what keeps it out, not the path shape.+ GraphNode(+ repository_id=repo.id,+ node_id="a_test.py::helper",+ node_type="symbol",+ is_test=True,+ ),+ ]+ )+ await session.commit()+ return repo.id+++async def test_paths_narrows_the_answer_to_the_asked_about_files(async_session) -> None:+ repo_id = await _seed_nodes(async_session)++ assert await get_test_file_paths(async_session, repo_id) == {"a_test.py", "b_test.py"}+ # Scoped: only what was asked about, and a non-test path in the ask is+ # simply absent rather than an error.+ assert await get_test_file_paths(async_session, repo_id, ["a_test.py", "prod.py"]) == {+ "a_test.py"+ }+ assert await get_test_file_paths(async_session, repo_id, ["prod.py"]) == set()+++async def test_empty_paths_is_not_the_same_as_none(async_session) -> None:+ """``[]`` means "no files asked about" and must not fall back to repo-wide.++ ``get_health`` passes the resolved target list straight through, and a+ targets call that resolved nothing passes ``[]``. Treating that as ``None``+ would answer a scoped question with the whole repo.+ """+ repo_id = await _seed_nodes(async_session)++ assert await get_test_file_paths(async_session, repo_id, []) == set()+ assert await get_test_file_paths(async_session, repo_id, None) != set()+++async def test_scoping_survives_more_paths_than_one_statement_can_bind(async_session) -> None:+ """A ``module:`` target expands to every file in the module, which on a+ monorepo exceeds SQLite's bind-parameter limit for a single ``IN``."""+ repo_id = await _seed_nodes(async_session)+ padding = [f"pad/{i}.py" for i in range(3000)]++ assert await get_test_file_paths(async_session, repo_id, [*padding, "b_test.py"]) == {+ "b_test.py"+ }diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex c98a5344f..9dba3915c 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -978,6 +978,43 @@ async def test_targeted_mode_is_never_split(setup_mcp, health_data_with_tests):assert result["metrics"][0]["is_test"] is True+async def test_targeted_mode_asks_only_about_the_files_it_was_given(+ setup_mcp, health_data_with_tests, monkeypatch+):+ """The test-path read is scoped to the targets in targeted mode.++ It answers one question per mode. Targeted mode only ever asks+ ``path in test_paths`` for paths the caller named, so it reads exactly+ those — a keyed seek instead of a read over every file node the repo has.+ Measured on the repowise index, 32.9ms -> 0.6ms on a single-file target,+ which was a quarter of the whole call spent deciding whether one file is a+ test. Dashboard mode partitions a ranked finding list whose paths are not+ known until that list is built, so it must stay repo-wide.+ """+ import repowise.server.mcp_server.tool_health as th+ from repowise.server.mcp_server import get_health++ asked: list[object] = []+ real = th.get_test_file_paths++ async def spy(session, repository_id, paths=None):+ asked.append(paths)+ return await real(session, repository_id, paths)++ monkeypatch.setattr(th, "get_test_file_paths", spy)++ targeted = await get_health(targets=["tests/test_service.py"])+ assert asked == [["tests/test_service.py"]]+ # Scoping it must not change the answer.+ assert targeted["metrics"][0]["is_test"] is True++ asked.clear()+ dashboard = await get_health()+ assert asked == [None], "the dashboard split needs the repo-wide answer"+ assert dashboard["test_findings"], "scoping the dashboard would empty this"++@pytest.mark.asyncioasync def test_kpis_still_include_test_files(setup_mcp, health_data_with_tests):"""Excluding test material from the KPIs is a scoring change, not a display one.diff --git a/tests/unit/server/mcp/test_perf_rank.py b/tests/unit/server/mcp/test_perf_rank.pynew file mode 100644index 000000000..9af6a796e--- /dev/null+++ b/tests/unit/server/mcp/test_perf_rank.py@@ -0,0 +1,283 @@+"""The performance dimension's ranking key.++Every performance finding carries ``health_impact: 0`` by construction — the+dimension is deliberately never blended into the score — so the ranked list came+back in whatever order the impact tie broke to, which is file order. "Which of+these 697 matters" was unanswerable from the payload, and the *cap* was+arbitrary with it: ``include=['performance']`` returned 20 of 697 chosen by+nothing.++``_perf_rank`` is an ordering key, not a score. Nothing here is blended into+``score`` / ``performance_score`` and nothing here was fitted against the defect+corpus; the frozen weights stay frozen.+"""++from __future__ import annotations++import uuid++import pytest++from repowise.core.analysis.health.biomarkers import registered_biomarkers+from repowise.server.mcp_server.tool_health import (+ _PERF_MARKER_POINTS,+ _perf_rank,+ _rank_emitted,+)++# ---------------------------------------------------------------------------+# The key itself+# ---------------------------------------------------------------------------+++def test_every_performance_biomarker_carries_a_weight() -> None:+ """The weight table must not silently acquire a default.++ A detector added without a weight ranks at the floor, which is the safe+ direction but also an invisible one — a new high-cost marker would sort+ below ``string_concat_in_loop`` and nobody would see it. This is the+ mechanism that makes adding one loud.+ """+ registered = {b.name for b in registered_biomarkers() if getattr(b, "category", "") == "performance"}+ assert registered, "no performance detectors registered — the check is vacuous"+ assert registered <= set(_PERF_MARKER_POINTS), (+ f"unweighted performance biomarkers: {sorted(registered - set(_PERF_MARKER_POINTS))}"+ )+ # And no stale entries pointing at detectors that no longer exist.+ assert set(_PERF_MARKER_POINTS) <= registered, (+ f"weights for unregistered markers: {sorted(set(_PERF_MARKER_POINTS) - registered)}"+ )+++def test_a_cross_function_subprocess_n_plus_one_outranks_a_filesystem_one() -> None:+ """Boundary kind separates two findings of identical shape.++ "A subprocess spawn in a loop is not a filesystem stat in a loop" is the+ whole reason the key reads ``boundary_kind``.+ """+ spawn = _perf_rank("io_in_loop", {"boundary_kind": "subprocess", "cross_function": True})+ stat = _perf_rank("io_in_loop", {"boundary_kind": "filesystem", "cross_function": True})+ assert spawn > stat+++def test_a_cross_function_hit_outranks_the_same_hit_inside_one_function() -> None:+ """The minimum the item asked for: cross-function N+1s above intra-function.++ An intra-function loop is often visibly bounded at the call site; a+ cross-function one is the one nobody sees by reading the loop.+ """+ same = {"boundary_kind": "db", "cross_function": False}+ across = {"boundary_kind": "db", "cross_function": True}+ assert _perf_rank("io_in_loop", across) > _perf_rank("io_in_loop", same)+++def test_the_gated_markers_carry_their_hotness_proof() -> None:+ """``hot_path_sync_io`` is only ever emitted on a hot, reachable function.++ ``perf.gated.collect_centrality_gated`` will not produce it otherwise, so+ its presence *is* the request-reachability signal and needs no new column.+ It therefore outranks the cheap in-loop CPU markers at the same boundary,+ while sitting level with a plain N+1 marker — it proves hotness and no+ multiplier, the loop proves a multiplier and no hotness.+ """+ hot = _perf_rank("hot_path_sync_io", {"boundary_kind": "db"})+ cheap = _perf_rank("string_concat_in_loop", {})+ assert hot > cheap+ assert hot == _perf_rank("io_in_loop", {"boundary_kind": "db"})+ # Superlinear beats both.+ assert _perf_rank("nested_loop_quadratic", {}) > _perf_rank("io_in_loop", {})+++def test_an_unknown_marker_sinks_rather_than_floats() -> None:+ assert _perf_rank("some_future_marker", {}) == min(_PERF_MARKER_POINTS.values())+++def test_malformed_details_never_raise() -> None:+ """Details come from a JSON column; the reader has to survive any shape."""+ for details in (None, [], "not a dict", 7, {}):+ assert _perf_rank("io_in_loop", details) >= 1+++# ---------------------------------------------------------------------------+# The sort+# ---------------------------------------------------------------------------+++class _Row:+ def __init__(self, impact, dimension, biomarker_type, details_json, file_path):+ self.health_impact = impact+ self.dimension = dimension+ self.biomarker_type = biomarker_type+ self.details_json = details_json+ self.file_path = file_path++ def __repr__(self) -> str: # pragma: no cover - failure output only+ return f"{self.file_path}:{self.biomarker_type}"+++def test_the_sort_reorders_the_perf_tier_and_leaves_the_defect_order_alone() -> None:+ rows = [+ _Row(2.0, "defect", "complex_method", None, "b.py"),+ _Row(0.0, "performance", "string_concat_in_loop", "{}", "a.py"),+ _Row(3.0, "defect", "god_class", None, "c.py"),+ _Row(+ 0.0,+ "performance",+ "io_in_loop",+ '{"boundary_kind": "subprocess", "cross_function": true}',+ "z.py",+ ),+ ]+ ranked = _rank_emitted(rows)+ # Defect rows keep their impact order and stay ahead of the zero-impact tier.+ assert [r.file_path for r in ranked[:2]] == ["c.py", "b.py"]+ # The perf tier is reordered by cost, not by file name.+ assert [r.file_path for r in ranked[2:]] == ["z.py", "a.py"]+++def test_ties_break_on_path_so_the_order_is_total() -> None:+ """Two findings that rank the same used to swap places between calls."""+ mk = lambda p: _Row(0.0, "performance", "io_in_loop", '{"boundary_kind": "db"}', p) # noqa: E731+ assert [r.file_path for r in _rank_emitted([mk("b.py"), mk("a.py")])] == ["a.py", "b.py"]+ assert [r.file_path for r in _rank_emitted([mk("a.py"), mk("b.py")])] == ["a.py", "b.py"]+++def test_rows_without_a_details_column_still_sort() -> None:+ """The narrow dashboard read carries no ``details_json`` unless the caller+ filtered to ``performance`` — those rank on the marker alone."""++ class _Lite:+ def __init__(self, bt, p):+ self.health_impact = 0.0+ self.dimension = "performance"+ self.biomarker_type = bt+ self.file_path = p++ ranked = _rank_emitted([_Lite("string_concat_in_loop", "a.py"), _Lite("io_in_loop", "z.py")])+ assert [r.file_path for r in ranked] == ["z.py", "a.py"]+++# ---------------------------------------------------------------------------+# End to end+# ---------------------------------------------------------------------------+++async def perf_findings(session, health_data: str) -> str:+ """Nine performance findings spanning the whole rank range.++ File names are deliberately in the *opposite* order to cost, so a response+ that still sorts by path is unmistakable.+ """+ import json++ from repowise.core.persistence.models import HealthFinding++ rows = [+ ("a_cheap.py", "string_concat_in_loop", {}),+ ("b_member.py", "membership_test_against_list_in_loop", {}),+ ("c_fs.py", "io_in_loop", {"boundary_kind": "filesystem", "cross_function": False}),+ ("d_db.py", "io_in_loop", {"boundary_kind": "db", "cross_function": False}),+ ("e_hot_fs.py", "hot_path_sync_io", {"boundary_kind": "filesystem"}),+ ("f_db_xfn.py", "io_in_loop", {"boundary_kind": "db", "cross_function": True}),+ ("g_hot_spawn.py", "hot_path_sync_io", {"boundary_kind": "subprocess"}),+ ("h_nested_db.py", "nested_loop_with_io", {"boundary_kind": "db"}),+ ("i_spawn_xfn.py", "io_in_loop", {"boundary_kind": "subprocess", "cross_function": True}),+ ]+ for path, biomarker, details in rows:+ session.add(+ HealthFinding(+ id=str(uuid.uuid4()),+ repository_id=health_data,+ file_path=path,+ biomarker_type=biomarker,+ severity="medium",+ function_name="f",+ line_start=1,+ line_end=1,+ details_json=json.dumps(details),+ health_impact=0.0,+ reason=f"{biomarker} in {path}",+ dimension="performance",+ status="open",+ )+ )+ await session.flush()+ return health_data+++async def test_the_perf_head_is_the_costliest_findings_not_the_first_alphabetically(+ setup_mcp, perf_findings+):+ """The defect this closes is about *selection*, not display.++ With ``include=['performance']`` the whole list is perf, every row ties at+ impact 0, and the cap keeps whichever ones the tie broke to. Before the key+ that was file order, so a small ``limit`` returned the cheapest findings in+ the repo and called them the top ones.++ The base fixture's perf finding carries a non-zero impact, so it still leads+ — the key breaks ties *within* an impact tier and never reorders across one.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health(include=["biomarkers", "performance"], limit=4)+ assert [f["file_path"] for f in result["findings"]] == [+ "src/auth/service.py",+ "i_spawn_xfn.py",+ "g_hot_spawn.py",+ "f_db_xfn.py",+ ]+ # Rank 6 is a three-way tie (the base fixture's row, the cross-function db+ # N+1 and the nested db loop); ``file_path`` is what makes the order total.+ assert [f["perf_rank"] for f in result["findings"]] == [6, 8, 7, 6]+ # The total still describes the whole filtered set, so the cap stays visible.+ assert result["findings_total"] == 10+++async def test_perf_rank_is_absent_from_every_other_dimension(setup_mcp, perf_findings):+ """Not zero — a defect finding ranks on ``weighted_deficit``, and a 0 here+ would read as "measured, and it is nothing"."""+ from repowise.server.mcp_server import get_health++ result = await get_health(include=["biomarkers"], limit=50)+ by_dim = {}+ for f in result["findings"]:+ by_dim.setdefault(f["dimension"], []).append(f)+ assert by_dim.get("defect"), "fixture should carry defect findings"+ assert all("perf_rank" not in f for f in by_dim["defect"])+ assert all("perf_rank" not in f for f in by_dim.get("maintainability", []))+ assert all("perf_rank" in f for f in by_dim["performance"])+++async def test_the_default_dashboard_does_not_pay_for_the_ranking_read(+ setup_mcp, perf_findings, monkeypatch+):+ """``details_json`` joins the narrow read only when perf can reach the head.++ Every perf finding carries impact 0, so in a mixed list all the defect+ findings sort above them and the rank cannot move a row — paying for the+ column there would be 6.6ms bought for nothing. This asserts the *read*:+ the response is identical either way, so a payload-only test would pass on+ the unfixed code.+ """+ from repowise.server.mcp_server import get_health, tool_health++ selected: list[list[str]] = []+ real = tool_health.select++ def spy(*cols):+ selected.append([getattr(c, "key", str(c)) for c in cols])+ return real(*cols)++ monkeypatch.setattr(tool_health, "select", spy)++ await get_health()+ assert not any("details_json" in cols for cols in selected)++ selected.clear()+ await get_health(include=["biomarkers", "performance"])+ assert any("details_json" in cols for cols in selected)diff --git a/tests/unit/server/test_health_files_summary.py b/tests/unit/server/test_health_files_summary.pynew file mode 100644index 000000000..7c4eba367--- /dev/null+++ b/tests/unit/server/test_health_files_summary.py@@ -0,0 +1,177 @@+"""``fields=summary`` on /api/repos/{id}/health/files.++The code-health map fires one unconditional 2,000-row request on page load and+reads none of the per-row lead or detail keys — measured on the repowise index,+1,060,407 B of which 432,081 B is keys nothing on that page touches, and the+lead is reduced from *every* open finding in the repo (10,740 rows, 1.66 MB of+``details_json``) to produce it.++``summary`` drops exactly the keys already declared optional on+``HealthFileMetric``, so a summary row still parses as one and every consumer+already handles them absent.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from tests.unit.server.conftest import create_test_repo++_FULL_ONLY = {+ "duplication_pct",+ "defect_score",+ "primary_biomarker",+ "primary_reason",+ "total_deduction",+}+++def _metric(i: int) -> dict:+ return {+ "file_path": f"src/f{i:02d}.py",+ "score": 3.0 + i,+ "max_ccn": 10 + i,+ "max_nesting": 3,+ "nloc": 100 - i,+ "has_test_file": False,+ "module": "src",+ "duplication_pct": 12.5,+ "defect_score": 3.0 + i,+ "maintainability_score": 6.0,+ "performance_score": 9.0,+ }+++def _finding(path: str, biomarker: str, dimension: str, impact: float) -> dict:+ return {+ "file_path": path,+ "biomarker_type": biomarker,+ "severity": "medium",+ "function_name": "f",+ "line_start": 1,+ "line_end": 2,+ "details": {"boundary_kind": "db"},+ "health_impact": impact,+ "reason": f"{biomarker} on {path}",+ "dimension": dimension,+ }+++async def _seed(app, repo_id: str) -> None:+ async with get_session(app.state.session_factory) as session:+ await crud.save_health_metrics(session, repo_id, [_metric(i) for i in range(3)])+ await crud.save_health_findings(+ session,+ repo_id,+ [+ _finding("src/f00.py", "complex_method", "defect", 2.5),+ _finding("src/f00.py", "io_in_loop", "performance", 0.0),+ _finding("src/f01.py", "io_in_loop", "performance", 0.0),+ _finding("src/f01.py", "io_in_loop", "performance", 0.0),+ ],+ )+++async def test_full_is_the_default_and_carries_every_key(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])++ default = (await client.get(f"/api/repos/{repo['id']}/health/files")).json()+ explicit = (+ await client.get(f"/api/repos/{repo['id']}/health/files", params={"fields": "full"})+ ).json()++ assert default == explicit, "the default must stay the wide row"+ row = next(f for f in default["files"] if f["file_path"] == "src/f00.py")+ assert set(row) >= _FULL_ONLY+ assert row["primary_biomarker"] == "complex_method"+ assert row["total_deduction"] == 2.5+++async def test_summary_omits_the_optional_keys_rather_than_nulling_them(+ client: AsyncClient, app+) -> None:+ """Omitted, not nulled — most of the saving is the key names themselves."""+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])++ body = (+ await client.get(f"/api/repos/{repo['id']}/health/files", params={"fields": "summary"})+ ).json()+ for row in body["files"]:+ assert not (_FULL_ONLY & set(row)), f"summary row still carries {_FULL_ONLY & set(row)}"+++async def test_summary_keeps_every_field_the_map_actually_colours_by(+ client: AsyncClient, app+) -> None:+ """The saving is only legitimate if the map can still draw itself.++ ``performance_findings`` is the one that makes this non-obvious: the+ narrowed read has to keep counting perf findings per file, and a summary+ mode that skipped the finding read entirely would grey out the performance+ lens while every other assertion here still passed.+ """+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])++ full = (await client.get(f"/api/repos/{repo['id']}/health/files")).json()+ lean = (+ await client.get(f"/api/repos/{repo['id']}/health/files", params={"fields": "summary"})+ ).json()++ map_fields = {+ "file_path",+ "score",+ "nloc",+ "module",+ "line_coverage_pct",+ "has_test_file",+ "maintainability_score",+ "performance_score",+ "performance_findings",+ "performance_analyzed",+ }+ by_path_full = {f["file_path"]: f for f in full["files"]}+ for row in lean["files"]:+ assert map_fields <= set(row)+ wide = by_path_full[row["file_path"]]+ for key in map_fields:+ assert row[key] == wide[key], f"{key} diverged on {row['file_path']}"+ # And the counts are real, not a constant zero.+ assert by_path_full["src/f01.py"]["performance_findings"] == 2+ assert by_path_full["src/f00.py"]["performance_findings"] == 1+++async def test_summary_still_windows_and_filters_identically(client: AsyncClient, app) -> None:+ """The projection subtracts keys; it must not change which rows come back."""+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])++ params = {"limit": 2, "offset": 1, "sort": "nloc", "order": "desc"}+ full = (await client.get(f"/api/repos/{repo['id']}/health/files", params=params)).json()+ lean = (+ await client.get(+ f"/api/repos/{repo['id']}/health/files", params={**params, "fields": "summary"}+ )+ ).json()++ assert full["total"] == lean["total"] == 3+ assert [f["file_path"] for f in full["files"]] == [f["file_path"] for f in lean["files"]]+++async def test_an_unknown_fields_value_is_rejected(client: AsyncClient) -> None:+ """A typo must not silently fall through to the wide row and be paid for."""+ repo = await create_test_repo(client)+ resp = await client.get(+ f"/api/repos/{repo['id']}/health/files", params={"fields": "lean"}+ )+ assert resp.status_code == 422