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(areas): directory health rollups at any depth (#4135)

Raghav Chamadiya81fb56f5dca6
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index 8455fd23a..cb1b5bfe6 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -39,6 +39,7 @@
"./modules": "./src/modules.ts",
"./overview": "./src/overview.ts",
"./actions": "./src/actions.ts",
+ "./areas": "./src/areas.ts",
"./pagination": "./src/pagination.ts",
"./owners": "./src/owners.ts",
"./pages": "./src/pages.ts",
diff --git a/packages/api-client/src/areas.ts b/packages/api-client/src/areas.ts
new file mode 100644
index 000000000..a91549dc0
--- /dev/null
+++ b/packages/api-client/src/areas.ts
@@ -0,0 +1,28 @@
+/** Areas: directory rollups at any depth (`/areas/tree`, `/areas/{path}`). */
+import type { AreaDetail, AreaTree, AreaTreeQuery } from "@repowise-dev/types/areas";
+import { apiGet } from "./client";
+
+export type {
+ AreaDeltaWindow,
+ AreaDetail,
+ AreaFileRow,
+ AreaFinding,
+ AreaNode,
+ AreaOwner,
+ AreaTree,
+ AreaTreeQuery,
+} from "@repowise-dev/types/areas";
+
+/** The root area's rollup plus every directory up to `depth` levels below it. */
+export async function getAreaTree(repoId: string, opts: AreaTreeQuery = {}): Promise<AreaTree> {
+ return apiGet<AreaTree>(`/api/repos/${repoId}/areas/tree`, {
+ root: opts.root || undefined,
+ depth: opts.depth,
+ });
+}
+
+/** One area's card; `""` is the repository root. */
+export async function getAreaDetail(repoId: string, area: string): Promise<AreaDetail> {
+ const path = area.split("/").filter(Boolean).map(encodeURIComponent).join("/");
+ return apiGet<AreaDetail>(path ? `/api/repos/${repoId}/areas/${path}` : `/api/repos/${repoId}/areas`);
+}
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index bfd8c4c7b..e48728914 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -185,6 +185,7 @@ export async function getHealthMap(
counts: opts.counts,
include_held: opts.include_held || undefined,
q: opts.q?.trim() || undefined,
+ area: opts.area || undefined,
});
}
diff --git a/packages/core/src/repowise/core/analysis/areas/__init__.py b/packages/core/src/repowise/core/analysis/areas/__init__.py
new file mode 100644
index 000000000..48e2f4904
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/__init__.py
@@ -0,0 +1,32 @@
+"""Areas: any directory at any depth, rolled up from the analyzers' stored outputs.
+
+The unit the zoomable map, its side panel, contributors and coupling views
+share. Reads health, git and finding rows; never re-scores anything.
+"""
+
+from __future__ import annotations
+
+from .detail import DETAIL_LIMIT, area_detail
+from .owners import FileOwner, file_owners
+from .paths import ROOT_AREA, ancestors, area_depth, in_area, normalize_area
+from .rollup import AreaIndex, build_area_index
+from .trend import area_score, area_scores, attach_deltas, baseline_index, nloc_weights
+
+__all__ = [
+ "DETAIL_LIMIT",
+ "ROOT_AREA",
+ "AreaIndex",
+ "FileOwner",
+ "ancestors",
+ "area_depth",
+ "area_detail",
+ "area_score",
+ "area_scores",
+ "attach_deltas",
+ "baseline_index",
+ "build_area_index",
+ "file_owners",
+ "in_area",
+ "nloc_weights",
+ "normalize_area",
+]
diff --git a/packages/core/src/repowise/core/analysis/areas/detail.py b/packages/core/src/repowise/core/analysis/areas/detail.py
new file mode 100644
index 000000000..36afe04f2
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/detail.py
@@ -0,0 +1,93 @@
+"""One area's card: its rollup plus the bounded lists a side panel opens on."""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any
+
+from repowise.core.analysis.health.grading import band_for, distribution
+from repowise.core.analysis.health.ranking import sort_metrics_worst_first
+from repowise.core.analysis.health.rows import field
+from repowise.core.analysis.health.scoring import is_advisory
+
+from .owners import owner_breakdown
+from .paths import in_area
+from .rollup import AreaIndex, coverage_rollup
+
+__all__ = ["DETAIL_LIMIT", "OWNER_LIMIT", "area_detail"]
+
+#: Rows per list (worst files, hotspots, findings). A card, not a table.
+DETAIL_LIMIT = 8
+OWNER_LIMIT = 5
+
+
+def _file(row: Any) -> dict[str, Any]:
+ score = float(field(row, "score"))
+ return {
+ "path": field(row, "file_path"),
+ "score": round(score, 2),
+ "band": band_for(score),
+ "nloc": int(field(row, "nloc", 0) or 0),
+ }
+
+
+def _top_findings(index: AreaIndex, area: str, limit: int) -> list[dict[str, Any]]:
+ """The first *limit* open findings in the area, in the finding lists' order.
+
+ Advisory findings are left out, as from the severity counts beside them.
+ """
+ out: list[dict[str, Any]] = []
+ for finding in index.findings:
+ if len(out) >= limit:
+ break
+ if in_area(finding["file_path"], area) and not is_advisory(
+ finding["biomarker_type"] or ""
+ ):
+ out.append(finding)
+ return out
+
+
+def _is_hotspot(index: AreaIndex, path: str) -> bool:
+ return bool(index.git_by_path.get(path, {}).get("is_hotspot"))
+
+
+def _test_reach(group: Sequence[Any]) -> dict[str, Any]:
+ """Paired test files, and measured line coverage where a report covered the area."""
+ coverage, measured = coverage_rollup(group)
+ return {
+ "files": len(group),
+ "with_test_file": sum(1 for r in group if field(r, "has_test_file")),
+ "measured_files": measured,
+ "line_coverage_pct": coverage,
+ }
+
+
+def area_detail(
+ index: AreaIndex,
+ area: str,
+ *,
+ trend: Sequence[dict[str, Any]] = (),
+ limit: int = DETAIL_LIMIT,
+) -> dict[str, Any] | None:
+ """The area's rollup and lists, or ``None`` when no scored file is under it.
+
+ *trend* is the area's score per snapshot (``[{taken_at, health}]``), read
+ from the history by the caller.
+ """
+ node = index.nodes.get(area)
+ if node is None:
+ return None
+ group = index.members[area]
+ ranked = sort_metrics_worst_first(group, index.deductions)
+ hotspots = [r for r in ranked if _is_hotspot(index, field(r, "file_path"))]
+ owners = owner_breakdown((field(r, "file_path") for r in group), index.owners, len(group))
+ return {
+ "area": node,
+ "distribution": distribution(group),
+ "worst_files": [_file(r) for r in ranked[:limit]],
+ "hotspots": {"total": len(hotspots), "files": [_file(r) for r in hotspots[:limit]]},
+ "owners": {"total": len(owners), "top": owners[:OWNER_LIMIT]},
+ "trend": list(trend),
+ "top_findings": _top_findings(index, area, limit),
+ "test_reach": _test_reach(group),
+ }
diff --git a/packages/core/src/repowise/core/analysis/areas/owners.py b/packages/core/src/repowise/core/analysis/areas/owners.py
new file mode 100644
index 000000000..e50f0ff17
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/owners.py
@@ -0,0 +1,64 @@
+"""Who owns each file, resolved to one identity per person.
+
+Keys come from :func:`repowise.core.analysis.owners.people_resolver`, the
+resolver every people-shaped figure goes through, so an area's owner key is the
+key the contributors pages link to.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any
+
+from repowise.core.analysis.health.rows import field
+from repowise.core.analysis.owners import people_resolver
+
+__all__ = ["FileOwner", "file_owners", "owner_breakdown", "primary_owner"]
+
+
+@dataclass(frozen=True)
+class FileOwner:
+ key: str
+ name: str
+ #: ``human``, ``agent`` or ``bot``.
+ kind: str
+
+
+def file_owners(git_rows: Sequence[Any], commit_rows: Iterable[Any] = ()) -> dict[str, FileOwner]:
+ """``{file_path: owner}`` for every git row with a resolvable primary owner."""
+ resolve = people_resolver(git_rows, commit_rows)
+ out: dict[str, FileOwner] = {}
+ for row in git_rows:
+ key = resolve(field(row, "primary_owner_name"), field(row, "primary_owner_email"))
+ if key:
+ owner = FileOwner(key, resolve.display_name(key), resolve.kind(key))
+ out[field(row, "file_path")] = owner
+ return out
+
+
+def owner_breakdown(
+ paths: Iterable[str], owners: Mapping[str, FileOwner], total: int
+) -> list[dict[str, Any]]:
+ """Owners of *paths* by files owned, most first; ``share`` is of *total* files.
+
+ Ties break on the key so two reads agree.
+ """
+ counts: Counter[FileOwner] = Counter(owners[p] for p in paths if p in owners)
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0].key))
+ return [
+ {
+ "key": owner.key,
+ "name": owner.name,
+ "kind": owner.kind,
+ "files": files,
+ "share": round(files / total, 4) if total else 0.0,
+ }
+ for owner, files in ranked
+ ]
+
+
+def primary_owner(breakdown: Sequence[dict[str, Any]]) -> dict[str, Any] | None:
+ """The person owning the most files; automation never leads an area."""
+ return next((row for row in breakdown if row["kind"] == "human"), None)
diff --git a/packages/core/src/repowise/core/analysis/areas/paths.py b/packages/core/src/repowise/core/analysis/areas/paths.py
new file mode 100644
index 000000000..b568a2259
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/paths.py
@@ -0,0 +1,53 @@
+"""What an area is: a directory at any depth, named by its repo-relative path.
+
+The repository root is the area ``""``. A file belongs to every directory
+above it, so ``a/b/c.py`` is in ``""``, ``a`` and ``a/b``. Pure string work,
+shared by the rollup, the trend and the map's ``?area=`` filter so the three
+can never disagree about which files an area holds.
+"""
+
+from __future__ import annotations
+
+__all__ = [
+ "ROOT_AREA",
+ "ancestors",
+ "area_depth",
+ "area_name",
+ "area_parent",
+ "in_area",
+ "normalize_area",
+]
+
+ROOT_AREA = ""
+
+
+def normalize_area(raw: str | None) -> str:
+ """A caller's area path in canonical form: forward slashes, no edge slashes, no ``.``."""
+ parts = [p for p in (raw or "").replace("\\", "/").split("/") if p and p != "."]
+ return "/".join(parts)
+
+
+def ancestors(file_path: str) -> list[str]:
+ """Every area *file_path* belongs to, root first."""
+ parts = file_path.split("/")[:-1]
+ return [ROOT_AREA, *("/".join(parts[: i + 1]) for i in range(len(parts)))]
+
+
+def in_area(file_path: str, area: str) -> bool:
+ return area == ROOT_AREA or file_path.startswith(area + "/")
+
+
+def area_depth(area: str) -> int:
+ """Segments in the path; the root is depth 0."""
+ return 0 if area == ROOT_AREA else area.count("/") + 1
+
+
+def area_name(area: str) -> str:
+ return area.rsplit("/", 1)[-1]
+
+
+def area_parent(area: str) -> str | None:
+ """The enclosing area; the root has none."""
+ if area == ROOT_AREA:
+ return None
+ return area.rsplit("/", 1)[0] if "/" in area else ROOT_AREA
diff --git a/packages/core/src/repowise/core/analysis/areas/rollup.py b/packages/core/src/repowise/core/analysis/areas/rollup.py
new file mode 100644
index 000000000..b1a627712
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/rollup.py
@@ -0,0 +1,196 @@
+"""Directory rollups at every depth, folded once over the whole repository.
+
+Every scored file is added to each area above it, then each area is folded with
+:func:`..health.aggregation.group_rollup`, the fold module health uses, so an
+area's health means exactly what a module's does: the NLOC-weighted average of
+its scored files, worst performer under the shared ranking key. A file health
+cannot score (no dialect for its language) is in no figure, as in
+``module_rollups``.
+
+Pure: the caller loads the rows and keeps the result per index state.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass, field
+from itertools import pairwise
+from typing import Any
+
+from repowise.core.analysis.health.aggregation import group_rollup, severity_breakdown
+from repowise.core.analysis.health.grading import BAND_ORDER, band_for, distribution
+from repowise.core.analysis.health.rows import field as row_field
+from repowise.core.analysis.health.rows import scored_rows
+
+from .owners import FileOwner, owner_breakdown, primary_owner
+from .paths import ancestors, area_depth, area_name, area_parent
+
+__all__ = [
+ "AreaIndex",
+ "build_area_index",
+ "coverage_rollup",
+ "finding_row",
+ "severity_by_file",
+]
+
+#: The fields an area reads of each row; the index is kept in memory per index
+#: state, so the rest of a row (an ORM entity is a few KB) is not kept.
+_METRIC_FIELDS = ("file_path", "score", "nloc", "is_test", "line_coverage_pct", "has_test_file")
+_GIT_FIELDS = ("is_hotspot", "bus_factor")
+
+
+def _pick(row: Any, names: tuple[str, ...]) -> dict[str, Any]:
+ return {name: row_field(row, name) for name in names}
+
+
+@dataclass
+class AreaIndex:
+ """Every area's rollup plus what a detail view folds further."""
+
+ nodes: dict[str, dict[str, Any]]
+ #: Scored metric rows (the fields an area reads) under each area, at any depth.
+ members: dict[str, list[Any]]
+ children: dict[str, list[str]]
+ #: ``{path: {is_hotspot, bus_factor}}``: only what an area reads, since
+ #: the index is kept in memory per index state.
+ git_by_path: Mapping[str, dict[str, Any]] = field(default_factory=dict)
+ owners: Mapping[str, FileOwner] = field(default_factory=dict)
+ deductions: Mapping[str, float] = field(default_factory=dict)
+ #: Open findings as :func:`finding_row` dicts, in the finding lists' priority order.
+ findings: Sequence[dict[str, Any]] = ()
+
+
+def finding_row(row: Any) -> dict[str, Any]:
+ """The fields an area shows of one finding, detached from its stored row."""
+ impact = row_field(row, "health_impact")
+ return {
+ "id": row_field(row, "id"),
+ "file_path": row_field(row, "file_path"),
+ "biomarker_type": row_field(row, "biomarker_type"),
+ "severity": str(row_field(row, "severity") or "").lower(),
+ "function_name": row_field(row, "function_name"),
+ "line_start": row_field(row, "line_start"),
+ "health_impact": round(float(impact), 3) if impact is not None else None,
+ "reason": row_field(row, "reason"),
+ }
+
+
+def severity_by_file(findings: Iterable[Any]) -> dict[str, dict[str, int]]:
+ """Open-finding counts per declared severity, per file (advisory left out)."""
+ grouped: dict[str, list[Any]] = defaultdict(list)
+ for finding in findings:
+ grouped[row_field(finding, "file_path")].append(finding)
+ return {path: severity_breakdown(rows) for path, rows in grouped.items()}
+
+
+def coverage_rollup(group: Sequence[Any]) -> tuple[float | None, int]:
+ """NLOC-weighted line coverage over the files a report measured, and how many.
+
+ ``None`` when no file in the group was measured: no report is not 0%.
+ """
+ measured = [r for r in group if row_field(r, "line_coverage_pct") is not None]
+ if not measured:
+ return None, 0
+ weighted = [(max(int(row_field(r, "nloc", 0) or 0), 1), r) for r in measured]
+ total = sum(w * float(row_field(r, "line_coverage_pct")) for w, r in weighted)
+ return round(total / sum(w for w, _ in weighted), 2), len(measured)
+
+
+def _sum_severities(
+ paths: Iterable[str], severities: Mapping[str, dict[str, int]]
+) -> dict[str, int]:
+ out = dict.fromkeys(severity_breakdown(()), 0)
+ for path in paths:
+ for severity, count in severities.get(path, {}).items():
+ out[severity] += count
+ return out
+
+
+def _node(
+ area: str,
+ group: list[Any],
+ *,
+ direct: int,
+ has_children: bool,
+ index: AreaIndex,
+ severities: Mapping[str, dict[str, int]],
+) -> dict[str, Any]:
+ rollup = group_rollup(group, index.deductions)
+ paths = [row_field(r, "file_path") for r in group]
+ git = [index.git_by_path[p] for p in paths if p in index.git_by_path]
+ bands = distribution(group)["bands"]
+ coverage, measured = coverage_rollup(group)
+ return {
+ "path": area,
+ "name": area_name(area),
+ "depth": area_depth(area),
+ "parent": area_parent(area),
+ "has_children": has_children,
+ "direct_file_count": direct,
+ "file_count": rollup["file_count"],
+ "nloc": rollup["nloc"],
+ "health": rollup["average_health"],
+ "band": band_for(rollup["average_health"]),
+ "band_counts": {band: bands[band]["files"] for band in BAND_ORDER},
+ "worst_file": {
+ "path": rollup["worst_performer_path"],
+ "score": rollup["worst_performer_score"],
+ },
+ "hotspot_count": sum(1 for g in git if row_field(g, "is_hotspot")),
+ "bus_factor_1_count": sum(1 for g in git if row_field(g, "bus_factor") == 1),
+ "primary_owner": primary_owner(owner_breakdown(paths, index.owners, len(paths))),
+ "line_coverage_pct": coverage,
+ "coverage_file_count": measured,
+ "findings": _sum_severities(paths, severities),
+ # Filled from the snapshot history by :func:`..trend.attach_deltas`.
+ "health_delta_30d": None,
+ }
+
+
+def build_area_index(
+ metrics: Iterable[Any],
+ *,
+ git_rows: Iterable[Any] = (),
+ owners: Mapping[str, FileOwner] | None = None,
+ findings: Iterable[Any] = (),
+ deductions: Mapping[str, float] | None = None,
+) -> AreaIndex:
+ """Fold every scored file into each directory above it, then roll each one up.
+
+ *findings* are the open findings the finding lists show; *deductions* the
+ per-file pre-clamp magnitudes the worst-first ranking breaks ties on.
+ """
+ members: dict[str, list[Any]] = defaultdict(list)
+ direct: dict[str, int] = defaultdict(int)
+ children: dict[str, set[str]] = defaultdict(set)
+ for row in (_pick(m, _METRIC_FIELDS) for m in scored_rows(metrics)):
+ chain = ancestors(row_field(row, "file_path"))
+ for area in chain:
+ members[area].append(row)
+ direct[chain[-1]] += 1
+ for parent, child in pairwise(chain):
+ children[parent].add(child)
+
+ index = AreaIndex(
+ nodes={},
+ members=dict(members),
+ children={area: sorted(kids) for area, kids in children.items()},
+ git_by_path={
+ row_field(g, "file_path"): _pick(g, _GIT_FIELDS) for g in git_rows
+ },
+ owners=owners or {},
+ deductions=deductions or {},
+ )
+ index.findings = [finding_row(f) for f in findings]
+ severities = severity_by_file(index.findings)
+ for area, group in index.members.items():
+ index.nodes[area] = _node(
+ area,
+ group,
+ direct=direct.get(area, 0),
+ has_children=bool(index.children.get(area)),
+ index=index,
+ severities=severities,
+ )
+ return index
diff --git a/packages/core/src/repowise/core/analysis/areas/trend.py b/packages/core/src/repowise/core/analysis/areas/trend.py
new file mode 100644
index 000000000..ca78d574f
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/areas/trend.py
@@ -0,0 +1,92 @@
+"""Area health over the recorded snapshot history.
+
+A snapshot stores ``{path: score}`` and no line counts, so an area's score at a
+snapshot is weighted by the files' *current* NLOC (1 for a file that no longer
+exists). Both ends of a delta use the same weights, so the delta moves only
+when scores move, never because the weighting did. That is close to, not the
+same number as, the live area health, which the current rows weight exactly.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Mapping, Sequence
+from datetime import datetime, timedelta
+from typing import Any
+
+from repowise.core.analysis.health.rows import field
+
+from .paths import ancestors, in_area
+
+__all__ = [
+ "DELTA_WINDOW_DAYS",
+ "area_score",
+ "area_scores",
+ "attach_deltas",
+ "baseline_index",
+ "nloc_weights",
+]
+
+DELTA_WINDOW_DAYS = 30
+
+
+def nloc_weights(metrics: Sequence[Any]) -> dict[str, int]:
+ """``{path: weight}`` with the floor of 1 every health average uses."""
+ return {field(m, "file_path"): max(int(field(m, "nloc", 0) or 0), 1) for m in metrics}
+
+
+def area_scores(score_map: Mapping[str, float], weights: Mapping[str, int]) -> dict[str, float]:
+ """Every area's weighted score in one snapshot map."""
+ sums: dict[str, float] = defaultdict(float)
+ totals: dict[str, int] = defaultdict(int)
+ for path, score in score_map.items():
+ if score is None:
+ continue
+ weight = weights.get(path, 1)
+ for area in ancestors(path):
+ sums[area] += float(score) * weight
+ totals[area] += weight
+ return {area: round(sums[area] / totals[area], 2) for area in sums}
+
+
+def area_score(
+ score_map: Mapping[str, float], area: str, weights: Mapping[str, int]
+) -> float | None:
+ """One area's weighted score in one snapshot map, ``None`` when it held no file."""
+ total = weight_sum = 0.0
+ for path, score in score_map.items():
+ if score is None or not in_area(path, area):
+ continue
+ weight = weights.get(path, 1)
+ total += float(score) * weight
+ weight_sum += weight
+ return round(total / weight_sum, 2) if weight_sum else None
+
+
+def baseline_index(
+ taken: Sequence[datetime | None], window_days: int = DELTA_WINDOW_DAYS
+) -> int | None:
+ """The snapshot nearest *window_days* before the newest one, never the newest.
+
+ *taken* is oldest-first. ``None`` with fewer than two dated snapshots. The
+ chosen one may sit nearer than the window when the history is short; the
+ caller reports its date so the reading names its real span.
+ """
+ if len(taken) < 2 or taken[-1] is None:
+ return None
+ target = taken[-1] - timedelta(days=window_days)
+ dated = [(i, t) for i, t in enumerate(taken[:-1]) if t is not None]
+ if not dated:
+ return None
+ return min(dated, key=lambda item: (abs(item[1] - target), -item[0]))[0]
+
+
+def attach_deltas(
+ nodes: Mapping[str, dict[str, Any]],
+ latest: Mapping[str, float],
+ baseline: Mapping[str, float],
+) -> None:
+ """Set each node's ``health_delta_30d``; left ``None`` where either end lacks the area."""
+ for area, node in nodes.items():
+ if area in latest and area in baseline:
+ node["health_delta_30d"] = round(latest[area] - baseline[area], 2)
diff --git a/packages/core/src/repowise/core/analysis/health/aggregation.py b/packages/core/src/repowise/core/analysis/health/aggregation.py
index b0574d2aa..6843317db 100644
--- a/packages/core/src/repowise/core/analysis/health/aggregation.py
+++ b/packages/core/src/repowise/core/analysis/health/aggregation.py
@@ -38,6 +38,7 @@ __all__ = [
"biomarker_breakdown",
"finding_base_deduction",
"finding_raw_deduction",
+ "group_rollup",
"module_label",
"module_labels",
"module_rollups",
@@ -137,27 +138,36 @@ def module_rollups(
if module:
buckets.setdefault(str(module), []).append(row)
- rows: list[dict[str, Any]] = []
- for name, group in buckets.items():
- # Weight floors at 1 per file, so a non-empty group always has weight
- # and the average never divides by zero.
- total_weight = sum(max(_nloc(row), 1) for row in group)
- average = sum(_score(row) * max(_nloc(row), 1) for row in group) / total_weight
- worst = worst_metric(group, deductions or {})
- rows.append(
- {
- "module": name,
- "file_count": len(group),
- "nloc": sum(_nloc(row) for row in group),
- "average_health": round(average, 2),
- "worst_performer_path": field(worst, "file_path", None),
- "worst_performer_score": round(_score(worst), 2),
- }
- )
+ rows = [
+ {"module": name, **group_rollup(group, deductions)} for name, group in buckets.items()
+ ]
rows.sort(key=lambda row: (row["average_health"], row["module"]))
return rows
+def group_rollup(
+ group: Sequence[Any], deductions: Mapping[str, float] | None = None
+) -> dict[str, Any]:
+ """One NLOC-weighted rollup over a non-empty group of scored rows.
+
+ The fold :func:`module_rollups` applies per module, shared with any surface
+ that buckets files another way (a directory at any depth) so the average
+ and the worst performer mean the same thing everywhere.
+ """
+ # Weight floors at 1 per file, so a non-empty group always has weight
+ # and the average never divides by zero.
+ total_weight = sum(max(_nloc(row), 1) for row in group)
+ average = sum(_score(row) * max(_nloc(row), 1) for row in group) / total_weight
+ worst = worst_metric(group, deductions or {})
+ return {
+ "file_count": len(group),
+ "nloc": sum(_nloc(row) for row in group),
+ "average_health": round(average, 2),
+ "worst_performer_path": field(worst, "file_path", None),
+ "worst_performer_score": round(_score(worst), 2),
+ }
+
+
def severity_breakdown(findings: Iterable[Any]) -> dict[str, int]:
"""Counts per declared severity. Unrecognized severities are not counted.
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 38f26c040..f769ad8f7 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -148,13 +148,12 @@ over data already in the database.
from __future__ import annotations
import json
-from collections import OrderedDict
from collections.abc import Collection, Mapping
from dataclasses import dataclass
from pathlib import PurePosixPath
from typing import Any, Literal, NamedTuple, TypeAlias
-from sqlalchemy import func, select, text
+from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.execution_graph import (
@@ -163,7 +162,8 @@ from repowise.core.analysis.execution_graph import (
file_of_symbol,
)
from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES, FILE_DEPENDENCY_EDGE_TYPES
-from repowise.core.persistence.models import GraphNode, HealthFileMetric, Repository
+from repowise.core.persistence.index_cache import IndexStampCache
+from repowise.core.persistence.models import GraphNode
from repowise.core.test_paths import paired_test_names
from .dead_code.file_reachability import BARREL_FILENAMES
@@ -434,37 +434,7 @@ async def load_test_files(session: AsyncSession, repo_id: str) -> set[str]:
# Do next both walk from them. Ceiling: Do next's per-file reach is still
# walked once per index; persisting it at index time (the engine's
# ``RepoTestIndex.reached_files`` set, stored as a per-file bool) is the upgrade path.
-_CACHE_SIZE = 32
-_cache: OrderedDict[tuple[Any, ...], Any] = OrderedDict()
-
-
-async def _index_stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:
- """What moves when an index run rewrites the graph: the repository row and
- the file metrics written beside the graph rows (the stamp Fix first uses).
- One statement, so a cached answer costs one read."""
- repo = Repository.id == repo_id
- metrics = HealthFileMetric.repository_id == repo_id
- columns = (
- select(Repository.head_commit).where(repo),
- select(Repository.updated_at).where(repo),
- select(Repository.graph_edges_parser_fingerprint).where(repo),
- select(func.max(HealthFileMetric.updated_at)).where(metrics),
- select(func.count()).select_from(HealthFileMetric).where(metrics),
- )
- row = (await session.execute(select(*(c.scalar_subquery() for c in columns)))).one()
- return tuple(row)
-
-
-async def _cache_key(session: AsyncSession, repo_id: str, *parts: Any) -> tuple[Any, ...]:
- bind = str(session.bind.url) if session.bind is not None else None
- return (bind, repo_id, await _index_stamp(session, repo_id), *parts)
-
-
-def _remember(key: tuple[Any, ...], value: Any) -> Any:
- _cache[key] = value
- while len(_cache) > _CACHE_SIZE:
- _cache.popitem(last=False)
- return value
+_cache = IndexStampCache(32)
def clear_test_map_cache() -> None:
@@ -473,11 +443,10 @@ def clear_test_map_cache() -> None:
async def cached_test_files(session: AsyncSession, repo_id: str) -> frozenset[str]:
""":func:`load_test_files`, read once per index state; frozen because it is shared."""
- key = await _cache_key(session, repo_id, "test_files")
+ key = await _cache.key(session, repo_id, "test_files")
if key in _cache:
- _cache.move_to_end(key)
- return _cache[key]
- return _remember(key, frozenset(await load_test_files(session, repo_id)))
+ return _cache.get(key)
+ return _cache.remember(key, frozenset(await load_test_files(session, repo_id)))
async def any_tests_reaching(
@@ -490,16 +459,15 @@ async def any_tests_reaching(
For the rest, :func:`tests_reaching_through_helpers`. Cached per index state.
"""
seeds = tuple(sorted(set(targets)))
- key = await _cache_key(session, repo_id, "any_reach", seeds)
+ key = await _cache.key(session, repo_id, "any_reach", seeds)
if key in _cache:
- _cache.move_to_end(key)
- return _cache[key]
+ return _cache.get(key)
test_files = set(await cached_test_files(session, repo_id))
found = await tests_reaching_by_tier(session, repo_id, list(seeds), test_files=test_files)
rest = [s for s in seeds if s not in found]
if rest:
found |= await tests_reaching_through_helpers(session, repo_id, rest, test_files)
- return _remember(key, found)
+ return _cache.remember(key, found)
async def tests_reaching_through_helpers(
diff --git a/packages/core/src/repowise/core/persistence/index_cache.py b/packages/core/src/repowise/core/persistence/index_cache.py
new file mode 100644
index 000000000..8d64c10cd
--- /dev/null
+++ b/packages/core/src/repowise/core/persistence/index_cache.py
@@ -0,0 +1,71 @@
+"""In-process answers kept per (database, repository, index stamp).
+
+A read model folded from a whole repository's rows is the same answer until an
+index run rewrites those rows, so it is computed once per index state and kept
+in a small LRU. The stamp is what moves when an index run lands: the repository
+row and the file metrics written beside the graph rows. One statement, so a
+cached answer costs one read.
+"""
+
+from __future__ import annotations
+
+from collections import OrderedDict
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import HealthFileMetric, Repository
+
+__all__ = ["IndexStampCache", "index_stamp"]
+
+
+async def index_stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:
+ """What moves when an index run rewrites the graph and the health rows."""
+ repo = Repository.id == repo_id
+ metrics = HealthFileMetric.repository_id == repo_id
+ columns = (
+ select(Repository.head_commit).where(repo),
+ select(Repository.updated_at).where(repo),
+ select(Repository.graph_edges_parser_fingerprint).where(repo),
+ select(func.max(HealthFileMetric.updated_at)).where(metrics),
+ select(func.count()).select_from(HealthFileMetric).where(metrics),
+ )
+ row = (await session.execute(select(*(c.scalar_subquery() for c in columns)))).one()
+ return tuple(row)
+
+
+class IndexStampCache:
+ """A bounded LRU whose keys carry the database, repository and index stamp."""
+
+ def __init__(self, size: int) -> None:
+ self._size = size
+ self._entries: OrderedDict[tuple[Any, ...], Any] = OrderedDict()
+
+ async def key(self, session: AsyncSession, repo_id: str, *parts: Any) -> tuple[Any, ...]:
+ bind = str(session.bind.url) if session.bind is not None else None
+ return (bind, repo_id, await index_stamp(session, repo_id), *parts)
+
+ def __contains__(self, key: tuple[Any, ...]) -> bool:
+ return key in self._entries
+
+ def get(self, key: tuple[Any, ...]) -> Any:
+ """The kept answer (marked recently used); ``KeyError`` when absent."""
+ value = self._entries[key]
+ self._entries.move_to_end(key)
+ return value
+
+ def drop_repo(self, repo_id: str) -> None:
+ """Forget every answer kept for *repo_id*, for a caller that keeps one
+ state per repository: an older index state is never asked for again."""
+ for key in [k for k in self._entries if k[1] == repo_id]:
+ del self._entries[key]
+
+ def remember(self, key: tuple[Any, ...], value: Any) -> Any:
+ self._entries[key] = value
+ while len(self._entries) > self._size:
+ self._entries.popitem(last=False)
+ return value
+
+ def clear(self) -> None:
+ self._entries.clear()
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index b311d6023..815947363 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -22,6 +22,7 @@ from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
+from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from repowise.core.persistence.database import (
@@ -38,6 +39,7 @@ from repowise.core.providers.embedding.registry import DEFAULT_EMBEDDER
from repowise.server import __version__
from repowise.server.routers import (
actions,
+ areas,
blast_radius,
c4,
changes,
@@ -348,6 +350,7 @@ _ROUTERS = (
workspace,
owners,
modules,
+ areas,
overview,
stats,
files,
@@ -379,6 +382,12 @@ def create_app() -> FastAPI:
allow_headers=["*"],
)
+ # Whole-repo JSON (the map, area trees, file lists) compresses 10:1 or better.
+ # Starlette leaves ``text/event-stream`` alone, so chat and job streams still
+ # flush per event; below 1 KB the header costs more than it saves. Level 5
+ # keeps most of level 9's ratio at a fraction of its CPU on 600 KB bodies.
+ app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=5)
+
# Exception handlers
@app.exception_handler(LookupError)
async def not_found_handler(request: Request, exc: LookupError) -> JSONResponse:
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index 68ab254a0..10bcc5bc7 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -59,6 +59,7 @@ from repowise.server.job_state import (
_persist_initial_index_state,
_stamp_last_sync_commit,
)
+from repowise.server.services.areas import warm_area_model
logger = structlog.get_logger(__name__)
@@ -571,6 +572,9 @@ async def _run_index_job(run: _JobRun, app_state: Any) -> None:
pages_generated = await _record_index_completion(run, result, all_pages, elapsed)
await _write_index_state(run, docs, total_pages=len(all_pages))
await _reload_cross_repo_enricher(app_state, spec.job_id)
+ # The area rollup is read on the first dashboard load after an index; fold
+ # it here, in the job's own task, instead of on that first request.
+ await warm_area_model(run.session_factory, spec.repo_id)
logger.info(
"job_completed",
diff --git a/packages/server/src/repowise/server/routers/areas.py b/packages/server/src/repowise/server/routers/areas.py
new file mode 100644
index 000000000..cf104cb84
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/areas.py
@@ -0,0 +1,79 @@
+"""/api/repos/{repo_id}/areas/* — directory rollups at any depth.
+
+Thin: the fold is :mod:`repowise.core.analysis.areas`, the read model and its
+cache are :mod:`repowise.server.services.areas`.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.areas import ROOT_AREA, normalize_area
+from repowise.core.persistence import crud
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas.areas import AreaDetailResponse, AreaTreeResponse
+from repowise.server.services.areas import (
+ MAX_TREE_DEPTH,
+ area_detail_payload,
+ area_tree_payload,
+ load_area_model,
+)
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["areas"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+async def _require_repo(session: AsyncSession, repo_id: str) -> None:
+ if await crud.get_repository(session, repo_id) is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+
+def _no_area(area: str) -> HTTPException:
+ return HTTPException(status_code=404, detail=f"No scored files under area '{area}'")
+
+
+# Registered before the detail route, which would otherwise read "tree" as a path.
+# Ceiling: a top-level directory named ``tree`` is reachable only through
+# ``/areas/tree?root=tree``; a detail alias would lift it if a repo needs one.
[email protected]("/{repo_id}/areas/tree", response_model=AreaTreeResponse)
+async def get_area_tree(
+ repo_id: str,
+ root: str = Query(
+ ROOT_AREA, max_length=1024, description="Area to unfold; the repo root by default."
+ ),
+ depth: int = Query(1, ge=1, le=MAX_TREE_DEPTH, description="Levels below the root to include."),
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """The root area's rollup plus every directory up to *depth* levels below it.
+
+ Complete over every scored file, not the map's drawn field.
+ """
+ await _require_repo(session, repo_id)
+ area = normalize_area(root)
+ payload = area_tree_payload(await load_area_model(session, repo_id), area, depth)
+ if payload is None:
+ raise _no_area(area)
+ return payload
+
+
[email protected]("/{repo_id}/areas", response_model=AreaDetailResponse)
[email protected]("/{repo_id}/areas/{area_path:path}", response_model=AreaDetailResponse)
+async def get_area_detail(
+ repo_id: str,
+ area_path: str = ROOT_AREA,
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """One area's card: rollup, worst files, hotspots, owners, trend, findings, test reach."""
+ await _require_repo(session, repo_id)
+ area = normalize_area(area_path)
+ model = await load_area_model(session, repo_id)
+ payload = await area_detail_payload(session, repo_id, model, area)
+ if payload is None:
+ raise _no_area(area)
+ return payload
diff --git a/packages/server/src/repowise/server/routers/code_health/map_routes.py b/packages/server/src/repowise/server/routers/code_health/map_routes.py
index 9d2d623c6..e77b2f162 100644
--- a/packages/server/src/repowise/server/routers/code_health/map_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/map_routes.py
@@ -12,6 +12,7 @@ from typing import Any
from fastapi import Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.areas import normalize_area
from repowise.server.deps import get_db_session
from repowise.server.services.health_map import (
DEFAULT_MAP_CAP,
@@ -46,6 +47,14 @@ async def get_health_map(
max_length=200,
description="Pin the files whose path contains this substring, so search finds undrawn files.",
),
+ area: str | None = Query(
+ None,
+ max_length=1024,
+ description=(
+ "Narrow the field to this directory (any depth). Ranking and the cap "
+ "apply within it, and every count describes the area."
+ ),
+ ),
scope: str = ScopeQuery,
counts: str = CountsQuery,
session: AsyncSession = Depends(get_db_session),
@@ -58,5 +67,6 @@ async def get_health_map(
counts=counts,
include_held=include_held,
query=q,
+ area=normalize_area(area) or None,
)
return feed.payload()
diff --git a/packages/server/src/repowise/server/schemas/areas.py b/packages/server/src/repowise/server/schemas/areas.py
new file mode 100644
index 000000000..1dea824aa
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/areas.py
@@ -0,0 +1,170 @@
+"""Area response models: directory rollups at any depth.
+
+The repository root is the area ``""``. Every figure covers the area's scored
+files (a file health has no dialect for is in none), complete over the
+repository rather than capped like the map's drawn field.
+"""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel
+
+Band = Literal["at_risk", "needs_work", "fair", "good", "excellent"]
+
+
+class AreaOwner(BaseModel):
+ #: Identity key, as the contributors pages key people.
+ key: str
+ name: str
+ kind: Literal["human", "agent", "bot"]
+ #: Files in the area this identity is primary owner of.
+ files: int
+ #: ``files`` over the area's file count, 0-1.
+ share: float
+
+
+class AreaBandCounts(BaseModel):
+ at_risk: int
+ needs_work: int
+ fair: int
+ good: int
+ excellent: int
+
+
+class AreaSeverityCounts(BaseModel):
+ critical: int
+ high: int
+ medium: int
+ low: int
+
+
+class AreaWorstFile(BaseModel):
+ path: str | None
+ score: float
+
+
+class AreaNode(BaseModel):
+ path: str
+ #: Last path segment; ``""`` for the root.
+ name: str
+ #: Path segments; the root is 0.
+ depth: int
+ parent: str | None
+ has_children: bool
+ #: Files directly in this directory, not in a subdirectory.
+ direct_file_count: int
+ file_count: int
+ nloc: int
+ #: NLOC-weighted average score, the module-health fold.
+ health: float
+ band: Band
+ band_counts: AreaBandCounts
+ worst_file: AreaWorstFile
+ hotspot_count: int
+ #: Files whose bus factor is exactly 1.
+ bus_factor_1_count: int
+ #: The person owning the most files; automation never leads an area.
+ primary_owner: AreaOwner | None
+ #: NLOC-weighted line coverage over measured files; ``None`` with no report.
+ line_coverage_pct: float | None
+ coverage_file_count: int
+ #: Open findings per severity, advisory left out.
+ findings: AreaSeverityCounts
+ #: Score at the newest snapshot minus at the snapshot nearest 30 days
+ #: before it (see ``delta_window``); ``None`` when either lacks the area.
+ health_delta_30d: float | None
+
+
+class AreaDeltaWindow(BaseModel):
+ """The snapshots behind ``health_delta_30d``; the baseline may be nearer than 30 days."""
+
+ target_days: int
+ latest_at: str | None
+ baseline_at: str | None
+
+
+class AreaTreeResponse(BaseModel):
+ root: AreaNode
+ depth: int
+ #: Every area up to ``depth`` levels below the root, sorted by path.
+ nodes: list[AreaNode]
+ delta_window: AreaDeltaWindow
+
+
+class AreaBandShare(BaseModel):
+ files: int
+ nloc: int
+ #: NLOC-weighted share of the area, 0-100.
+ pct: float
+
+
+class AreaBandShares(BaseModel):
+ at_risk: AreaBandShare
+ needs_work: AreaBandShare
+ fair: AreaBandShare
+ good: AreaBandShare
+ excellent: AreaBandShare
+
+
+class AreaDistribution(BaseModel):
+ total_files: int
+ total_nloc: int
+ bands: AreaBandShares
+
+
+class AreaFileRow(BaseModel):
+ path: str
+ score: float
+ band: Band
+ nloc: int
+
+
+class AreaHotspots(BaseModel):
+ total: int
+ files: list[AreaFileRow]
+
+
+class AreaOwners(BaseModel):
+ total: int
+ top: list[AreaOwner]
+
+
+class AreaTrendPoint(BaseModel):
+ taken_at: str | None
+ health: float
+
+
+class AreaFinding(BaseModel):
+ id: str
+ file_path: str
+ biomarker_type: str
+ severity: str
+ function_name: str | None
+ line_start: int | None
+ health_impact: float | None
+ reason: str | None
+
+
+class AreaTestReach(BaseModel):
+ files: int
+ #: Files with a paired test file.
+ with_test_file: int
+ measured_files: int
+ line_coverage_pct: float | None
+
+
+class AreaDetailResponse(BaseModel):
+ area: AreaNode
+ distribution: AreaDistribution
+ #: Worst-first, bounded.
+ worst_files: list[AreaFileRow]
+ hotspots: AreaHotspots
+ owners: AreaOwners
+ #: Area score per snapshot, oldest first, over the newest 20 snapshots.
+ trend: list[AreaTrendPoint]
+ #: First open findings in the finding lists' priority order.
+ top_findings: list[AreaFinding]
+ test_reach: AreaTestReach
+ delta_window: AreaDeltaWindow
diff --git a/packages/server/src/repowise/server/services/areas.py b/packages/server/src/repowise/server/services/areas.py
new file mode 100644
index 000000000..214446506
--- /dev/null
+++ b/packages/server/src/repowise/server/services/areas.py
@@ -0,0 +1,244 @@
+"""Area read model: loads the rows the rollup folds, once per index state.
+
+The fold itself lives in :mod:`repowise.core.analysis.areas`; this module reads
+the stored analysis, keeps the folded index per (database, repository, index
+stamp, area stamp), and shapes the tree and detail answers. The area stamp
+covers what can move without an index run: findings triage and a snapshot
+written after the scores.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+import structlog
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from repowise.core.analysis.areas import (
+ AreaIndex,
+ area_depth,
+ area_detail,
+ area_score,
+ area_scores,
+ attach_deltas,
+ baseline_index,
+ build_area_index,
+ file_owners,
+ in_area,
+ nloc_weights,
+)
+from repowise.core.analysis.areas.trend import DELTA_WINDOW_DAYS
+from repowise.core.persistence import crud
+from repowise.core.persistence.crud import code_file_rows
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.index_cache import IndexStampCache
+from repowise.core.persistence.models import (
+ GitCommit,
+ GitMetadata,
+ HealthFinding,
+ HealthSnapshot,
+)
+
+__all__ = [
+ "MAX_TREE_DEPTH",
+ "TREND_POINTS",
+ "AreaReadModel",
+ "area_detail_payload",
+ "area_tree_payload",
+ "clear_area_cache",
+ "load_area_model",
+ "warm_area_model",
+]
+
+logger = structlog.get_logger(__name__)
+
+#: Levels one tree request may unfold below its root. Deeper is a second request.
+MAX_TREE_DEPTH = 4
+
+#: Snapshots an area trend reads, newest last; the repo trend's default window.
+TREND_POINTS = 20
+
+#: Folded indexes, one per repository (older states are dropped): a few MB
+#: each on a 6k-file repository.
+_models = IndexStampCache(4)
+#: Area cards, the ones a reader opens.
+_details = IndexStampCache(128)
+#: One build per repository at a time; a concurrent caller waits and reads the
+#: cache instead of folding the same rows again.
+_locks: dict[str, asyncio.Lock] = {}
+
+
+def clear_area_cache() -> None:
+ _models.clear()
+ _details.clear()
+ # A lock is bound to the loop that first waited on it.
+ _locks.clear()
+
+
+@dataclass
+class AreaReadModel:
+ index: AreaIndex
+ weights: dict[str, int]
+ latest_at: datetime | None
+ baseline_at: datetime | None
+
+
+async def _area_stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:
+ """What moves the model between index runs: a finding triaged, a snapshot
+ recorded after the scores. One statement, beside the index stamp. Git rows
+ are rewritten with the health rows (the index stamp sees those), so they
+ are not scanned here: on this repository that scan was most of a warm read."""
+ columns = []
+ for model, moved in (
+ (HealthFinding, HealthFinding.updated_at),
+ (HealthSnapshot, HealthSnapshot.taken_at),
+ ):
+ mine = model.repository_id == repo_id
+ columns += [
+ select(func.max(moved)).where(mine),
+ select(func.count()).select_from(model).where(mine),
+ ]
+ row = (await session.execute(select(*(c.scalar_subquery() for c in columns)))).one()
+ return tuple(row)
+
+
+def _score_map(raw: str | None) -> dict[str, float]:
+ try:
+ parsed = json.loads(raw or "{}")
+ except ValueError:
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+async def _snapshot_map(session: AsyncSession, snap: Any) -> dict[str, float]:
+ """One snapshot's ``{path: score}``, loaded now because the list deferred it."""
+ await session.refresh(snap, ["per_file_scores_json"])
+ return _score_map(snap.per_file_scores_json)
+
+
+async def _git_rows(session: AsyncSession, repo_id: str) -> list[Any]:
+ g = GitMetadata
+ columns = (
+ g.file_path,
+ g.is_hotspot,
+ g.bus_factor,
+ g.primary_owner_name,
+ g.primary_owner_email,
+ g.top_authors_json,
+ )
+ return list((await session.execute(select(*columns).where(code_file_rows(repo_id)))).all())
+
+
+async def _commit_rows(session: AsyncSession, repo_id: str) -> list[Any]:
+ """Commit authors, so owner keys resolve as on the contributors pages."""
+ q = select(GitCommit.author_name, GitCommit.author_email).where(
+ GitCommit.repository_id == repo_id
+ )
+ return list((await session.execute(q)).all())
+
+
+async def _build(session: AsyncSession, repo_id: str) -> AreaReadModel:
+ metrics = await crud.get_health_metrics(session, repo_id)
+ git_rows = await _git_rows(session, repo_id)
+ index = build_area_index(
+ metrics,
+ git_rows=git_rows,
+ owners=file_owners(git_rows, await _commit_rows(session, repo_id)),
+ findings=await crud.get_health_findings(session, repo_id),
+ deductions=await crud.get_deduction_by_path(session, repo_id),
+ )
+ weights = nloc_weights(metrics)
+ history = await crud.list_health_snapshots(session, repo_id, file_maps=False)
+ base = baseline_index([s.taken_at for s in history])
+ if base is None:
+ return AreaReadModel(index, weights, None, None)
+ latest, baseline = history[-1], history[base]
+ attach_deltas(
+ index.nodes,
+ area_scores(await _snapshot_map(session, latest), weights),
+ area_scores(await _snapshot_map(session, baseline), weights),
+ )
+ return AreaReadModel(index, weights, latest.taken_at, baseline.taken_at)
+
+
+async def load_area_model(session: AsyncSession, repo_id: str) -> AreaReadModel:
+ """The folded area index for *repo_id*, built once per index and findings state."""
+ key = await _models.key(session, repo_id, await _area_stamp(session, repo_id))
+ if key in _models:
+ return _models.get(key)
+ async with _locks.setdefault(repo_id, asyncio.Lock()):
+ if key in _models:
+ return _models.get(key)
+ model = await _build(session, repo_id)
+ _models.drop_repo(repo_id)
+ return _models.remember(key, model)
+
+
+async def warm_area_model(
+ session_factory: async_sessionmaker[AsyncSession], repo_id: str
+) -> None:
+ """Fold *repo_id*'s areas now, so the first reader after an index run does
+ not pay for it. Best effort: a failure leaves the build to that reader.
+ Ceiling: an index written outside this process (``repowise update`` from
+ the CLI) is still folded on first read."""
+ try:
+ async with get_session(session_factory) as session:
+ await load_area_model(session, repo_id)
+ except Exception:
+ logger.warning("areas_warm_failed", repo_id=repo_id, exc_info=True)
+
+
+def _iso(dt: datetime | None) -> str | None:
+ return dt.isoformat() if dt is not None else None
+
+
+def _delta_window(model: AreaReadModel) -> dict[str, Any]:
+ return {
+ "target_days": DELTA_WINDOW_DAYS,
+ "latest_at": _iso(model.latest_at),
+ "baseline_at": _iso(model.baseline_at),
+ }
+
+
+def area_tree_payload(model: AreaReadModel, root: str, depth: int) -> dict[str, Any] | None:
+ """*root*'s rollup and every area up to *depth* levels below it, parents first."""
+ nodes = model.index.nodes
+ root_node = nodes.get(root)
+ if root_node is None:
+ return None
+ floor = area_depth(root)
+ below = [
+ node
+ for area, node in nodes.items()
+ if area != root and in_area(area, root) and node["depth"] - floor <= depth
+ ]
+ below.sort(key=lambda node: node["path"])
+ return {
+ "root": root_node,
+ "depth": depth,
+ "nodes": below,
+ "delta_window": _delta_window(model),
+ }
+
+
+async def area_detail_payload(
+ session: AsyncSession, repo_id: str, model: AreaReadModel, area: str
+) -> dict[str, Any] | None:
+ """The area card, its trend read from the newest :data:`TREND_POINTS` snapshots."""
+ if area not in model.index.nodes:
+ return None
+ key = await _details.key(session, repo_id, area, await _area_stamp(session, repo_id))
+ if key in _details:
+ return _details.get(key)
+ trend = []
+ for snap in await crud.list_health_snapshots(session, repo_id, limit=TREND_POINTS):
+ score = area_score(_score_map(snap.per_file_scores_json), area, model.weights)
+ if score is not None:
+ trend.append({"taken_at": _iso(snap.taken_at), "health": score})
+ detail = area_detail(model.index, area, trend=trend)
+ return _details.remember(key, {**detail, "delta_window": _delta_window(model)})
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
index 486539afd..0ef52034d 100644
--- a/packages/server/src/repowise/server/services/health_map.py
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -26,6 +26,7 @@ from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.areas import in_area
from repowise.core.analysis.finding_registry import HELD_ORIGINS
from repowise.core.analysis.health.counts import DEFAULT_COUNTS
from repowise.core.analysis.health.counts import project as project_counts
@@ -92,11 +93,14 @@ class HealthMapFeed:
#: Which half of the repository the field describes.
scope: str = DEFAULT_SCOPE
counts: str = DEFAULT_COUNTS
+ #: The directory the field is narrowed to, ``None`` for the whole repository.
+ area: str | None = None
def payload(self) -> dict[str, Any]:
return {
"scope": self.scope,
"counts": self.counts,
+ "area": self.area,
"files": self.files,
"cap": self.cap,
"shown": self.shown,
@@ -144,10 +148,16 @@ class HealthMapService:
counts: str = DEFAULT_COUNTS,
include_held: bool = False,
query: str | None = None,
+ area: str | None = None,
) -> HealthMapFeed:
session, repo_id = self._session, self._repository_id
metrics = await crud.get_health_metrics(session, repo_id)
rollups = await crud.performance_file_rollups(session, repo_id)
+ if area:
+ # A drilled area is its own field: every count, the cap and the
+ # performance totals below describe the area, never the repository.
+ metrics = [m for m in metrics if in_area(m.file_path, area)]
+ rollups = [r for r in rollups if in_area(r.file_path, area)]
languages = await crud.get_file_language_map(session, repo_id)
summary = await crud.get_performance_summary(session, repo_id)
perf_languages = supported_perf_languages()
@@ -315,6 +325,7 @@ class HealthMapService:
),
scope=DEFAULT_SCOPE if not scope_narrowed else "production",
counts=counts,
+ area=area or None,
)
def _row(
diff --git a/packages/types/package.json b/packages/types/package.json
index e32309b1a..24c0dea60 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -36,6 +36,7 @@
"./files": "./src/files.ts",
"./external-systems": "./src/external-systems.ts",
"./health": "./src/health.ts",
+ "./areas": "./src/areas.ts",
"./coupling": "./src/coupling.ts",
"./stats": "./src/stats.ts",
"./refactoring": "./src/refactoring.ts",
diff --git a/packages/types/src/areas.ts b/packages/types/src/areas.ts
new file mode 100644
index 000000000..546f4c17d
--- /dev/null
+++ b/packages/types/src/areas.ts
@@ -0,0 +1,25 @@
+/**
+ * Areas: any directory at any depth, rolled up from the stored analysis.
+ *
+ * Generated from the server's response models
+ * (`packages/server/src/repowise/server/schemas/areas.py`) for
+ * `GET /api/repos/{id}/areas/tree` and `GET /api/repos/{id}/areas/{path}`.
+ * The repository root is the area `""`. Every figure covers the area's scored
+ * files, complete rather than capped like the map's drawn field.
+ */
+export type {
+ AreaDeltaWindow,
+ AreaDetailResponse as AreaDetail,
+ AreaFileRow,
+ AreaFinding,
+ AreaNode,
+ AreaOwner,
+ AreaTreeResponse as AreaTree,
+} from "./generated/http.js";
+
+export interface AreaTreeQuery {
+ /** Area to unfold; the repository root by default. */
+ root?: string;
+ /** Levels below the root, 1-4. */
+ depth?: number;
+}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index b2915f48e..85d1eeea5 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -254,6 +254,142 @@ export interface ArchitectureViewResponse {
entry_candidates?: string[];
}
+export interface AreaBandCounts {
+ at_risk: number;
+ needs_work: number;
+ fair: number;
+ good: number;
+ excellent: number;
+}
+
+export interface AreaBandShare {
+ files: number;
+ nloc: number;
+ pct: number;
+}
+
+export interface AreaBandShares {
+ at_risk: AreaBandShare;
+ needs_work: AreaBandShare;
+ fair: AreaBandShare;
+ good: AreaBandShare;
+ excellent: AreaBandShare;
+}
+
+/** The snapshots behind ``health_delta_30d``; the baseline may be nearer than 30 days. */
+export interface AreaDeltaWindow {
+ target_days: number;
+ latest_at: string | null;
+ baseline_at: string | null;
+}
+
+export interface AreaDetailResponse {
+ area: AreaNode;
+ distribution: AreaDistribution;
+ worst_files: AreaFileRow[];
+ hotspots: AreaHotspots;
+ owners: AreaOwners;
+ trend: AreaTrendPoint[];
+ top_findings: AreaFinding[];
+ test_reach: AreaTestReach;
+ delta_window: AreaDeltaWindow;
+}
+
+export interface AreaDistribution {
+ total_files: number;
+ total_nloc: number;
+ bands: AreaBandShares;
+}
+
+export interface AreaFileRow {
+ path: string;
+ score: number;
+ band: "at_risk" | "needs_work" | "fair" | "good" | "excellent";
+ nloc: number;
+}
+
+export interface AreaFinding {
+ id: string;
+ file_path: string;
+ biomarker_type: string;
+ severity: string;
+ function_name: string | null;
+ line_start: number | null;
+ health_impact: number | null;
+ reason: string | null;
+}
+
+export interface AreaHotspots {
+ total: number;
+ files: AreaFileRow[];
+}
+
+export interface AreaNode {
+ path: string;
+ name: string;
+ depth: number;
+ parent: string | null;
+ has_children: boolean;
+ direct_file_count: number;
+ file_count: number;
+ nloc: number;
+ health: number;
+ band: "at_risk" | "needs_work" | "fair" | "good" | "excellent";
+ band_counts: AreaBandCounts;
+ worst_file: AreaWorstFile;
+ hotspot_count: number;
+ bus_factor_1_count: number;
+ primary_owner: AreaOwner | null;
+ line_coverage_pct: number | null;
+ coverage_file_count: number;
+ findings: AreaSeverityCounts;
+ health_delta_30d: number | null;
+}
+
+export interface AreaOwner {
+ key: string;
+ name: string;
+ kind: "human" | "agent" | "bot";
+ files: number;
+ share: number;
+}
+
+export interface AreaOwners {
+ total: number;
+ top: AreaOwner[];
+}
+
+export interface AreaSeverityCounts {
+ critical: number;
+ high: number;
+ medium: number;
+ low: number;
+}
+
+export interface AreaTestReach {
+ files: number;
+ with_test_file: number;
+ measured_files: number;
+ line_coverage_pct: number | null;
+}
+
+export interface AreaTreeResponse {
+ root: AreaNode;
+ depth: number;
+ nodes: AreaNode[];
+ delta_window: AreaDeltaWindow;
+}
+
+export interface AreaTrendPoint {
+ taken_at: string | null;
+ health: number;
+}
+
+export interface AreaWorstFile {
+ path: string | null;
+ score: number;
+}
+
export interface ArtifactUpdateRequest {
pinned: boolean;
}
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 7c0953c5f..9a1b0b6e2 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -963,6 +963,8 @@ export interface HealthMapPerformance {
* caption can never disagree with the field beside it.
*/
export interface HealthMapFeed {
+ /** The directory the field is narrowed to; `null` for the whole repository. Absent on older servers. */
+ area?: string | null;
files: HealthFileMetric[];
cap: number;
shown: number;
@@ -988,6 +990,8 @@ export interface HealthMapQuery {
include_held?: boolean;
/** Pin files whose path contains this substring. */
q?: string;
+ /** Narrow the field to this directory; the cap and every count then describe it. */
+ area?: string;
}
/* ------------------------------------------------------------------ *
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 7773875be..b0322f42c 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -35,6 +35,7 @@ export * from "./repos.js";
export * from "./files.js";
export * from "./external-systems.js";
export * from "./health.js";
+export * from "./areas.js";
export * from "./coupling.js";
export * from "./stats.js";
export * from "./refactoring.js";
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index e09133501..3641cf671 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -56,6 +56,7 @@ export default defineConfig({
"../types/src/external-systems.ts",
),
"@repowise-dev/types/health": path.resolve(__dirname, "../types/src/health.ts"),
+ "@repowise-dev/types/areas": path.resolve(__dirname, "../types/src/areas.ts"),
"@repowise-dev/types/refactoring": path.resolve(
__dirname,
"../types/src/refactoring.ts",
diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.js
index 89e702c98..558c247a7 100644
--- a/plugins/claude-code/hooks/lens/lens.js
+++ b/plugins/claude-code/hooks/lens/lens.js
@@ -3283,7 +3283,8 @@ async function getHealthMap(repoId, opts = {}) {
scope: opts.scope,
counts: opts.counts,
include_held: opts.include_held || void 0,
- q: opts.q?.trim() || void 0
+ q: opts.q?.trim() || void 0,
+ area: opts.area || void 0
});
}
diff --git a/tests/unit/analysis/test_areas.py b/tests/unit/analysis/test_areas.py
new file mode 100644
index 000000000..604f145ee
--- /dev/null
+++ b/tests/unit/analysis/test_areas.py
@@ -0,0 +1,144 @@
+"""Area rollups: directories at any depth folded from stored rows, purely."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.analysis.areas import (
+ FileOwner,
+ ancestors,
+ area_detail,
+ area_score,
+ area_scores,
+ attach_deltas,
+ baseline_index,
+ build_area_index,
+ in_area,
+ nloc_weights,
+ normalize_area,
+)
+from repowise.core.analysis.areas.paths import area_parent
+from repowise.core.analysis.health.aggregation import module_rollups
+
+
+def _m(path, score, nloc=10, **extra):
+ return {"file_path": path, "score": score, "nloc": nloc, "is_test": False, **extra}
+
+
+METRICS = [
+ _m("README.py", 9.0, 5),
+ _m("a/x.py", 4.0, 100, line_coverage_pct=50.0, has_test_file=True),
+ _m("a/y.py", 9.0, 300, line_coverage_pct=90.0),
+ _m("a/b/z.py", 2.0, 50),
+ _m("c/w.py", 8.0, 10),
+ _m("c/unscored.md", None, 10),
+]
+GIT = [
+ {"file_path": "a/x.py", "is_hotspot": True, "bus_factor": 1},
+ {"file_path": "a/y.py", "is_hotspot": False, "bus_factor": 3},
+ {"file_path": "a/b/z.py", "is_hotspot": True, "bus_factor": 1},
+]
+ALICE = FileOwner("[email protected]", "Alice", "human")
+BOT = FileOwner("bot@ci", "ci-bot", "bot")
+OWNERS = {"a/x.py": BOT, "a/y.py": BOT, "a/b/z.py": ALICE}
+FINDINGS = [
+ {"file_path": "a/b/z.py", "severity": "high", "biomarker_type": "complex_method", "id": "1"},
+ {"file_path": "a/x.py", "severity": "low", "biomarker_type": "large_method", "id": "2"},
+ {"file_path": "c/w.py", "severity": "critical", "biomarker_type": "complex_method", "id": "3"},
+]
+
+
+def _index():
+ return build_area_index(METRICS, git_rows=GIT, owners=OWNERS, findings=FINDINGS)
+
+
+def test_paths_name_every_enclosing_directory():
+ assert ancestors("a/b/c.py") == ["", "a", "a/b"]
+ assert ancestors("top.py") == [""]
+ assert normalize_area("/a\\b/./") == "a/b"
+ assert normalize_area(None) == ""
+ assert in_area("a/b/c.py", "a") and not in_area("ab/c.py", "a")
+ assert in_area("anything.py", "")
+ assert area_parent("a/b") == "a" and area_parent("a") == "" and area_parent("") is None
+
+
+def test_every_directory_rolls_up_with_module_semantics():
+ index = _index()
+ assert set(index.nodes) == {"", "a", "a/b", "c"}
+ # The fold module health uses: same average, same worst performer.
+ rows = [{**m, "module": "a"} for m in METRICS if m["file_path"].startswith("a/")]
+ (expected,) = module_rollups(rows)
+ node = index.nodes["a"]
+ assert node["health"] == expected["average_health"]
+ assert node["file_count"] == expected["file_count"] == 3
+ assert node["worst_file"] == {
+ "path": expected["worst_performer_path"],
+ "score": expected["worst_performer_score"],
+ }
+ # Unscored files are in no figure, as in module_rollups.
+ assert index.nodes["c"]["file_count"] == 1
+
+
+def test_tree_shape_counts_direct_files_and_children():
+ index = _index()
+ assert index.children[""] == ["a", "c"]
+ assert index.nodes[""]["direct_file_count"] == 1
+ assert index.nodes["a"]["direct_file_count"] == 2
+ assert index.nodes["a"]["has_children"] and not index.nodes["a/b"]["has_children"]
+ assert index.nodes["a/b"]["depth"] == 2 and index.nodes["a/b"]["parent"] == "a"
+
+
+def test_signals_bands_coverage_and_findings():
+ a = _index().nodes["a"]
+ assert a["hotspot_count"] == 2
+ assert a["bus_factor_1_count"] == 2
+ assert a["band_counts"] == {
+ "at_risk": 1, "needs_work": 1, "fair": 0, "good": 0, "excellent": 1
+ }
+ # NLOC-weighted over measured files only.
+ assert a["line_coverage_pct"] == round((50 * 100 + 90 * 300) / 400, 2)
+ assert a["coverage_file_count"] == 2
+ assert a["findings"] == {"critical": 0, "high": 1, "medium": 0, "low": 1}
+ assert _index().nodes["c"]["line_coverage_pct"] is None
+
+
+def test_automation_never_leads_an_area():
+ a = _index().nodes["a"]
+ # The bot owns two files, Alice one: Alice still leads, share of all three.
+ assert a["primary_owner"]["key"] == "[email protected]"
+ assert a["primary_owner"]["share"] == round(1 / 3, 4)
+ assert _index().nodes["c"]["primary_owner"] is None
+
+
+def test_snapshot_scores_use_current_weights_and_deltas_attach():
+ weights = nloc_weights(METRICS)
+ old = {"a/x.py": 2.0, "a/y.py": 9.0, "gone/q.py": 5.0}
+ new = {"a/x.py": 4.0, "a/y.py": 9.0}
+ assert area_score(old, "a", weights) == round((2 * 100 + 9 * 300) / 400, 2)
+ assert area_scores(old, weights)["gone"] == 5.0
+ assert area_score(new, "c", weights) is None
+ index = _index()
+ attach_deltas(index.nodes, area_scores(new, weights), area_scores(old, weights))
+ assert index.nodes["a"]["health_delta_30d"] == round(
+ area_score(new, "a", weights) - area_score(old, "a", weights), 2
+ )
+ assert index.nodes["c"]["health_delta_30d"] is None
+
+
+def test_baseline_is_nearest_thirty_days_back_and_never_the_newest():
+ days = [datetime(2026, 9, d) for d in (1, 10, 20, 30)]
+ assert baseline_index(days) == 0 # Sep 30 - 30d = Aug 31, nearest Sep 1
+ assert baseline_index(days[2:]) == 0 # short history: the only older one
+ assert baseline_index(days[:1]) is None
+
+
+def test_detail_lists_are_bounded_and_worst_first():
+ index = _index()
+ detail = area_detail(index, "a", trend=[{"taken_at": "t", "health": 7.0}], limit=2)
+ assert [f["path"] for f in detail["worst_files"]] == ["a/b/z.py", "a/x.py"]
+ assert detail["hotspots"]["total"] == 2
+ assert detail["owners"]["top"][0]["key"] == "bot@ci"
+ assert [f["id"] for f in detail["top_findings"]] == ["1", "2"]
+ assert detail["test_reach"]["with_test_file"] == 1
+ assert detail["distribution"]["total_files"] == 3
+ assert area_detail(index, "nope") is None
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index d7aa82357..016d5a4b1 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -23,9 +23,12 @@ def cursor_hooks_json(tmp_path_factory, monkeypatch):
@pytest.fixture(autouse=True)
def fresh_test_map_cache():
"""In-memory stores reuse one URL and seed graph rows without moving the
- index stamp, so the process-wide test-map cache starts empty per test."""
+ index stamp, so the process-wide index-state caches start empty per test."""
from repowise.core.analysis.test_reachability import clear_test_map_cache
+ from repowise.server.services.areas import clear_area_cache
clear_test_map_cache()
+ clear_area_cache()
yield
clear_test_map_cache()
+ clear_area_cache()
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index 984407ae2..d0e6bc8d0 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -31,6 +31,7 @@ def _create_test_app():
from fastapi.responses import JSONResponse
from repowise.server.routers import (
+ areas,
blast_radius,
c4,
changes,
@@ -103,6 +104,7 @@ def _create_test_app():
app.include_router(code_health.router)
app.include_router(owners.router)
app.include_router(modules.router)
+ app.include_router(areas.router)
app.include_router(decisions.router)
app.include_router(episodes.router)
app.include_router(external_systems.router)
diff --git a/tests/unit/server/test_areas_routes.py b/tests/unit/server/test_areas_routes.py
new file mode 100644
index 000000000..2d0d0e3e2
--- /dev/null
+++ b/tests/unit/server/test_areas_routes.py
@@ -0,0 +1,162 @@
+"""/areas/tree, /areas/{path} and /health/map?area= over a seeded store."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+from httpx import AsyncClient
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.persistence import crud
+from tests.unit.server.conftest import create_test_repo
+
+
+def _metric(path: str, score: float, nloc: int) -> dict:
+ return {
+ "file_path": path,
+ "score": score,
+ "max_ccn": 3,
+ "max_nesting": 2,
+ "nloc": nloc,
+ "duplication_pct": 0.0,
+ "has_test_file": False,
+ "line_coverage_pct": None,
+ "branch_coverage_pct": None,
+ "module": path.split("/")[0],
+ }
+
+
+async def _seed(app, client: AsyncClient) -> str:
+ repo_id = (await create_test_repo(client))["id"]
+ now = datetime.now(UTC)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(
+ session,
+ repo_id,
+ [
+ _metric("src/core/a.py", 3.0, 100),
+ _metric("src/core/b.py", 9.0, 100),
+ _metric("src/ui/c.py", 8.0, 50),
+ _metric("docs/d.py", 10.0, 5),
+ ],
+ )
+ await crud.save_health_findings(
+ session,
+ repo_id,
+ [
+ HealthFindingData(
+ biomarker_type="complex_method",
+ severity=Severity.HIGH,
+ file_path="src/core/a.py",
+ function_name="run",
+ line_start=3,
+ line_end=30,
+ details={},
+ health_impact=2.0,
+ reason="run branches a lot",
+ )
+ ],
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/core/a.py",
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ is_hotspot=True,
+ bus_factor=1,
+ )
+ for days_ago, a_score in ((31, 2.0), (0, 3.0)):
+ await crud.save_health_snapshot(
+ session,
+ repo_id,
+ hotspot_health=None,
+ average_health=7.0,
+ worst_performer_path=None,
+ worst_performer_score=None,
+ per_file_scores={"src/core/a.py": a_score, "src/core/b.py": 9.0},
+ taken_at=now - timedelta(days=days_ago),
+ )
+ await session.commit()
+ return repo_id
+
+
+async def test_tree_unfolds_depth_levels_below_the_root(app, client):
+ repo_id = await _seed(app, client)
+ one = (await client.get(f"/api/repos/{repo_id}/areas/tree", params={"depth": 1})).json()
+ assert one["root"]["file_count"] == 4
+ assert [n["path"] for n in one["nodes"]] == ["docs", "src"]
+ two = (await client.get(f"/api/repos/{repo_id}/areas/tree", params={"depth": 2})).json()
+ assert [n["path"] for n in two["nodes"]] == ["docs", "src", "src/core", "src/ui"]
+ scoped = (
+ await client.get(f"/api/repos/{repo_id}/areas/tree", params={"root": "src/"})
+ ).json()
+ assert scoped["root"]["path"] == "src"
+ core = next(n for n in scoped["nodes"] if n["path"] == "src/core")
+ assert core["health"] == 6.0
+ assert core["hotspot_count"] == 1 and core["bus_factor_1_count"] == 1
+ assert core["primary_owner"]["name"] == "Alice"
+ assert core["findings"]["high"] == 1
+ # Snapshot weights are the current NLOC: (3*100 + 9*100)/200 - (2*100 + 9*100)/200.
+ assert core["health_delta_30d"] == 0.5
+
+
+async def test_detail_and_unknown_areas(app, client):
+ repo_id = await _seed(app, client)
+ detail = (await client.get(f"/api/repos/{repo_id}/areas/src/core")).json()
+ assert detail["area"]["path"] == "src/core"
+ assert detail["worst_files"][0]["path"] == "src/core/a.py"
+ assert [p["health"] for p in detail["trend"]] == [5.5, 6.0]
+ assert detail["top_findings"][0]["biomarker_type"] == "complex_method"
+ root = (await client.get(f"/api/repos/{repo_id}/areas")).json()
+ assert root["area"]["file_count"] == 4
+ missing = await client.get(f"/api/repos/{repo_id}/areas/tree", params={"root": "nope"})
+ assert missing.status_code == 404
+ assert (await client.get(f"/api/repos/{repo_id}/areas/nope")).status_code == 404
+ assert (await client.get("/api/repos/no-such-repo/areas/tree")).status_code == 404
+
+
+async def test_map_narrows_to_the_area_and_counts_it(app, client):
+ repo_id = await _seed(app, client)
+ feed = (
+ await client.get(f"/api/repos/{repo_id}/health/map", params={"area": "src/core"})
+ ).json()
+ assert feed["area"] == "src/core"
+ assert sorted(f["file_path"] for f in feed["files"]) == ["src/core/a.py", "src/core/b.py"]
+ assert feed["repository_total"] == 2
+ whole = (await client.get(f"/api/repos/{repo_id}/health/map")).json()
+ assert whole["area"] is None and whole["repository_total"] == 4
+
+
+async def test_a_new_snapshot_moves_the_cached_delta(app, client):
+ repo_id = await _seed(app, client)
+ url = f"/api/repos/{repo_id}/areas/tree"
+ before = (await client.get(url, params={"root": "src"})).json()
+ assert before["nodes"][0]["health_delta_30d"] == 0.5
+ async with app.state.session_factory() as session:
+ await crud.save_health_snapshot(
+ session,
+ repo_id,
+ hotspot_health=None,
+ average_health=7.0,
+ worst_performer_path=None,
+ worst_performer_score=None,
+ per_file_scores={"src/core/a.py": 4.0, "src/core/b.py": 9.0},
+ )
+ await session.commit()
+ after = (await client.get(url, params={"root": "src"})).json()
+ assert after["nodes"][0]["health_delta_30d"] == 1.0
+
+
+async def test_a_warmed_model_serves_the_next_read_without_a_build(app, client, monkeypatch):
+ from repowise.server.services import areas as service
+
+ repo_id = await _seed(app, client)
+ await service.warm_area_model(app.state.session_factory, repo_id)
+
+ async def no_build(*_args):
+ raise AssertionError("the warm-up should have built the model")
+
+ monkeypatch.setattr(service, "_build", no_build)
+ tree = await client.get(f"/api/repos/{repo_id}/areas/tree")
+ assert tree.status_code == 200