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
feat(server): one-call /api/repos/summary, and make file_count count files (#1577)
Raghav Chamadiyad96e0c74f3f3
diff --git a/packages/api-client/src/repos.ts b/packages/api-client/src/repos.tsindex 71dff7a32..4ec146081 100644--- a/packages/api-client/src/repos.ts+++ b/packages/api-client/src/repos.ts@@ -1,3 +1,4 @@+import type { ReposSummaryResponse } from "@repowise-dev/types/repos";import { apiGet, apiPost, apiPatch, apiDelete } from "./client";import type {RepoCreate,@@ -15,6 +16,13 @@ export async function listRepos(): Promise<RepoResponse[]> {return apiGet<RepoResponse[]>("/api/repos");}+/** One-call payload for the multi-repo dashboard: every registered repo's+ * headline figures. Replaces `listRepos` plus a `getRepoStats` and a+ * `getGitSummary` per repo, whose cost grew with the repository count. */+export async function getReposSummary(): Promise<ReposSummaryResponse> {+ return apiGet<ReposSummaryResponse>("/api/repos/summary");+}+export async function getRepo(repoId: string): Promise<RepoResponse> {return apiGet<RepoResponse>(`/api/repos/${repoId}`);}diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.pyindex ba3c33ca3..bb411f510 100644--- a/packages/core/src/repowise/core/persistence/crud/repository.py+++ b/packages/core/src/repowise/core/persistence/crud/repository.py@@ -102,7 +102,7 @@ def _read_head_commit(local_path: str) -> str | None:git_dir = Path(local_path) / ".git"# Linked worktrees use a ``.git`` *file* (gitdir pointer), not a dir;# treated as non-git here on purpose so this stays in lockstep with the- # MCP ``_meta._read_live_head`` reader (same is_dir() guard), keeping+ # MCP ``_meta.read_live_head`` reader (same is_dir() guard), keeping# the written commit and the read-back comparison symmetric.if not git_dir.is_dir():return Nonediff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex eb9867ea3..fe9735d51 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -31,7 +31,7 @@ from typing import Any_STALE_AGE_FLOOR_DAYS = 90-def _read_live_head(local_path: str | None) -> str | None:+def read_live_head(local_path: str | None) -> str | None:"""Read the repo's current git HEAD SHA via plain file I/O.Returns a full 40-char SHA, or ``None`` when the repo isn't a git checkout@@ -259,7 +259,7 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = Noneif indexed_full:out["indexed_commit"] = indexed_full[:12] if isinstance(indexed_full, str) else indexed_full- live_full = _read_live_head(local_path)+ live_full = read_live_head(local_path)if live_full and indexed_full:if live_full != indexed_full:diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex af75c112e..2b097f4fa 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -3,16 +3,18 @@from __future__ import annotationsimport asyncio+import contextlibimport ioimport loggingimport zipfilefrom pathlib import Path, PurePosixPath-from typing import Literal+from typing import Any, Literalfrom fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom fastapi.responses import PlainTextResponse, StreamingResponsefrom pydantic import BaseModel, Field-from sqlalchemy import func, select+from sqlalchemy import case, func, select+from sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.docs_mode import resolve_docs_mode@@ -21,14 +23,24 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (DeadCodeFinding,GenerationJob,+ GitMetadata,GraphNode,+ HealthSnapshot,Page,Repository,)from repowise.server.deps import get_db_session, get_fts, verify_api_keyfrom repowise.server.job_executor import execute_job+from repowise.server.mcp_server._meta import read_live_head, resolve_indexed_commitfrom repowise.server.routers._sorting import repository_sort_key-from repowise.server.schemas import RepoCreate, RepoResponse, RepoStatsResponse, RepoUpdate+from repowise.server.schemas import (+ RepoCreate,+ RepoResponse,+ ReposSummaryResponse,+ RepoStatsResponse,+ RepoSummaryRow,+ RepoUpdate,+)logger = logging.getLogger(__name__)@@ -292,6 +304,190 @@ async def list_repos(return responses+def _fresh_case(column: Any, value: Any) -> Any:+ """Portable conditional count. ``count(...) FILTER (WHERE ...)`` needs+ SQLite 3.30+ and this project ships no version floor, so every conditional+ count in the codebase is a ``sum(case(...))`` — see ``routers/git.py``."""+ return func.coalesce(func.sum(case((column == value, 1), else_=0)), 0)+++async def _summary_rows_for(session: AsyncSession) -> dict[str, dict[str, Any]]:+ """Headline figures for every repo in one database, five queries total.++ Grouped by ``repository_id`` rather than filtered per repo: the route this+ replaces ran six queries *per repository* for the stats alone, and+ ``/git-summary`` hydrated every ``git_metadata`` row (one per file, ~3.5k on+ this repo) to produce two integers.++ A table that does not exist yet — a repo registered but never analysed, an+ older store — degrades that section to zero rather than 500-ing the whole+ dashboard, which is the same contract ``routers/stats.py`` documents.+ """+ out: dict[str, dict[str, Any]] = {}++ def row_for(repo_id: str) -> dict[str, Any]:+ return out.setdefault(repo_id, {})++ # Files, symbols and entry points. `graph_nodes` holds symbol rows in the+ # same table, so every count here is scoped to `node_type == "file"`; the+ # unscoped count is what makes /stats report 38,813 "files" for 3,600.+ with contextlib.suppress(SQLAlchemyError):+ result = await session.execute(+ select(+ GraphNode.repository_id,+ func.count(GraphNode.id),+ func.coalesce(func.sum(GraphNode.symbol_count), 0),+ _fresh_case(GraphNode.is_entry_point, True),+ )+ .where(GraphNode.node_type == "file")+ .group_by(GraphNode.repository_id)+ )+ for repo_id, files, symbols, entries in result.all():+ row_for(repo_id).update(+ file_count=int(files or 0),+ symbol_count=int(symbols or 0),+ entry_point_count=int(entries or 0),+ )++ # Documentation pages and the fresh subset. Never selects `content`.+ with contextlib.suppress(SQLAlchemyError):+ result = await session.execute(+ select(+ Page.repository_id,+ func.count(Page.id),+ _fresh_case(Page.freshness_status, "fresh"),+ ).group_by(Page.repository_id)+ )+ for repo_id, pages, fresh in result.all():+ row_for(repo_id).update(+ doc_page_count=int(pages or 0),+ doc_fresh_page_count=int(fresh or 0),+ )++ # Open unused exports — the one dead-code figure the dashboard quotes.+ with contextlib.suppress(SQLAlchemyError):+ result = await session.execute(+ select(DeadCodeFinding.repository_id, func.count(DeadCodeFinding.id))+ .where(+ DeadCodeFinding.kind == "unused_export",+ DeadCodeFinding.status == "open",+ )+ .group_by(DeadCodeFinding.repository_id)+ )+ for repo_id, dead in result.all():+ row_for(repo_id).update(dead_export_count=int(dead or 0))++ # Hotspots, and the tracked-file denominator they are meaningful against.+ with contextlib.suppress(SQLAlchemyError):+ result = await session.execute(+ select(+ GitMetadata.repository_id,+ func.count(GitMetadata.id),+ _fresh_case(GitMetadata.is_hotspot, True),+ ).group_by(GitMetadata.repository_id)+ )+ for repo_id, tracked, hotspots in result.all():+ row_for(repo_id).update(+ tracked_file_count=int(tracked or 0),+ hotspot_count=int(hotspots or 0),+ )++ # Latest health snapshot per repo. Three scalar columns only: a snapshot+ # row carries `per_file_scores_json`, ~186 KB apiece, and selecting the+ # entity would pull the whole retained history's worth of it for two+ # floats (see crud.get_health_snapshot_headline's docstring). Reduced in+ # Python rather than with a window function, because retention bounds the+ # row count to tens per repo and window syntax is not uniform across the+ # two supported backends.+ with contextlib.suppress(SQLAlchemyError):+ result = await session.execute(+ select(+ HealthSnapshot.repository_id,+ HealthSnapshot.taken_at,+ HealthSnapshot.average_health,+ HealthSnapshot.hotspot_health,+ ).order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc())+ )+ for repo_id, taken_at, average, hotspot in result.all():+ # Ascending order means the last write per repo wins.+ row_for(repo_id).update(+ average_health=round(float(average), 2) if average is not None else None,+ hotspot_health=round(float(hotspot), 2) if hotspot is not None else None,+ health_taken_at=taken_at,+ )++ return out+++def _freshness_for(repo: RepoResponse) -> tuple[str | None, str | None, bool | None]:+ """(indexed commit, live HEAD, is the index behind) for one repo.++ Both reads are plain file I/O — `read_live_head` parses `.git/HEAD` and+ follows at most one ref rather than spawning git — so this stays cheap+ enough to run per repo on a page load. Returns ``None`` for+ ``index_behind`` when either side is unavailable, so "current" and+ "could not tell" never collapse into the same answer.+ """+ if not repo.local_path:+ return None, None, None+ indexed = resolve_indexed_commit(repo.head_commit, repo.local_path)+ live = read_live_head(repo.local_path)+ if not indexed or not live:+ return (indexed[:12] if indexed else None), (live[:12] if live else None), None+ return indexed[:12], live[:12], indexed != live++[email protected]("/summary", response_model=ReposSummaryResponse)+async def repos_summary(+ request: Request,+ session: AsyncSession = Depends(get_db_session),+) -> ReposSummaryResponse:+ """One-call payload for the multi-repo dashboard.++ Replaces a `2N+1` waterfall — `/api/repos`, then `/stats` and+ `/git-summary` per repository — with a single request whose cost does not+ grow with the number of repos.++ Declared **before** ``/{repo_id}``: FastAPI matches in declaration order,+ so a literal path registered after the parameterised one is unreachable+ and would answer 404 "Repository not found" instead.+ """+ repos = await list_repos(request, session)++ # Grouped aggregates from the ambient DB. In workspace mode each repo+ # keeps its own wiki.db and the primary session cannot see those rows, so+ # fan out the same way `list_repos` does. One unreadable DB drops that+ # repo's figures to zero rather than failing the page.+ stats = await _summary_rows_for(session)+ ws_sessions: dict = getattr(request.app.state, "workspace_sessions", {})+ for repo_id, ws_factory in ws_sessions.items():+ if repo_id in stats:+ continue+ try:+ async with ws_factory() as ws_session:+ stats.update(await _summary_rows_for(ws_session))+ except Exception: # one unreadable store must not fail the whole list+ logger.debug("repos_summary_workspace_db_unreadable", extra={"repo": repo_id})++ rows: list[RepoSummaryRow] = []+ for repo in repos:+ indexed, live, behind = _freshness_for(repo)+ rows.append(+ RepoSummaryRow(+ id=repo.id,+ name=repo.name,+ local_path=repo.local_path,+ updated_at=repo.updated_at,+ status=repo.workspace_status or "indexed",+ indexed_commit=indexed,+ live_head=live,+ index_behind=behind,+ **stats.get(repo.id, {}),+ )+ )+ return ReposSummaryResponse(repos=rows)++@router.get("/{repo_id}", response_model=RepoResponse)async def get_repo(repo_id: str,@@ -392,8 +588,16 @@ async def get_repo_stats(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")+ # File nodes only. `graph_nodes` holds symbol rows in the same table, so+ # the unscoped count reported ~10x the real figure — 38,813 against 3,600+ # on this codebase — under a field named `file_count`. Both surfaces that+ # read it printed that as "N files": the multi-repo dashboard and the chat+ # empty state.file_count_result = await session.execute(- select(func.count(GraphNode.id)).where(GraphNode.repository_id == repo_id)+ select(func.count(GraphNode.id)).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "file",+ ))file_count = file_count_result.scalar_one() or 0diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex e0eb31776..34e340e69 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -159,6 +159,8 @@ from .pagination import Paginatedfrom .repository import (RepoCreate,RepoResponse,+ ReposSummaryResponse,+ RepoSummaryRow,RepoUpdate,)from .search import (@@ -333,7 +335,9 @@ __all__ = ["RepoCreate","RepoResponse","RepoStatsResponse",+ "RepoSummaryRow","RepoUpdate",+ "ReposSummaryResponse","ReviewerEntry","ReviewerSuggestion","ReviewerSuggestionsResponse",diff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.pyindex a9f79d445..3f816da8a 100644--- a/packages/server/src/repowise/server/schemas/repository.py+++ b/packages/server/src/repowise/server/schemas/repository.py@@ -87,3 +87,55 @@ class RepoResponse(BaseModel):created_at=obj.created_at, # type: ignore[attr-defined]updated_at=obj.updated_at, # type: ignore[attr-defined])+++class RepoSummaryRow(BaseModel):+ """One repository's headline figures, for the multi-repo dashboard.++ Every count here is a count of the thing its name says. ``file_count`` in+ particular is file nodes only: ``/stats`` counts every ``graph_nodes`` row,+ which on this repo is 38,813 against 3,600 actual files, because symbol+ nodes live in the same table.+ """++ id: str+ name: str+ local_path: str+ updated_at: datetime | None = None+ #: "indexed" | "needs_index" | "missing_dir" — same vocabulary as+ #: ``RepoResponse.workspace_status``, which the sidebar already renders.+ status: str = "indexed"++ file_count: int = 0+ symbol_count: int = 0+ entry_point_count: int = 0++ #: Documentation pages, and how many of them are still fresh. Both counts+ #: ship rather than a percentage so a caller can print "3,797 of 4,059"+ #: and the ratio without the two disagreeing.+ doc_page_count: int = 0+ doc_fresh_page_count: int = 0++ dead_export_count: int = 0++ #: Files carrying git history, and the hotspot subset. The denominator is+ #: here because hotspots are only meaningful against it.+ tracked_file_count: int = 0+ hotspot_count: int = 0++ #: Latest health snapshot. ``None`` when the repo has never been analysed —+ #: distinct from a score of 0, which would mean "analysed, and terrible".+ average_health: float | None = None+ hotspot_health: float | None = None+ health_taken_at: datetime | None = None++ #: Index-vs-checkout freshness. ``index_behind`` is ``None`` when the+ #: comparison could not run (no git checkout on disk, unreadable HEAD)+ #: rather than ``False``, so "current" and "unknown" stay separable.+ indexed_commit: str | None = None+ live_head: str | None = None+ index_behind: bool | None = None+++class ReposSummaryResponse(BaseModel):+ repos: list[RepoSummaryRow]diff --git a/packages/types/package.json b/packages/types/package.jsonindex 03d28a26a..470cd8fd5 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -25,6 +25,7 @@"./owners": "./src/owners.ts","./modules": "./src/modules.ts","./overview": "./src/overview.ts",+ "./repos": "./src/repos.ts","./files": "./src/files.ts","./external-systems": "./src/external-systems.ts","./health": "./src/health.ts",diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 13cb871df..82b979e5d 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -25,6 +25,7 @@ export * from "./security.js";export * from "./owners.js";export * from "./modules.js";export * from "./overview.js";+export * from "./repos.js";export * from "./files.js";export * from "./external-systems.js";export * from "./health.js";diff --git a/packages/types/src/repos.ts b/packages/types/src/repos.tsnew file mode 100644index 000000000..e90b9c0ff--- /dev/null+++ b/packages/types/src/repos.ts@@ -0,0 +1,55 @@+/**+ * Repo-summary contract — the one-call payload behind the multi-repo+ * dashboard (`GET /api/repos/summary`). Mirrors the server's+ * `schemas/repository.py` response shape.+ */++/** Whether a registered repo has an index behind it yet. Same vocabulary as+ * `RepoResponse.workspace_status`, which the sidebar already renders. */+export type RepoIndexStatus = "indexed" | "needs_index" | "missing_dir";++export interface RepoSummaryRow {+ id: string;+ name: string;+ local_path: string;+ updated_at: string | null;+ status: RepoIndexStatus;++ /** File nodes only. `/api/repos/{id}/stats` counts every `graph_nodes` row+ * under this name, symbols included, which over-reports by roughly 10x. */+ file_count: number;+ symbol_count: number;+ entry_point_count: number;++ /** Documentation pages, and how many are still fresh. Both counts ship+ * rather than a percentage, so a surface can print "3,797 of 4,059" and+ * the ratio without the two disagreeing. */+ doc_page_count: number;+ doc_fresh_page_count: number;++ /** Open `unused_export` findings. Acknowledged and resolved ones are out,+ * and so are the other dead-code kinds. */+ dead_export_count: number;++ /** Files carrying git history, and the hotspot subset of them. The+ * denominator ships because a hotspot count means nothing without it. */+ tracked_file_count: number;+ hotspot_count: number;++ /** Latest health snapshot, 0-10. `null` means never analysed — which is a+ * different thing from a score of 0, and must not render as one. */+ average_health: number | null;+ hotspot_health: number | null;+ health_taken_at: string | null;++ /** Index-vs-checkout freshness. `index_behind` is `null` when the+ * comparison could not run (no git checkout, unreadable HEAD) rather than+ * `false`, so "current" and "unknown" stay separable. */+ indexed_commit: string | null;+ live_head: string | null;+ index_behind: boolean | null;+}++export interface ReposSummaryResponse {+ repos: RepoSummaryRow[];+}diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.pyindex 8da8c16d1..9eeca944b 100644--- a/tests/unit/server/mcp/test_meta_freshness.py+++ b/tests/unit/server/mcp/test_meta_freshness.py@@ -45,7 +45,7 @@ def _prime(tmp_path, changed: frozenset[str] | None):def test_head_match_is_silent(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _INDEXED)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _INDEXED)out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])assert "stale_warning" not in outassert out["index_behind"] is False@@ -58,13 +58,13 @@ def test_no_git_signal_omits_index_behind_entirely(tmp_path, monkeypatch):Without a live HEAD the comparison never runs, so claiming ``false`` herewould report a repo as verified-current on no evidence at all."""- monkeypatch.setattr(_meta, "_read_live_head", lambda p: None)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: None)out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])assert "index_behind" not in outdef test_served_target_changed_warns(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset({"src/a.py"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])assert "stale_warning" in out@@ -73,7 +73,7 @@ def test_served_target_changed_warns(tmp_path, monkeypatch):def test_unaffected_targets_get_index_behind_not_warning(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset({"docs/README.md"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])assert "stale_warning" not in out@@ -82,13 +82,13 @@ def test_unaffected_targets_get_index_behind_not_warning(tmp_path, monkeypatch):def test_no_targets_keeps_repo_level_warning(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)assert "stale_warning" in outdef test_empty_targets_means_nothing_served_and_never_warns(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset({"src/a.py"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=[])assert "stale_warning" not in out@@ -104,7 +104,7 @@ def test_no_targets_with_zero_changed_files_does_not_warn(tmp_path, monkeypatch)A warning that fires when zero files changed is the loudest possible way tobe wrong, and it trains an agent to stop reading the field."""- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset())out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)assert "stale_warning" not in out@@ -114,7 +114,7 @@ def test_no_targets_with_zero_changed_files_does_not_warn(tmp_path, monkeypatch)def test_no_targets_with_real_changes_still_warns(tmp_path, monkeypatch):"""The zero-change carve-out must not silence a genuinely behind index."""- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset({"src/a.py"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)assert "stale_warning" in out@@ -156,7 +156,7 @@ def test_empty_commit_over_real_git_is_not_stale(tmp_path):def test_git_diff_failure_falls_back_to_repo_level_warning(tmp_path, monkeypatch):- monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)+ monkeypatch.setattr(_meta, "read_live_head", lambda p: _LIVE)_prime(tmp_path, None) # git couldn't answer (rebased-away SHA, timeout)out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])assert "stale_warning" in outdiff --git a/tests/unit/server/test_repos.py b/tests/unit/server/test_repos.pyindex ca2b3a633..63ddaf4b9 100644--- a/tests/unit/server/test_repos.py+++ b/tests/unit/server/test_repos.py@@ -201,3 +201,40 @@ async def test_export_wiki_returns_zip(client: AsyncClient, session) -> None:assert len(names) == 1assert names[0].startswith("wiki/")assert names[0].endswith(".md")+++async def test_stats_file_count_excludes_symbol_nodes(client: AsyncClient, session) -> None:+ """`file_count` must count files, not every `graph_nodes` row.++ Symbol nodes share the table. Counting them made the field report ~10x+ the real figure, which both the multi-repo dashboard and the chat empty+ state printed verbatim as "N files".+ """+ from repowise.core.persistence.crud import upsert_repository+ from repowise.core.persistence.models import GraphNode++ repo = await upsert_repository(session, name="counts", local_path="/tmp/counts")+ for i in range(2):+ session.add(+ GraphNode(+ repository_id=repo.id,+ node_id=f"src/mod{i}.py",+ node_type="file",+ symbol_count=5,+ )+ )+ for j in range(5):+ session.add(+ GraphNode(+ repository_id=repo.id,+ node_id=f"src/mod{i}.py::sym{j}",+ node_type="symbol",+ )+ )+ await session.commit()++ data = (await client.get(f"/api/repos/{repo.id}/stats")).json()++ assert data["file_count"] == 2 # not 12+ assert data["symbol_count"] == 10diff --git a/tests/unit/server/test_repos_summary.py b/tests/unit/server/test_repos_summary.pynew file mode 100644index 000000000..cae38b66b--- /dev/null+++ b/tests/unit/server/test_repos_summary.py@@ -0,0 +1,267 @@+"""Tests for GET /api/repos/summary — the multi-repo dashboard payload.++The two properties worth pinning are that the figures are counts of what+their names say, and that the query count does not grow with the number of+repositories. The route exists because the shape it replaces did both wrong.+"""++from __future__ import annotations++import tempfile+from datetime import UTC, datetime, timedelta+from pathlib import Path++import pytest+from httpx import AsyncClient+from sqlalchemy import event++from repowise.core.persistence.crud import upsert_page+from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphNode,+ HealthSnapshot,+)+from tests.unit.persistence.helpers import make_page_kwargs+++async def _register(client: AsyncClient, name: str) -> dict:+ """Register a repo against a real temp dir (the create route validates it)."""+ repo_dir = Path(tempfile.mkdtemp()) / name+ repo_dir.mkdir()+ (repo_dir / ".git").mkdir()+ resp = await client.post(+ "/api/repos",+ json={"index": False, "name": name, "local_path": str(repo_dir), "url": ""},+ )+ assert resp.status_code == 201+ return resp.json()+++async def _seed(session, repo_id: str, *, files: int, symbols_per_file: int = 3) -> None:+ """Give a repo one of everything the summary counts."""+ for i in range(files):+ session.add(+ GraphNode(+ repository_id=repo_id,+ node_id=f"src/mod{i}.py",+ node_type="file",+ symbol_count=symbols_per_file,+ is_entry_point=(i == 0),+ )+ )+ # Symbol nodes share the table with file nodes. They are what makes the+ # unscoped count wrong, so every fixture carries some.+ for j in range(symbols_per_file):+ session.add(+ GraphNode(+ repository_id=repo_id,+ node_id=f"src/mod{i}.py::sym{j}",+ node_type="symbol",+ symbol_count=0,+ )+ )+ session.add(+ GitMetadata(+ repository_id=repo_id,+ file_path=f"src/mod{i}.py",+ is_hotspot=(i == 0),+ )+ )+ await upsert_page(+ session,+ **make_page_kwargs(+ repo_id,+ page_id=f"file_page:src/mod{i}.py",+ target_path=f"src/mod{i}.py",+ title=f"mod{i}",+ freshness_status="fresh" if i == 0 else "stale",+ ),+ )+ session.add(+ DeadCodeFinding(+ repository_id=repo_id,+ kind="unused_export",+ file_path="src/mod0.py",+ status="open",+ )+ )+ # Should not be counted: a resolved export, and an open finding of another kind.+ session.add(+ DeadCodeFinding(+ repository_id=repo_id,+ kind="unused_export",+ file_path="src/mod0.py",+ symbol_name="already_gone",+ status="resolved",+ )+ )+ session.add(+ DeadCodeFinding(+ repository_id=repo_id,+ kind="unreachable_file",+ file_path="src/orphan.py",+ status="open",+ )+ )+ await session.commit()+++async def test_summary_is_not_shadowed_by_the_repo_id_route(client: AsyncClient) -> None:+ """`/summary` must be declared before `/{repo_id}`.++ Declared after it, FastAPI matches `get_repo(repo_id="summary")` and the+ route answers 404 "Repository not found" — with nothing else failing.+ """+ resp = await client.get("/api/repos/summary")+ assert resp.status_code == 200+ assert resp.json() == {"repos": []}+++async def test_file_count_excludes_symbol_nodes(client: AsyncClient, session) -> None:+ """The count has to be counting the thing the noun names.++ `/stats` counts every `graph_nodes` row as a file; on this codebase that+ reports 38,813 files against 3,600 real ones.+ """+ repo = await _register(client, "counted")+ await _seed(session, repo["id"], files=4, symbols_per_file=3)++ resp = await client.get("/api/repos/summary")+ assert resp.status_code == 200+ row = resp.json()["repos"][0]++ assert row["file_count"] == 4 # not 16+ assert row["symbol_count"] == 12+ assert row["entry_point_count"] == 1+++async def test_summary_reports_each_figure(client: AsyncClient, session) -> None:+ repo = await _register(client, "figures")+ await _seed(session, repo["id"], files=3)+ session.add(+ HealthSnapshot(+ repository_id=repo["id"],+ taken_at=datetime.now(UTC),+ average_health=7.43,+ hotspot_health=4.62,+ )+ )+ await session.commit()++ row = (await client.get("/api/repos/summary")).json()["repos"][0]++ assert row["id"] == repo["id"]+ assert row["name"] == "figures"+ assert row["doc_page_count"] == 3+ assert row["doc_fresh_page_count"] == 1+ assert row["dead_export_count"] == 1 # open unused_export only+ assert row["tracked_file_count"] == 3+ assert row["hotspot_count"] == 1+ assert row["average_health"] == 7.43+ assert row["hotspot_health"] == 4.62+++async def test_health_uses_the_latest_snapshot(client: AsyncClient, session) -> None:+ repo = await _register(client, "trending")+ now = datetime.now(UTC)+ for offset, score in ((2, 5.0), (0, 8.5), (1, 6.0)):+ session.add(+ HealthSnapshot(+ repository_id=repo["id"],+ taken_at=now - timedelta(hours=offset),+ average_health=score,+ hotspot_health=score,+ )+ )+ await session.commit()++ row = (await client.get("/api/repos/summary")).json()["repos"][0]+ assert row["average_health"] == 8.5+++async def test_never_analysed_repo_reports_null_health_not_zero(+ client: AsyncClient,+) -> None:+ """A missing score and a bad score must not render the same.++ Zero would read as "analysed, and terrible" on a dashboard row.+ """+ await _register(client, "fresh-registration")++ row = (await client.get("/api/repos/summary")).json()["repos"][0]++ assert row["average_health"] is None+ assert row["hotspot_health"] is None+ assert row["file_count"] == 0+ assert row["doc_page_count"] == 0+++async def test_figures_are_grouped_per_repo(client: AsyncClient, session) -> None:+ """One repo's rows must not leak into another's counts."""+ big = await _register(client, "big")+ small = await _register(client, "small")+ await _seed(session, big["id"], files=5)+ await _seed(session, small["id"], files=2)++ rows = {r["name"]: r for r in (await client.get("/api/repos/summary")).json()["repos"]}++ assert rows["big"]["file_count"] == 5+ assert rows["small"]["file_count"] == 2+ assert rows["big"]["tracked_file_count"] == 5+ assert rows["small"]["tracked_file_count"] == 2+++async def test_query_count_does_not_grow_with_repo_count(+ client: AsyncClient, session, test_engine+) -> None:+ """The whole point of the route.++ The shape it replaces issued six `/stats` queries plus a full+ `git_metadata` hydration *per repository*, across two sequential request+ waves. Grouped aggregates make the cost flat, and this is the only test+ that would notice a future edit reintroducing a per-repo query.+ """+ for i in range(2):+ repo = await _register(client, f"repo{i}")+ await _seed(session, repo["id"], files=3)++ statements: list[str] = []++ def record(conn, cursor, statement, parameters, context, executemany):+ statements.append(statement)++ event.listen(test_engine.sync_engine, "before_cursor_execute", record)+ try:+ two_repos = len(await _count_queries(client, statements))+ statements.clear()+ for i in range(2, 6):+ repo = await _register(client, f"repo{i}")+ await _seed(session, repo["id"], files=3)+ statements.clear()+ six_repos = len(await _count_queries(client, statements))+ finally:+ event.remove(test_engine.sync_engine, "before_cursor_execute", record)++ assert six_repos == two_repos, (+ f"query count grew from {two_repos} (2 repos) to {six_repos} (6 repos) — "+ "something in the route is running per repository again"+ )+ # One repo list plus five grouped aggregates. Pinned so "flat" has a value:+ # a change that merges or splits an aggregate should be a deliberate edit+ # here, not a silent drift.+ assert six_repos == 6+++async def _count_queries(client: AsyncClient, statements: list[str]) -> list[str]:+ statements.clear()+ resp = await client.get("/api/repos/summary")+ assert resp.status_code == 200+ return list(statements)