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(overview): merge every detector into one attention list (#2429)
Raghav Chamadiyad8309144619e
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.pyindex 9b9440b83..75be45858 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py@@ -163,8 +163,16 @@ async def get_dead_code_findings(kind: str | None = None,min_confidence: float = 0.0,status: str = "open",+ safe_to_delete: bool | None = None,+ limit: int | None = None,) -> list[DeadCodeFinding]:- """Return dead code findings filtered by kind, confidence, and status."""+ """Return dead code findings filtered by kind, confidence, and status.++ ``safe_to_delete`` and ``limit`` exist so a caller that wants a short+ preview does not have to load every open finding in the repository and+ then throw most of them away in Python. Overview does exactly that for a+ five-row list.+ """q = select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repository_id,DeadCodeFinding.status == status,@@ -172,7 +180,11 @@ async def get_dead_code_findings()if kind is not None:q = q.where(DeadCodeFinding.kind == kind)+ if safe_to_delete is not None:+ q = q.where(DeadCodeFinding.safe_to_delete.is_(safe_to_delete))q = q.order_by(DeadCodeFinding.confidence.desc())+ if limit is not None:+ q = q.limit(limit)result = await session.execute(q)return list(result.scalars().all())diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex fe2714cdf..ab0ed5682 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -9,6 +9,7 @@ decisions slice, savings headline, and health KPIs.from __future__ import annotations+import asyncioimport configparserimport contextlibimport json@@ -33,7 +34,11 @@ from repowise.core.persistence.models import ()from repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.routers.git import _hotspot_from_row-from repowise.server.services.knowledge_map import compute_knowledge_map+from repowise.server.services.attention import build_attention+from repowise.server.services.knowledge_map import (+ compute_knowledge_silos,+ compute_onboarding_targets,+)from repowise.server.services.module_health import top_level_modulerouter = APIRouter(@@ -47,7 +52,7 @@ router = APIRouter(HEALTH_HISTORY_POINTS = 12-def _index_storage_bytes(repowise_dir: Path) -> int:+def _walk_index_storage_bytes(repowise_dir: Path) -> int:"""Total on-disk size of a repo's ``.repowise/`` directory."""if not repowise_dir.is_dir():return 0@@ -59,6 +64,22 @@ def _index_storage_bytes(repowise_dir: Path) -> int:return total+async def _index_storage_bytes(repowise_dir: Path) -> int:+ """``_walk_index_storage_bytes`` off the event loop.++ The walk is a full recursive stat of a directory that holds the vectors,+ the wiki and the symbol store, so it is routinely hundreds of megabytes and+ tens of thousands of files. Run inline in an ``async def`` it does not just+ make this request slow: it blocks the worker's event loop for its whole+ duration, stalling every other request in flight.++ Ceiling: a thread is the cheap fix, and the walk still happens once per+ page load. The real fix is to stamp the size when the index is written and+ read the number back; do that if this ever shows up in a profile again.+ """+ return await asyncio.to_thread(_walk_index_storage_bytes, repowise_dir)++def _remote_url(stored_url: str | None, local_path: str | None) -> str | None:"""Best-effort git remote for a repo.@@ -166,75 +187,6 @@ async def _savings_headline(repo_local_path: str | None) -> dict:}-def _build_attention_items(- decision_health: dict,- knowledge_silos: list[dict],- dead_safe: list[Any],-) -> list[dict]:- """Flat, severity-tagged attention list — the server-side twin of the- AttentionPanel item builder that used to live in the overview page."""- items: list[dict] = []- for d in decision_health.get("stale_decisions", []):- items.append(- {- "id": f"stale-{d.id}",- "type": "stale_decision",- "title": d.title,- "description": "Active decision drifting from the code it governs",- "severity": "high",- "target_id": d.id,- }- )- for d in decision_health.get("proposed_awaiting_review", []):- items.append(- {- "id": f"proposed-{d.id}",- "type": "proposed_decision",- "title": d.title,- "description": "Auto-proposed decision awaiting review",- "severity": "medium",- "target_id": d.id,- }- )- for fp in decision_health.get("ungoverned_hotspots", [])[:10]:- items.append(- {- "id": f"ungoverned-{fp}",- "type": "ungoverned_hotspot",- "title": fp,- "description": "High-churn file with no governing decision",- "severity": "medium",- "target_id": fp,- }- )- for s in knowledge_silos[:10]:- items.append(- {- "id": f"silo-{s['file_path']}",- "type": "knowledge_silo",- "title": s["file_path"],- "description": (f"{round(s['owner_pct'] * 100)}% single-owner concentration"),- "severity": "medium",- "target_id": s["file_path"],- }- )- for f in dead_safe[:10]:- label = f.symbol_name or f.file_path- items.append(- {- "id": f"dead-{f.id}",- "type": "dead_code",- "title": label,- "description": f"Safe to delete ({f.lines} lines)",- "severity": "low",- "target_id": f.file_path,- }- )- severity_rank = {"high": 0, "medium": 1, "low": 2}- items.sort(key=lambda i: severity_rank.get(i["severity"], 3))- return items--@router.get("/{repo_id}/overview-summary")async def overview_summary(repo_id: str,@@ -465,15 +417,24 @@ async def overview_summary(# --- Attention items + onboarding targets -----------------------------decision_health = await crud.get_decision_health_summary(session, repo_id)- knowledge = await compute_knowledge_map(session, repo_id)- dead_safe = [- f- for f in await crud.get_dead_code_findings(session, repo_id, status="open")- if f.safe_to_delete- ]- attention = _build_attention_items(- decision_health, knowledge.get("knowledge_silos", []), dead_safe+ # Silos only. The full knowledge map also computes top owners and+ # onboarding targets, and paying for those here meant loading the content+ # of every generated page to count its words for a list this page does not+ # render.+ knowledge_silos = await compute_knowledge_silos(session, repo_id)+ # Read by the first-index experience. Its own call rather than the full+ # knowledge map, which would also aggregate owners this payload never uses.+ onboarding_targets = await compute_onboarding_targets(session, repo_id)+ # Every finding store, merged and ranked worst-first. This used to read+ # three stores and rank them by which store they came from; see+ # `services/attention.py` for what changed and why.+ attention_result = await build_attention(+ session,+ repo_id,+ decision_health=decision_health,+ knowledge_silos=knowledge_silos,)+ attention = attention_result["items"]# --- Top hotspots + recent decisions slices ---------------------------hotspot_rows = (@@ -577,6 +538,13 @@ async def overview_summary("hotspot_count": hotspot_count,"silo_count": silo_count,"module_count": module_count,+ # Summed from the health metrics already loaded above, so it costs+ # nothing. It is here because Overview's only use for the whole+ # Stats "By the Numbers" endpoint was this one figure, and that+ # endpoint runs its own commit-history pass; its docstring says it+ # is scoped for its own page. Matches the field hosted's backend+ # already serves.+ "total_nloc": sum(int(m.nloc or 0) for m in health_metrics),"deltas": deltas,},"health": {@@ -607,7 +575,15 @@ async def overview_summary(},"languages": languages,"attention": attention,- "onboarding_targets": knowledge.get("onboarding_targets", []),+ # Counts for everything the sources hold, beside the capped list. The+ # page shows five rows out of these, and "5 open" would be a lie that+ # gets worse the more findings a repository has.+ "attention_summary": {+ "total": attention_result["total"],+ "by_source": attention_result["by_source"],+ "areas": attention_result["areas"],+ },+ "onboarding_targets": onboarding_targets,"top_hotspots": top_hotspots,"recent_decisions": recent_decisions,"savings": savings,@@ -617,6 +593,6 @@ async def overview_summary("last_sync_model": last_sync_model,"active_job_id": active_job_id,"page_count": total_pages,- "index_storage_bytes": _index_storage_bytes(repowise_dir),+ "index_storage_bytes": await _index_storage_bytes(repowise_dir),},}diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.pynew file mode 100644index 000000000..0fc9f500a--- /dev/null+++ b/packages/server/src/repowise/server/services/attention.py@@ -0,0 +1,722 @@+"""One ranked attention list for the repo Overview.++Overview's "Needs attention" used to be built from three stores — decision+health, knowledge silos, dead code — because those were the three that existed+when it was written. Everything added since (code-health findings and the+test-quality biomarkers that ride in them, security findings, documentation+drift) lives on a tab and never reaches the page whose job is to say where to+look. This module is the merge.++Two rules it follows, because they are what the old builder got wrong:++**Severity is the finding's own, never the source's.** The old list assigned a+severity per source — every dead-code row was ``low``, every proposed decision+``medium`` — so the ranking encoded "which store did this come from" and read+as if it encoded danger. Stores that publish a severity are passed through+unchanged here. Stores that genuinely do not have one (dead code and drift+carry a confidence float and nothing else) get a documented bucketing rather+than a per-source constant.++**A count travels with what it covers.** Each source is capped so no single+store floods the list, so the caller cannot infer a total by taking ``len()``.+:func:`build_attention` returns the totals beside the items.++The ladder is the four-level ``Severity`` from+``repowise.core.analysis.health.models``, the only severity vocabulary in the+codebase with parity tests against its TypeScript twin. The three-level ladder+the old ``AttentionItem`` declared is a subset of it.+"""++from __future__ import annotations++from typing import Any++from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.health.grading import HealthBand, band_for+from repowise.core.persistence.models import (+ DeadCodeFinding,+ DocDriftFinding,+ HealthFileMetric,+ HealthFinding,+ RefactoringSuggestion,+ SecurityFinding,+)++#: Worst first. Mirrors ``core.analysis.health.models.Severity``.+SEVERITY_RANK: dict[str, int] = {"critical": 0, "high": 1, "medium": 2, "low": 3}++#: Tie-break within one severity. The ordering is a claim about kind, not about+#: importance: a secret in the tree and a file the scanner scored are statements+#: about the code being wrong, a decision record drifting is a statement about+#: the documentation of the code, and dead code is untidiness. When two items+#: are equally severe, the one that says something is *wrong* goes first.+SOURCE_RANK: dict[str, int] = {+ "security_finding": 0,+ "health_finding": 1,+ "refactoring": 2,+ "stale_decision": 3,+ "ungoverned_hotspot": 4,+ "doc_drift": 5,+ "proposed_decision": 6,+ "knowledge_silo": 7,+ "dead_code": 8,+}++#: Per-source ceilings. Deliberately larger than the five rows Overview shows:+#: the global sort has to be able to rank a critical finding above a wall of+#: medium ones, which it cannot do if each source arrives pre-truncated to the+#: display length.+PER_SOURCE_CAP = 8++#: How much an item matters *within* its own source, for breaking ties inside a+#: severity band. Comparable only against its own kind — a health finding's+#: impact and a drift finding's confidence are not the same quantity — which is+#: all the tie-break needs, since `SOURCE_RANK` has already separated sources.+#:+#: Without it the tie-break fell through to the item id, so the lead of an area+#: was whichever member of its worst band sorted first alphabetically. Health+#: fetches in `health_impact DESC` and the rank pass then discarded that order.+WEIGHT_KEY = "weight"++#: Above this, a drift finding is confident enough to be worth a person's+#: attention rather than a glance. `DocDriftFinding` has no severity column, so+#: this bucketing is ours; it is set here rather than inline so the two places+#: that care (this list and the drift tab's own summary) can converge later.+DRIFT_CONFIDENT = 0.8+++def _test_paths(repo_id: str):+ """Sub-select of this repository's test files.++ Production scope, which the Code Health page already offers as a control+ and this list was missing. A test file cannot be the most urgent thing in+ a repository: it has no users, a defect in it fails a build rather than a+ customer, and `tests/` is usually the largest directory in the tree, so+ without this the top of the list fills with test files and the section+ stops being about the product.++ Reads the `is_test` column the health pass already stamps, rather than+ re-deriving it from the path here and disagreeing with the page that shows+ the same files.+ """+ return select(HealthFileMetric.file_path).where(+ HealthFileMetric.repository_id == repo_id,+ HealthFileMetric.is_test.is_(True),+ )+++#: The five health bands against this list's four severities. `excellent` and+#: `good` both mean "not a problem" here; the list has no band above `low`.+_SEVERITY_OF_BAND: dict[HealthBand, str] = {+ "at_risk": "critical",+ "needs_work": "high",+ "fair": "medium",+ "good": "low",+ "excellent": "low",+}+++def _severity_of_file_score(score: float) -> str:+ """A file's own band, expressed as a severity.++ The health item is a file, so its severity has to describe the file. Taking+ the worst *finding's* severity instead inverted the ranking: a file with one+ finding on the per-finding cap (score 7.5, comfortably fair) called itself+ critical and outranked a file carrying thirty-eight findings and twelve+ points of deduction (score 1.0, genuinely at risk).++ `band_for` is the single source of truth for the cutoffs and is called, not+ reimplemented. A recalibration there has to reach this list, or the same+ file is `at risk` on the health pages and `medium` here.+ """+ return _SEVERITY_OF_BAND[band_for(score)]+++def _severity_of_drift(confidence: float | None) -> str:+ """Bucket a drift confidence onto the shared ladder.++ Never returns ``high``. A document that misdescribes the tree is worth+ fixing and is not the same class of problem as a credential in git or a+ file the health pass scored critical, and letting drift reach the top band+ would push those off a five-row list.+ """+ return "medium" if (confidence or 0.0) >= DRIFT_CONFIDENT else "low"+++async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:+ """Open code-health findings, aggregated to the file, worst file first.++ A file rather than a finding, because `health_impact` saturates. The cap is+ 2.50 and several criticals sit exactly on it, so ranking findings against+ each other decides the top of the list on a tie-break rather than on the+ metric — it surfaced one `nested_complexity` finding ahead of a file+ carrying thirty-eight findings and twelve points of deduction. Summed+ impact is the file's whole score (a file scores `10 - sum`), so this ranks+ on the number the product already stands behind.++ This is also what puts the test-quality work on the page: mock saturation,+ assertion-free tests, untested hotspots and coverage gaps are+ `biomarker_type` values inside `health_findings` rather than stores of+ their own, so they arrive here without a special case.++ `total` stays a count of findings, not of files. The row says how much the+ area holds; the lead says where to start.+ """+ scoped = (+ HealthFinding.repository_id == repo_id,+ HealthFinding.status == "open",+ HealthFinding.file_path.not_in(_test_paths(repo_id)),+ )+ rows = (+ await session.execute(+ select(+ HealthFinding.file_path,+ func.sum(HealthFinding.health_impact).label("impact"),+ func.count(HealthFinding.id).label("findings"),+ )+ .where(*scoped)+ .group_by(HealthFinding.file_path)+ .order_by(func.sum(HealthFinding.health_impact).desc())+ .limit(PER_SOURCE_CAP)+ )+ ).all()+ total = await session.scalar(select(func.count(HealthFinding.id)).where(*scoped)) or 0+ if not rows:+ return [], int(total), ""++ # The biomarker to name each file by: its own heaviest one. Bounded to the+ # handful of files above, so this is a keyed read rather than a scan.+ paths = [r.file_path for r in rows]+ lead_biomarker: dict[str, str] = {}+ for path, biomarker in (+ await session.execute(+ select(HealthFinding.file_path, HealthFinding.biomarker_type)+ .where(*scoped, HealthFinding.file_path.in_(paths))+ .order_by(HealthFinding.health_impact.desc())+ )+ ).all():+ lead_biomarker.setdefault(path, biomarker)++ items = [+ {+ "id": f"health-{row.file_path}",+ "type": "health_finding",+ "title": row.file_path,+ "description": (+ f"{row.findings} finding{'' if row.findings == 1 else 's'}"+ f" · {float(row.impact or 0.0):.1f} deducted"+ ),+ "severity": _severity_of_file_score(+ max(1.0, 10.0 - float(row.impact or 0.0))+ ),+ "target_id": row.file_path,+ # The UI resolves this through the biomarker glossary it owns, so+ # this module holds no second copy of that vocabulary.+ "subtype": lead_biomarker.get(row.file_path),+ "weight": float(row.impact or 0.0),+ }+ for row in rows+ ]+ return items, int(total), ""+++async def _security_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:+ """Security findings, high severity first.++ ``SecurityFinding`` has no status column: rows are replaced wholesale by+ each scan, so every stored row is open by construction and there is nothing+ to filter on. It also only ever writes ``high`` or ``low`` — the router's+ docstring mentions a ``med`` that the scanner never emits — so the two+ middle bands of the ladder are simply unused here.+ """+ rows = (+ (+ await session.execute(+ select(SecurityFinding)+ .where(SecurityFinding.repository_id == repo_id)+ .order_by(+ # `high` before anything else, then newest. Expressed as a+ # sort key rather than two queries.+ (SecurityFinding.severity != "high"),+ SecurityFinding.detected_at.desc(),+ )+ .limit(PER_SOURCE_CAP)+ )+ )+ .scalars()+ .all()+ )+ total = (+ await session.scalar(+ select(func.count(SecurityFinding.id)).where(+ SecurityFinding.repository_id == repo_id+ )+ )+ or 0+ )+ # A secret in the working tree and one only reachable through git history+ # are different jobs — one is a deletion, the other a rotation and a+ # rewrite — and 245 findings reads as an emergency until the split says+ # most of them are historical.+ in_tree = (+ await session.scalar(+ select(func.count(SecurityFinding.id)).where(+ SecurityFinding.repository_id == repo_id,+ SecurityFinding.commit_sha == "",+ )+ )+ or 0+ )+ items = [+ {+ "id": f"security-{row.id}",+ "type": "security_finding",+ "title": row.file_path,+ "description": (+ f"{row.kind}{f' in commit {row.commit_sha[:7]}' if row.commit_sha else ''}"+ ),+ "severity": row.severity if row.severity in SEVERITY_RANK else "medium",+ "target_id": row.file_path,+ "subtype": row.kind,+ # Nothing separates two `high` secrets but recency, and a secret+ # still sitting in the tree outranks one only git remembers.+ "weight": 1.0 if not row.commit_sha else 0.0,+ }+ for row in rows+ ]+ return items, int(total), (+ f"{in_tree} in the working tree, {int(total) - in_tree} in git history"+ if total+ else ""+ )+++async def _drift_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:+ """Documentation drift, most confident first.++ ``file_path`` on this row is the *document* making the false claim, not the+ code it is wrong about, which is why the row links to the drift tab rather+ than to a file page.+ """+ rows = (+ (+ await session.execute(+ select(DocDriftFinding)+ .where(DocDriftFinding.repository_id == repo_id)+ .order_by(DocDriftFinding.confidence.desc())+ .limit(PER_SOURCE_CAP)+ )+ )+ .scalars()+ .all()+ )+ total = (+ await session.scalar(+ select(func.count(DocDriftFinding.id)).where(+ DocDriftFinding.repository_id == repo_id+ )+ )+ or 0+ )+ items = [+ {+ "id": f"drift-{row.id}",+ "type": "doc_drift",+ "title": row.file_path,+ "description": row.reason or f"{row.kind} no longer matches the tree",+ "severity": _severity_of_drift(row.confidence),+ "target_id": row.file_path,+ "subtype": row.kind,+ "weight": float(row.confidence or 0.0),+ }+ for row in rows+ ]+ return items, int(total), ""+++async def _refactoring_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:+ """Open refactoring plans, biggest recovered health first.++ The one store on this list that holds *work* rather than observations: a+ row is a plan with an impact estimate and an effort bucket, so it is the+ only source where "what should I do about it" is already answered.++ Severity is derived from the impact it recovers, because the store has no+ severity column and an opportunity is not a defect. It is capped at+ ``medium``: a thing you could improve never outranks a thing that is+ wrong.+ """+ rows = (+ (+ await session.execute(+ select(RefactoringSuggestion)+ .where(+ RefactoringSuggestion.repository_id == repo_id,+ RefactoringSuggestion.status == "open",+ RefactoringSuggestion.file_path.not_in(_test_paths(repo_id)),+ )+ .order_by(RefactoringSuggestion.impact_delta.desc())+ .limit(PER_SOURCE_CAP)+ )+ )+ .scalars()+ .all()+ )+ total = (+ await session.scalar(+ select(func.count(RefactoringSuggestion.id)).where(+ RefactoringSuggestion.repository_id == repo_id,+ RefactoringSuggestion.status == "open",+ RefactoringSuggestion.file_path.not_in(_test_paths(repo_id)),+ )+ )+ or 0+ )+ items = [+ {+ "id": f"refactor-{row.id}",+ "type": "refactoring",+ "title": row.target_symbol or row.file_path,+ "description": (+ f"+{row.impact_delta:.1f} health"+ f"{f', {row.effort_bucket} effort' if row.effort_bucket else ''}"+ f" · {row.file_path}"+ ),+ "severity": "medium" if (row.impact_delta or 0.0) >= 1.0 else "low",+ "target_id": row.file_path,+ "subtype": row.refactoring_type,+ "weight": float(row.impact_delta or 0.0),+ }+ for row in rows+ ]+ return items, int(total), ""+++async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:+ """Safe-to-delete dead code, most confident first.++ Stays in the bottom band whatever its confidence. Confidence here measures+ how sure the graph is that nothing reaches the symbol, not how much it+ costs to leave it there, and a high-confidence unused export is still the+ least urgent thing this list can show.+ """+ rows = (+ (+ await session.execute(+ select(DeadCodeFinding)+ .where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.safe_to_delete.is_(True),+ DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),+ )+ .order_by(DeadCodeFinding.confidence.desc())+ .limit(PER_SOURCE_CAP)+ )+ )+ .scalars()+ .all()+ )+ total = (+ await session.scalar(+ select(func.count(DeadCodeFinding.id)).where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.safe_to_delete.is_(True),+ DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),+ )+ )+ or 0+ )+ items = [+ {+ "id": f"dead-{row.id}",+ "type": "dead_code",+ "title": row.symbol_name or row.file_path,+ "description": f"Unreachable {row.symbol_kind or 'symbol'} ({row.lines} lines)",+ "severity": "low",+ "target_id": row.file_path,+ "subtype": row.kind,+ "weight": float(row.confidence or 0.0),+ }+ for row in rows+ ]+ return items, int(total), ""+++def _decision_items(decision_health: dict) -> tuple[list[dict], int, str]:+ """Decision-record problems, in the order the summary already ranked them.++ ``get_decision_health_summary`` sorts stale records by staleness, proposed+ by confidence and ungoverned hotspots by hotspot score, and its docstring+ asks callers to truncate rather than re-sort. Truncation only.+ """+ items: list[dict] = []+ stale = decision_health.get("stale_decisions", []) or []+ proposed = decision_health.get("proposed_awaiting_review", []) or []+ ungoverned = decision_health.get("ungoverned_hotspots", []) or []++ # The summary already ranked each lane and asks callers not to re-sort, so+ # position becomes the weight: first in a lane outranks second.+ for rank, d in enumerate(stale[:PER_SOURCE_CAP]):+ items.append(+ {+ "weight": float(PER_SOURCE_CAP - rank),+ "id": f"stale-{d.id}",+ "type": "stale_decision",+ "title": d.title,+ "description": "Active decision drifting from the code it governs",+ "severity": "high",+ "target_id": d.id,+ }+ )+ for rank, d in enumerate(proposed[:PER_SOURCE_CAP]):+ items.append(+ {+ "weight": float(PER_SOURCE_CAP - rank),+ "id": f"proposed-{d.id}",+ "type": "proposed_decision",+ "title": d.title,+ "description": "Auto-proposed decision awaiting review",+ "severity": "medium",+ "target_id": d.id,+ }+ )+ for rank, fp in enumerate(ungoverned[:PER_SOURCE_CAP]):+ items.append(+ {+ "weight": float(PER_SOURCE_CAP - rank),+ "id": f"ungoverned-{fp}",+ "type": "ungoverned_hotspot",+ "title": fp,+ "description": "High-churn file with no governing decision",+ "severity": "medium",+ "target_id": fp,+ }+ )+ # One count over three lanes is not a fact anyone can act on. "1,064+ # decisions need attention" is mostly our own auto-proposals plus a+ # governance-coverage gap, and reporting those as one number overstates+ # the first and hides the second.+ parts = []+ if stale:+ parts.append(f"{len(stale)} drifting from the code")+ if proposed:+ parts.append(f"{len(proposed)} awaiting review")+ if ungoverned:+ parts.append(f"{len(ungoverned)} hotspots ungoverned")+ return items, len(stale) + len(proposed) + len(ungoverned), " · ".join(parts)+++def _silo_items(knowledge_silos: list[dict]) -> tuple[list[dict], int, str]:+ """Files whose history sits with one person."""+ items = [+ {+ "id": f"silo-{s['file_path']}",+ "type": "knowledge_silo",+ "title": s["file_path"],+ "description": (+ f"{round(s['owner_pct'] * 100)}% single-owner concentration"+ + (+ f", {s['commit_count_90d']} commits in 90d"+ if s.get("commit_count_90d")+ else ", not touched in 90 days"+ )+ ),+ "severity": "medium",+ "target_id": s["file_path"],+ # Sole ownership of dormant code is a fact, not a risk. Activity+ # decides which silo leads; concentration only breaks a tie.+ "weight": float(s.get("commit_count_90d") or 0) + float(s["owner_pct"]),+ }+ for s in knowledge_silos[:PER_SOURCE_CAP]+ ]+ return items, len(knowledge_silos), ""+++def _rank(items: list[dict]) -> list[dict]:+ """Worst band first, and inside a band one item per source before seconds.++ A plain severity sort is the obvious implementation and it is wrong at+ real scale. The sources are orders of magnitude apart — this repository+ holds around sixteen thousand open health findings against twenty drift+ findings — so a strict sort hands every visible row to whichever store is+ biggest, and the page silently becomes a code-health list with a+ misleading title.++ Severity still decides absolutely: every critical precedes every high, and+ a source with nothing critical does not get pulled up. The round-robin+ applies only within a band, and the buckets are walked in ``SOURCE_RANK``+ order, so the leading item of each band is still the one the tie-break+ prefers.++ Ties are broken on ``id`` before bucketing, so the order is stable across+ requests rather than following whatever order the queries returned in.+ """+ ranked: list[dict] = []+ for band in sorted({i["severity"] for i in items}, key=lambda s: SEVERITY_RANK.get(s, 99)):+ buckets: dict[str, list[dict]] = {}+ for item in sorted(+ (i for i in items if i["severity"] == band),+ key=lambda i: (+ SOURCE_RANK.get(i["type"], len(SOURCE_RANK)),+ -float(i.get(WEIGHT_KEY) or 0.0),+ i["id"],+ ),+ ):+ buckets.setdefault(item["type"], []).append(item)+ while buckets:+ for source in list(buckets):+ ranked.append(buckets[source].pop(0))+ if not buckets[source]:+ del buckets[source]+ return ranked+++#: Which item types roll up into which area row. Decisions are three lanes and+#: one destination, so they collapse; everything else is its own area.+AREA_OF: dict[str, str] = {+ "security_finding": "security",+ "health_finding": "health",+ "refactoring": "refactoring",+ "doc_drift": "doc_drift",+ "stale_decision": "decisions",+ "proposed_decision": "decisions",+ "ungoverned_hotspot": "decisions",+ "knowledge_silo": "ownership",+ "dead_code": "dead_code",+}++#: Display order for the area rows. Fixed, not data-driven: a list whose rows+#: reorder between visits cannot be scanned by position, and these are stable+#: subjects rather than a ranking.+AREA_ORDER: list[str] = [+ "security",+ "health",+ "refactoring",+ "doc_drift",+ "decisions",+ "ownership",+ "dead_code",+]+++def _areas(+ items: list[dict], by_source: dict[str, int], details: dict[str, str]+) -> list[dict]:+ """One row per area of work, each carrying its worst item as a lead.++ Ranking individual findings does not scale. With sixteen thousand open+ health findings, six rows of findings is a random sample of one store+ rather than triage, and the areas that hold less simply never appear. An+ area row is a count, a named example and a way in, which is a summary and+ a specific thing at the same time.++ Built from the already-ranked ``items`` rather than from a second set of+ queries, so an area's lead is exactly the item that topped it.+ """+ # `details` arrives keyed by SOURCE; the rows are keyed by AREA, and the+ # two only coincide for the sources whose name is also their area.+ totals: dict[str, int] = {}+ area_details: dict[str, str] = {}+ for source, count in by_source.items():+ area = AREA_OF.get(source, source)+ totals[area] = totals.get(area, 0) + count+ if details.get(source):+ area_details[area] = details[source]++ leads: dict[str, dict] = {}+ for item in items: # already ranked worst-first+ leads.setdefault(AREA_OF.get(item["type"], item["type"]), item)++ out: list[dict] = []+ for area in AREA_ORDER:+ total = totals.get(area, 0)+ if not total:+ continue+ lead = leads.get(area)+ out.append(+ {+ "key": area,+ "total": total,+ "severity": lead["severity"] if lead else "low",+ # What the count is made of, where one number over several+ # lanes would misstate it. Empty for areas that have one lane.+ "detail": area_details.get(area, ""),+ "lead": (+ {+ "title": lead["title"],+ "description": lead["description"],+ "type": lead["type"],+ "target_id": lead.get("target_id"),+ "subtype": lead.get("subtype"),+ "severity": lead["severity"],+ }+ if lead+ else None+ ),+ }+ )+ return out+++async def build_attention(+ session: AsyncSession,+ repo_id: str,+ *,+ decision_health: dict,+ knowledge_silos: list[dict],+) -> dict[str, Any]:+ """Every attention source, merged and ranked worst-first.++ Returns ``{"items": [...], "total": int, "by_source": {type: count}}``.+ ``total`` counts everything the sources hold, not the capped list, so a+ caller rendering five rows can honestly say "5 of 231".++ ``decision_health`` and ``knowledge_silos`` are passed in rather than+ fetched: the Overview route already has both in hand for other parts of its+ payload, and re-deriving them here would be two more scans of the widest+ table in the schema.++ A source that raises is dropped with its count, not allowed to fail the+ page. Overview is an aggregate over a dozen stores and one absent table (an+ index built before a detector shipped) should cost the row rather than the+ whole page.+ """+ by_source: dict[str, int] = {}+ details: dict[str, str] = {}+ items: list[dict] = []++ def _collect(key: str | None, got: list[dict], total: int, detail: str) -> None:+ source = key or (got[0]["type"] if got else None)+ if source and total:+ by_source[source] = total+ if detail:+ details[source] = detail+ items.extend(got)++ async def _add_async(fn) -> None:+ try:+ got, total, detail = await fn(session, repo_id)+ except Exception:+ return+ _collect(None, got, total, detail)++ await _add_async(_health_items)+ await _add_async(_security_items)+ await _add_async(_refactoring_items)+ await _add_async(_drift_items)+ await _add_async(_dead_code_items)++ _collect("decisions", *_decision_items(decision_health))+ _collect("knowledge_silo", *_silo_items(knowledge_silos))++ ranked = _rank(items)+ return {+ "items": ranked,+ "total": sum(by_source.values()),+ "by_source": by_source,+ "areas": _areas(ranked, by_source, details),+ }diff --git a/packages/server/src/repowise/server/services/knowledge_map.py b/packages/server/src/repowise/server/services/knowledge_map.pyindex 6bb8c83b3..2c5c265d3 100644--- a/packages/server/src/repowise/server/services/knowledge_map.py+++ b/packages/server/src/repowise/server/services/knowledge_map.py@@ -5,12 +5,132 @@ from __future__ import annotationsfrom collections import defaultdictfrom typing import Any-from sqlalchemy import select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence.models import GitMetadata, GraphNode, Page+async def compute_knowledge_silos(session: AsyncSession, repo_id: str) -> list[dict[str, Any]]:+ """Files whose primary owner holds more than 80% of the commits.++ Split out of :func:`compute_knowledge_map` because Overview wants only this+ list and the full map is expensive to the point of dominating that page:+ it hydrates every ``GitMetadata`` row as an ORM entity (seven large JSON+ blob columns) and loads the full ``content`` of every file page to count+ words for a top-10 onboarding list Overview never reads.++ Three columns, one query, no entity hydration.+ """+ rows = await session.execute(+ select(+ GitMetadata.file_path,+ GitMetadata.primary_owner_email,+ GitMetadata.primary_owner_commit_pct,+ GitMetadata.commit_count_90d,+ GitMetadata.is_hotspot,+ )+ .where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.primary_owner_commit_pct > 0.8,+ )+ # Activity first, concentration second. Sole ownership of a file nobody+ # has touched in a year is a fact, not a risk: the bus factor only+ # costs anything on code that still changes. Ordered here so every+ # caller previewing a few of these gets the ones that matter rather+ # than whatever the table returned first.+ .order_by(+ GitMetadata.is_hotspot.desc(),+ GitMetadata.commit_count_90d.desc().nulls_last(),+ GitMetadata.primary_owner_commit_pct.desc(),+ )+ )+ return [+ {+ "file_path": file_path,+ "owner_email": owner_email or "",+ "owner_pct": round(float(owner_pct or 0.0), 3),+ "commit_count_90d": int(commits or 0),+ "is_hotspot": bool(is_hotspot),+ }+ for file_path, owner_email, owner_pct, commits, is_hotspot in rows+ ]+++async def compute_onboarding_targets(+ session: AsyncSession, repo_id: str+) -> list[dict[str, Any]]:+ """High-centrality files carrying the least documentation.++ Its own function because two callers want exactly this and nothing else+ around it: the knowledge-map endpoint, and the Overview payload, which+ feeds the first-index experience. Overview used to reach it through+ :func:`compute_knowledge_map` and pay for the owner aggregation as well.+ """+ # `pagerank > 0` in SQL, not in the comprehension below: the filter+ # discards most rows and there is no reason to ship them.+ node_result = await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.repository_id == repo_id,+ GraphNode.is_test == False, # noqa: E712+ GraphNode.pagerank > 0.0,+ )+ )+ all_nodes = node_result.all()++ # Character length, computed in the database. The previous version selected+ # `Page.content` for every file page and called `len(text.split())` on each+ # one, which loads the entire generated prose of the repository — megabytes+ # on a documented tree — to produce a ten-row list.+ #+ # Length is only the shortlisting key. It ranks the same way a word count+ # does for prose, and the exact counts are read back below for the handful+ # of rows that survive, so the figure this returns is still a word count.+ size_result = await session.execute(+ select(Page.target_path, func.length(Page.content)).where(+ Page.repository_id == repo_id,+ Page.page_type == "file_page",+ )+ )+ doc_chars: dict[str, int] = {path: int(n or 0) for path, n in size_result}++ candidates = [+ {+ "path": node_id,+ "pagerank": pagerank,+ "doc_chars": doc_chars.get(node_id, 0),+ }+ for node_id, pagerank in all_nodes+ ]+ candidates.sort(key=lambda x: (x["doc_chars"], -x["pagerank"]))+ shortlist = candidates[:10]++ # Exact words for the ten rows that are actually returned. Most of them are+ # undocumented files with no page at all, so this usually fetches nothing.+ documented = [c["path"] for c in shortlist if c["doc_chars"] > 0]+ exact_words: dict[str, int] = {}+ if documented:+ word_rows = await session.execute(+ select(Page.target_path, Page.content).where(+ Page.repository_id == repo_id,+ Page.page_type == "file_page",+ Page.target_path.in_(documented),+ )+ )+ exact_words = {path: len((content or "").split()) for path, content in word_rows}++ onboarding_targets = [+ {+ "path": c["path"],+ "pagerank": c["pagerank"],+ "doc_words": exact_words.get(c["path"], 0),+ }+ for c in shortlist+ ]++ return onboarding_targets++async def compute_knowledge_map(session: AsyncSession, repo_id: str) -> dict[str, Any]:"""Return knowledge-map data for *repo_id*.@@ -21,10 +141,18 @@ async def compute_knowledge_map(session: AsyncSession, repo_id: str) -> dict[strReturns an empty dict when no git metadata is available."""+ # Four columns, not the whole entity: GitMetadata carries seven JSON blob+ # columns (top authors, significant commits, co-change partners, …) and+ # none of them is read here.git_res = await session.execute(- select(GitMetadata).where(GitMetadata.repository_id == repo_id)+ select(+ GitMetadata.file_path,+ GitMetadata.primary_owner_email,+ GitMetadata.primary_owner_name,+ GitMetadata.primary_owner_commit_pct,+ ).where(GitMetadata.repository_id == repo_id))- all_git = git_res.scalars().all()+ all_git = git_res.all()if not all_git:return {}@@ -32,12 +160,12 @@ async def compute_knowledge_map(session: AsyncSession, repo_id: str) -> dict[str# top_owners: aggregate primary_owner_email across all filesowner_file_count: dict[str, int] = defaultdict(int)owner_name_map: dict[str, str] = {}- for g in all_git:- email = g.primary_owner_email or ""+ for _file_path, owner_email, owner_name, _pct in all_git:+ email = owner_email or ""if email:owner_file_count[email] += 1- if g.primary_owner_name:- owner_name_map[email] = g.primary_owner_name+ if owner_name:+ owner_name_map[email] = owner_nametotal_files = len(all_git) or 1top_owners = sorted(@@ -53,47 +181,20 @@ async def compute_knowledge_map(session: AsyncSession, repo_id: str) -> dict[strkey=lambda x: -x["files_owned"],)[:10]- # knowledge_silos: files where primary owner has > 80% ownership+ # knowledge_silos: files where primary owner has > 80% ownership. Derived+ # from the rows already in hand rather than by calling+ # compute_knowledge_silos, which would be a second scan of the same table.knowledge_silos = [{- "file_path": g.file_path,- "owner_email": g.primary_owner_email or "",- "owner_pct": round(float(g.primary_owner_commit_pct or 0.0), 3),+ "file_path": file_path,+ "owner_email": owner_email or "",+ "owner_pct": round(float(pct or 0.0), 3),}- for g in all_git- if (g.primary_owner_commit_pct or 0.0) > 0.8+ for file_path, owner_email, _owner_name, pct in all_git+ if (pct or 0.0) > 0.8]- # onboarding_targets: high-centrality files with fewest docs- node_result = await session.execute(- select(GraphNode).where(- GraphNode.repository_id == repo_id,- GraphNode.is_test == False, # noqa: E712- )- )- all_nodes = node_result.scalars().all()-- page_result = await session.execute(- select(Page).where(- Page.repository_id == repo_id,- Page.page_type == "file_page",- )- )- doc_words: dict[str, int] = {- p.target_path: len(p.content.split()) for p in page_result.scalars().all()- }-- candidates = [- {- "path": n.node_id,- "pagerank": n.pagerank,- "doc_words": doc_words.get(n.node_id, 0),- }- for n in all_nodes- if n.pagerank > 0.0- ]- candidates.sort(key=lambda x: (x["doc_words"], -x["pagerank"]))- onboarding_targets = candidates[:10]+ onboarding_targets = await compute_onboarding_targets(session, repo_id)return {"top_owners": top_owners,diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.tsindex 9f5407ef5..d393fe346 100644--- a/packages/types/src/overview.ts+++ b/packages/types/src/overview.ts@@ -5,7 +5,7 @@*/import type { Hotspot } from "./git.js";-import type { DefectAccuracy } from "./health.js";+import type { DefectAccuracy, HealthSeverity } from "./health.js";export interface OverviewRepoMeta {id: string;@@ -59,6 +59,12 @@ export interface OverviewStats {hotspot_count: number;silo_count: number;module_count: number;+ /**+ * Total non-comment lines of code, summed from the per-file health metrics.+ * Optional: a server predating the field omits it and the caller then has no+ * lines figure rather than rendering a zero it did not measure.+ */+ total_nloc?: number;deltas: OverviewStatDeltas;}@@ -105,16 +111,91 @@ export type OverviewAttentionType =| "proposed_decision"| "ungoverned_hotspot"| "knowledge_silo"- | "dead_code";+ | "dead_code"+ | "health_finding"+ | "security_finding"+ | "doc_drift"+ | "refactoring";export interface OverviewAttentionItem {id: string;type: OverviewAttentionType;title: string;description: string;- severity: "high" | "medium" | "low";+ /**+ * The four-level ladder shared with `HealthSeverity`, rather than the three+ * levels this used to declare. Sources that publish their own severity are+ * passed through unchanged; the two that genuinely have none (dead code and+ * documentation drift carry a confidence float instead) are bucketed onto it+ * server-side. See `server/services/attention.py`.+ */+ severity: HealthSeverity;/** Decision id, file path, … — what the item points at. */target_id: string;+ /**+ * The finding's own kind within its source: a `biomarker_type` for a health+ * finding, a scanner kind for security, a drift kind. Optional because the+ * decision and silo sources have no sub-kind.+ *+ * Sent raw so the UI can resolve it through the biomarker glossary it+ * already owns, rather than the server holding a second copy of that+ * vocabulary and the two drifting.+ */+ subtype?: string;+}++/**+ * How much each source holds, beside the capped list in `attention`.+ *+ * Every source is capped so no single store floods the merged list, which+ * means `attention.length` is not a total and never was safe to render as one.+ */+export type OverviewAttentionArea =+ | "security"+ | "health"+ | "refactoring"+ | "doc_drift"+ | "decisions"+ | "ownership"+ | "dead_code";++/**+ * One area of work, with the worst thing in it named.+ *+ * Six ranked findings out of sixteen thousand is a sample, not triage, and it+ * lets one store own every visible row. An area row reports how much that area+ * holds and leads with the single item that topped it, so the list stays a+ * fixed, scannable seven rows whatever the underlying volume.+ */+export interface OverviewAttentionAreaRow {+ key: OverviewAttentionArea;+ /** Everything this area holds, not what is displayed. */+ total: number;+ /** Severity of the lead, i.e. the worst thing in the area. */+ severity: HealthSeverity;+ /**+ * What the count is made of, where one number over several lanes would+ * misstate it — "365 awaiting review · 699 hotspots ungoverned" rather than+ * a bare 1,064. Empty string for an area with a single lane.+ */+ detail?: string;+ /** Absent only if the area reports a count with no item behind it. */+ lead: {+ title: string;+ description: string;+ type: OverviewAttentionType;+ target_id?: string | null;+ subtype?: string;+ severity: HealthSeverity;+ } | null;+}++export interface OverviewAttentionSummary {+ total: number;+ /** Keyed by attention type, plus `decisions` for the three decision lanes. */+ by_source: Record<string, number>;+ /** Optional: a server predating the area rows omits it. */+ areas?: OverviewAttentionAreaRow[];}export interface OverviewOnboardingTarget {@@ -171,6 +252,9 @@ export interface OverviewSummaryResponse {health: OverviewHealth;languages: OverviewLanguage[];attention: OverviewAttentionItem[];+ /** Optional: a server predating the merged attention list omits it, and the+ * UI then falls back to counting the rows it was given. */+ attention_summary?: OverviewAttentionSummary;onboarding_targets: OverviewOnboardingTarget[];top_hotspots: Hotspot[];recent_decisions: OverviewDecisionSlim[];diff --git a/packages/ui/__tests__/dashboard/attention-panel.test.tsx b/packages/ui/__tests__/dashboard/attention-panel.test.tsxindex a141f49e0..e83c1b848 100644--- a/packages/ui/__tests__/dashboard/attention-panel.test.tsx+++ b/packages/ui/__tests__/dashboard/attention-panel.test.tsx@@ -5,6 +5,7 @@ import {type AttentionItem,type AttentionItemType,} from "../../src/dashboard/attention-panel";+import { ATTENTION_SEVERITY_RANK } from "../../src/dashboard/attention-href";function item(id: string,@@ -16,8 +17,9 @@ function item(/** Server order: strictly severity-sorted, which is what the panel re-mixes. */function severitySorted(items: AttentionItem[]): AttentionItem[] {- const rank = { high: 0, medium: 1, low: 2 } as const;- return [...items].sort((a, b) => rank[a.severity] - rank[b.severity]);+ return [...items].sort(+ (a, b) => ATTENTION_SEVERITY_RANK[a.severity] - ATTENTION_SEVERITY_RANK[b.severity],+ );}describe("AttentionPanel", () => {diff --git a/packages/ui/src/dashboard/attention-href.ts b/packages/ui/src/dashboard/attention-href.tsindex d0e569f90..90195d6ba 100644--- a/packages/ui/src/dashboard/attention-href.ts+++ b/packages/ui/src/dashboard/attention-href.ts@@ -5,20 +5,133 @@ export type AttentionItemType =| "knowledge_silo"| "ungoverned_hotspot"| "dead_code"- | "proposed_decision";+ | "proposed_decision"+ | "health_finding"+ | "security_finding"+ | "doc_drift"+ | "refactoring";export interface AttentionItem {id: string;type: AttentionItemType;title: string;description: string;- severity: "high" | "medium" | "low";+ /** Four levels, matching `HealthSeverity`. The three-level version this+ * used to declare could not represent a critical health finding, which is+ * the band that most needs to outrank everything else on the list. */+ severity: AttentionSeverity;/** What the item points at — a decision id, file path, owner, … Used to* deep-link straight to the offending entity. */target_id?: string;+ /** The finding's kind within its source — a `biomarker_type`, a scanner+ * kind, a drift kind. Resolved to a label by the renderer. */+ subtype?: string;href?: string;}+/** The four-level ladder, worst first. Matches `HealthSeverity`. */+export type AttentionSeverity = "critical" | "high" | "medium" | "low";++/**+ * Sort weight for a severity, worst first.+ *+ * The server ranks the list before it ships (see+ * `server/services/attention.py`), so nothing in the UI needs to re-sort by+ * severity. This exists for the surfaces that re-mix the order for their own+ * reasons — the dashboard panel round-robins by type — and so that they do it+ * against one ladder instead of a local literal each.+ */+export const ATTENTION_SEVERITY_RANK: Record<AttentionSeverity, number> = {+ critical: 0,+ high: 1,+ medium: 2,+ low: 3,+};++/**+ * What to call each source, for every surface that renders these items.+ *+ * One map rather than one per renderer: the panel and the Overview rows had+ * separately maintained copies that had already drifted in case ("Stale+ * Decision" against "Stale decision"), and a new source meant remembering to+ * add it to both.+ *+ * Sentence case, per the copy rules: these are labels, not headings.+ */+export const ATTENTION_TYPE_LABEL: Record<AttentionItemType, string> = {+ stale_decision: "Stale decision",+ proposed_decision: "Needs review",+ ungoverned_hotspot: "Ungoverned",+ knowledge_silo: "Knowledge silo",+ dead_code: "Dead code",+ health_finding: "Code health",+ security_finding: "Security",+ doc_drift: "Doc drift",+ refactoring: "Refactoring",+};++/**+ * The page that owns a whole source, as opposed to one item of it.+ *+ * Used for the breakdown beside the list, and as {@link getDefaultHref}'s+ * fallback when an item carries no target — those were the same URLs written+ * twice, and the copy inside the switch had already started to drift from the+ * routes.+ *+ * `decisions` is not an item type; it is the key the server uses for the three+ * decision lanes together in `attention_summary.by_source`.+ */+export function attentionSourceHref(source: string, prefix: string): string {+ switch (source) {+ // Area keys, from `attention_summary.areas`. Listed beside the item types+ // they roll up so one function answers "where does this go" for both.+ // `doc_drift` and `dead_code` name an area and an item type at once and+ // route to the same page either way, so they need no separate case.+ case "security":+ return `${prefix}/code-health?tab=security`;+ case "health":+ return `${prefix}/code-health?tab=findings`;+ case "ownership":+ return `${prefix}/owners`;+ case "stale_decision":+ case "proposed_decision":+ case "decisions":+ return `${prefix}/decisions`;+ case "knowledge_silo":+ return `${prefix}/owners`;+ case "ungoverned_hotspot":+ return `${prefix}/code-health?tab=triage`;+ case "health_finding":+ return `${prefix}/code-health?tab=findings`;+ case "refactoring":+ return `${prefix}/refactoring`;+ case "security_finding":+ return `${prefix}/code-health?tab=security`;+ case "doc_drift":+ return `${prefix}/code-health?tab=doc-drift`;+ case "dead_code":+ return `${prefix}/code-health?tab=dead-code`;+ default:+ return prefix;+ }+}++/** Area keys are not item types, so they get their own names. */+const AREA_LABEL: Record<string, string> = {+ security: "Security",+ health: "Code health",+ refactoring: "Refactoring",+ doc_drift: "Doc drift",+ decisions: "Decisions",+ ownership: "Ownership",+ dead_code: "Dead code",+};++/** What to call a `by_source` key or an area key. */+export function attentionSourceLabel(source: string): string {+ return AREA_LABEL[source] ?? ATTENTION_TYPE_LABEL[source as AttentionItemType] ?? source;+}+/*** Where an attention item points.*@@ -42,16 +155,49 @@ export function getDefaultHref(item: AttentionItem, prefix: string): string {// Deep-link to the specific decision when we know which one.return target? `${prefix}/decisions/${encodeURIComponent(target)}`- : `${prefix}/decisions`;+ : attentionSourceHref(item.type, prefix);case "knowledge_silo":- // The silo target is the owning module/path — surface it on the owners- // view so the offending area is preselected.- return target ? `${prefix}/owners?path=${encodeURIComponent(target)}` : `${prefix}/owners`;+ // The file's own History tab, which is where ownership concentration is+ // visible. NOT `/owners?path=`: that route is a directory of people and+ // reads no path param at all, so the deep link this used to emit landed+ // on an unfiltered contributor list with the offending file nowhere on+ // it. A tab a file does not have falls back to its Overview, so this is+ // safe for any target.+ return target+ ? `${fileEntityPath(prefix, target)}?tab=history`+ : attentionSourceHref(item.type, prefix);case "ungoverned_hotspot":// Target is the hotspot's file path → open its file entity page.- return target ? fileEntityPath(prefix, target) : `${prefix}/code-health?tab=triage`;+ return target ? fileEntityPath(prefix, target) : attentionSourceHref(item.type, prefix);+ case "health_finding":+ // The file's Health tab, where the biomarker that produced this row is+ // listed with its deduction.+ return target+ ? `${fileEntityPath(prefix, target)}?tab=health`+ : attentionSourceHref(item.type, prefix);+ case "security_finding":+ // The category, deliberately: a security finding is a file and a line,+ // and no per-file surface renders it. Unlike the silo and dead-code+ // cases there is no better destination to deep-link to, so this lands+ // where the finding is actually readable.+ return attentionSourceHref(item.type, prefix);+ case "refactoring":+ // The plan list, not the file: a refactoring row IS the work, and the+ // page that owns it is where the plan can be read and handed to an+ // agent.+ return attentionSourceHref(item.type, prefix);+ case "doc_drift":+ // Also the category. `target_id` here is the *document* making the false+ // claim rather than the code it is wrong about, so a file page would+ // open the wrong subject.+ return attentionSourceHref(item.type, prefix);case "dead_code":- return `${prefix}/code-health?tab=dead-code`;+ // The row names one symbol, so the category list is the wrong landing:+ // the dead-code tab has no per-file filter, and arriving at a few+ // hundred unfiltered findings means finding the row again by hand. The+ // file page carries the symbol and its health. Untargeted findings still+ // get the list.+ return target ? fileEntityPath(prefix, target) : attentionSourceHref(item.type, prefix);default:return prefix;}diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsxindex 4dabfa4ea..cd090e12a 100644--- a/packages/ui/src/dashboard/attention-panel.tsx+++ b/packages/ui/src/dashboard/attention-panel.tsx@@ -8,6 +8,10 @@ import {Users,FileWarning,Lightbulb,+ Activity,+ ShieldAlert,+ FileText,+ Wrench,} from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { Badge } from "../ui/badge";@@ -23,16 +27,20 @@ import { buildWorkQueueAiPrompt } from "../health/ai-prompt-builder";// and a `"use client"` file cannot hand a callable function to the server.export { getDefaultHref } from "./attention-href";export type { AttentionItem, AttentionItemType } from "./attention-href";-import { getDefaultHref } from "./attention-href";-import type { AttentionItem, AttentionItemType } from "./attention-href";+import { ATTENTION_TYPE_LABEL, getDefaultHref } from "./attention-href";+import type { AttentionItem, AttentionItemType, AttentionSeverity } from "./attention-href";-const ICON_MAP = {+const ICON_MAP: Record<AttentionItemType, typeof AlertTriangle> = {stale_decision: AlertTriangle,knowledge_silo: Users,ungoverned_hotspot: FileWarning,dead_code: Trash2,proposed_decision: Lightbulb,-} as const;+ health_finding: Activity,+ security_finding: ShieldAlert,+ doc_drift: FileText,+ refactoring: Wrench,+};/*** Severity ramp for the row icons. Only `high` earns a hue — a column of@@ -41,19 +49,14 @@ const ICON_MAP = {* rather than colour, so all three stay distinguishable while red keeps its* meaning by being rare.*/-const SEVERITY_COLORS = {+const SEVERITY_COLORS: Record<AttentionSeverity, string> = {+ // Critical shares the error colour with high rather than adding a fourth+ // step. The point of the ramp is that red is rare; a second red defeats it.+ critical: "text-[var(--color-error)]",high: "text-[var(--color-error)]",medium: "text-[var(--color-text-secondary)]",low: "text-[var(--color-text-tertiary)]",-} as const;--const TYPE_LABELS = {- stale_decision: "Stale Decision",- knowledge_silo: "Knowledge Silo",- ungoverned_hotspot: "Ungoverned Hotspot",- dead_code: "Dead Code",- proposed_decision: "Needs Review",-} as const;+};interface AttentionPanelProps {items: AttentionItem[];@@ -179,7 +182,7 @@ export function AttentionPanel({{stripMarkdown(item.title)}</span><span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">- {TYPE_LABELS[item.type]}+ {ATTENTION_TYPE_LABEL[item.type]}</span></div><p className="text-xs text-[var(--color-text-tertiary)] truncate">diff --git a/packages/ui/src/git/fix-history-badge.tsx b/packages/ui/src/git/fix-history-badge.tsxindex 8bd6155e1..c6d1a470d 100644--- a/packages/ui/src/git/fix-history-badge.tsx+++ b/packages/ui/src/git/fix-history-badge.tsx@@ -38,11 +38,14 @@ export function FixHistoryBadge({if (!fix) return null;return (- <Badge- variant={fix.magnet ? "outdated" : "outline"}- className={className}- title={title ?? DEFAULT_TITLE}- >+ // Always `outline`, never the `outdated` variant it used to take when the+ // magnet fired. `fresh`/`stale`/`outdated` are the *documentation+ // confidence* vocabulary — on every other surface that red means "this+ // page is out of date" — and a file that attracts bug fixes is not an+ // outdated doc. Two marks on one object must not share a colour+ // vocabulary, so this one keeps the word and the bug glyph, which name+ // the thing far better than a hue can.+ <Badge variant="outline" className={className} title={title ?? DEFAULT_TITLE}><Bug className="h-2.5 w-2.5" />{fix.magnet ? `Bug magnet · ${fix.label}` : fix.label}</Badge>diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex e32ba6316..5d82061e4 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -525,7 +525,7 @@ export interface WorkQueueItem {type: string;title: string;description: string;- severity: "high" | "medium" | "low";+ severity: "critical" | "high" | "medium" | "low";target_id?: string | null;}diff --git a/packages/ui/src/overview/activity-lists.tsx b/packages/ui/src/overview/activity-lists.tsxindex 896370d30..1a5202061 100644--- a/packages/ui/src/overview/activity-lists.tsx+++ b/packages/ui/src/overview/activity-lists.tsx@@ -37,7 +37,7 @@ export function CommitRows({}: {commits: CommitRow[];hrefFor: (sha: string) => string;- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}) {const A = LinkComponent ?? "a";if (commits.length === 0) {@@ -84,7 +84,7 @@ export function DecisionRows({}: {decisions: DecisionRow[];hrefFor: (id: string) => string;- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}) {const A = LinkComponent ?? "a";if (decisions.length === 0) {diff --git a/packages/ui/src/overview/attention-areas.tsx b/packages/ui/src/overview/attention-areas.tsxnew file mode 100644index 000000000..5fdfda385--- /dev/null+++ b/packages/ui/src/overview/attention-areas.tsx@@ -0,0 +1,129 @@+import * as React from "react";+import type { OverviewAttentionAreaRow } from "@repowise-dev/types/overview";+import {+ attentionSourceHref,+ attentionSourceLabel,+ type AttentionSeverity,+} from "../dashboard/attention-href";+import { biomarkerLabel } from "../health/biomarker-glossary";+import { formatNumber } from "../lib/format";++const SEVERITY_COLOR: Record<AttentionSeverity, string> = {+ // Critical and high share the one red. The palette has a single "this is+ // bad" hue and a second would spend the distinction on nothing: the band is+ // already named in the screen-reader text and carried by the row order.+ critical: "var(--color-error)",+ high: "var(--color-error)",+ medium: "var(--color-warning)",+ low: "var(--color-text-tertiary)",+};++/** What to call the lead item's kind. Health findings name their biomarker. */+function leadKind(lead: NonNullable<OverviewAttentionAreaRow["lead"]>): string {+ if (lead.type === "health_finding" && lead.subtype) return biomarkerLabel(lead.subtype);+ return "";+}++/**+ * Attention as one row per area of work.+ *+ * This replaces a list of individual findings, which does not survive real+ * volume. With roughly sixteen thousand open health findings against twenty+ * documentation-drift findings, six ranked rows are six health findings: a+ * random sample of the largest store, presented as if it were a worklist, with+ * every other area invisible. Nobody can act on "change entropy in report.py"+ * pulled out of a pile that size.+ *+ * A row is deliberately both things at once. The count says how much the area+ * holds, the lead names the single worst thing in it so the row is concrete+ * rather than a category, and the whole row links to the page that owns the+ * subject. That is what keeps this from being the sidebar with numbers glued+ * on: a row you can only navigate from belongs in navigation, a row that+ * reports state belongs here.+ *+ * Fixed order, never re-sorted by severity. These are stable subjects, and a+ * list whose rows move between visits cannot be scanned by position — you have+ * to re-read it every time. Severity is carried by the dot and by the lead.+ */+export function AttentionAreas({+ areas,+ prefix,+ LinkComponent,+}: {+ areas: OverviewAttentionAreaRow[];+ prefix: string;+ LinkComponent?: React.ElementType | undefined;+}) {+ const A = LinkComponent ?? "a";+ if (areas.length === 0) {+ return (+ <p className="text-xs text-[var(--color-success)]">Nothing needs attention right now.</p>+ );+ }++ return (+ <ul className="m-0 list-none divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">+ {areas.map((area) => {+ const kind = area.lead ? leadKind(area.lead) : "";+ return (+ <li key={area.key}>+ <A+ href={attentionSourceHref(area.key, prefix)}+ className="group flex flex-col gap-1 py-3 text-xs no-underline sm:flex-row sm:items-baseline sm:gap-4"+ >+ <span className="flex shrink-0 items-center gap-2 sm:w-40">+ <span+ aria-hidden+ className="h-1.5 w-1.5 shrink-0 rounded-full"+ style={{ background: SEVERITY_COLOR[area.severity] }}+ />+ {/* The dot is nothing at all to a screen reader, and to anyone+ who cannot separate the hues. The text equivalent goes here+ rather than into a `title`, which assistive tech reads+ inconsistently. */}+ <span className="sr-only">worst item is {area.severity} severity. </span>+ <span className="font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">+ {attentionSourceLabel(area.key)}+ </span>+ </span>++ <span className="shrink-0 font-mono tabular-nums text-[var(--color-text-secondary)] sm:w-24">+ {formatNumber(area.total)}+ </span>++ <span className="min-w-0 flex-1 text-[var(--color-text-tertiary)]">+ {area.lead ? (+ <>+ {kind && <span className="text-[var(--color-text-secondary)]">{kind} · </span>}+ <span className="text-[var(--color-text-secondary)]">{area.lead.title}</span>+ <span className="mt-0.5 block truncate text-[11px] [text-wrap:pretty]">+ {/* The composition wins the second line where there is+ one: knowing that most of a security count is git+ history rather than the working tree changes what the+ number means, and changes it more than one more+ example would. */}+ {area.detail || area.lead.description}+ </span>+ </>+ ) : (+ area.detail && (+ <span className="block truncate text-[11px] [text-wrap:pretty]">+ {area.detail}+ </span>+ )+ )}+ </span>++ <span+ aria-hidden+ className="hidden shrink-0 self-center text-[var(--color-text-tertiary)] transition-transform group-hover:translate-x-0.5 group-hover:text-[var(--color-accent-primary)] sm:block"+ >+ →+ </span>+ </A>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/packages/ui/src/overview/attention-rows.tsx b/packages/ui/src/overview/attention-rows.tsxindex 789d0eada..31dfd6cd5 100644--- a/packages/ui/src/overview/attention-rows.tsx+++ b/packages/ui/src/overview/attention-rows.tsx@@ -1,25 +1,37 @@import * as React from "react";-import type { AttentionItem } from "../dashboard/attention-href";+import { ATTENTION_TYPE_LABEL, type AttentionItem } from "../dashboard/attention-href";+import { biomarkerLabel } from "../health/biomarker-glossary";/** Same item the panel renders. Deliberately not a parallel local type: the* two surfaces must resolve identical targets, and a looser `type: string`* here would silently accept a value `getDefaultHref` cannot route. */export type AttentionRowItem = AttentionItem;-const TYPE_LABEL: Record<string, string> = {- stale_decision: "Stale decision",- proposed_decision: "Proposed",- ungoverned_hotspot: "Ungoverned",- knowledge_silo: "Knowledge silo",- dead_code: "Dead code",-};const SEVERITY_COLOR: Record<string, string> = {+ // Critical and high share the error colour rather than introducing a fifth+ // hue: the palette has one "this is bad" red, and the band is already named+ // in the screen-reader text and carried by the sort order.+ critical: "var(--color-error)",high: "var(--color-error)",medium: "var(--color-warning)",low: "var(--color-text-tertiary)",};+/**+ * The kind chip on the left of a row.+ *+ * A health finding says which biomarker fired rather than the generic "Code+ * health", because "Brain method" and "Untested hotspot" are different jobs+ * and the source name is the least useful thing the row could lead with. The+ * glossary that resolves it lives in the UI, which is why the server sends the+ * raw `biomarker_type` instead of a label of its own.+ */+function typeLabel(item: AttentionItem): string {+ if (item.type === "health_finding" && item.subtype) return biomarkerLabel(item.subtype);+ return ATTENTION_TYPE_LABEL[item.type] ?? item.type;+}+/*** Triage items as full-width rows.*@@ -40,7 +52,7 @@ export function AttentionRows({items: AttentionRowItem[];/** Resolves an item to its target page; null renders the row unlinked. */hrefFor: (item: AttentionRowItem) => string | null;- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}) {const A = LinkComponent ?? "a";if (items.length === 0) {@@ -57,7 +69,7 @@ export function AttentionRows({const href = hrefFor(item);const body = (<>- <span className="flex shrink-0 items-center gap-1.5 sm:w-32">+ <span className="flex shrink-0 items-center gap-1.5 sm:w-40"><spanaria-hiddenclassName="h-1.5 w-1.5 shrink-0 rounded-full"@@ -69,7 +81,7 @@ export function AttentionRows({`title`, which assistive tech reads inconsistently. */}<span className="sr-only">{item.severity} severity. </span><span className="font-mono text-[9.5px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">- {TYPE_LABEL[item.type] ?? item.type}+ {typeLabel(item)}</span></span><span className="min-w-0 flex-1">diff --git a/packages/ui/src/overview/attention-sources.tsx b/packages/ui/src/overview/attention-sources.tsxnew file mode 100644index 000000000..3795b936a--- /dev/null+++ b/packages/ui/src/overview/attention-sources.tsx@@ -0,0 +1,52 @@+import * as React from "react";+import { attentionSourceHref, attentionSourceLabel } from "../dashboard/attention-href";+import { formatNumber } from "../lib/format";++/**+ * What the attention list is made of, beside the rows it could fit.+ *+ * The rows are ranked by severity, which is right and has a consequence: on a+ * repository whose worst findings all come from one detector, six rows can be+ * six code-health findings, and a section titled "Needs attention" then looks+ * like it only knows about one thing. The breakdown is the honest fix. It says+ * what the other sources hold without spending a row on a finding that is+ * genuinely less urgent than the ones above it, and it gives every source a+ * way in even when none of its items made the cut.+ *+ * Counts, not proportions. A bar would imply the sources are commensurable,+ * and 15,892 health findings against 245 security findings is not a ratio+ * anybody should read as one.+ */+export function AttentionSources({+ bySource,+ prefix,+ LinkComponent,+}: {+ /** `attention_summary.by_source` — keyed by item type, plus `decisions`. */+ bySource: Record<string, number>;+ prefix: string;+ LinkComponent?: React.ElementType | undefined;+}) {+ const A = LinkComponent ?? "a";+ const entries = Object.entries(bySource)+ .filter(([, count]) => count > 0)+ .sort(([, a], [, b]) => b - a);+ if (entries.length === 0) return null;++ return (+ <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1.5 pt-1">+ {entries.map(([source, count]) => (+ <A+ key={source}+ href={attentionSourceHref(source, prefix)}+ className="group text-[11px] text-[var(--color-text-tertiary)] no-underline"+ >+ <span className="font-mono font-semibold tabular-nums text-[var(--color-text-secondary)] transition-colors group-hover:text-[var(--color-accent-primary)]">+ {formatNumber(count)}+ </span>{" "}+ <span className="group-hover:underline">{attentionSourceLabel(source)}</span>+ </A>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/overview/explore-list.tsx b/packages/ui/src/overview/explore-list.tsxindex f0e78e045..bb60c118c 100644--- a/packages/ui/src/overview/explore-list.tsx+++ b/packages/ui/src/overview/explore-list.tsx@@ -27,7 +27,7 @@ export function ExploreList({LinkComponent,}: {entries: ExploreEntry[];- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}) {const A = LinkComponent ?? "a";if (entries.length === 0) return null;diff --git a/packages/ui/src/overview/health-lede.tsx b/packages/ui/src/overview/health-lede.tsxindex aca8ec967..1bf210e40 100644--- a/packages/ui/src/overview/health-lede.tsx+++ b/packages/ui/src/overview/health-lede.tsx@@ -5,16 +5,16 @@ import { LedeLink, PageLede } from "../shared/page-lede";export interface HealthLedeProps {/** Defect-risk headline, 1–10. Null until the first health run. */score: number | null;- maintainability?: number | null;- /** Static performance risk, 1–10. */- performance?: number | null;+ maintainability?: number | null | undefined;+ /** Static performance score, 1–10. Higher is better, like the other two. */+ performance?: number | null | undefined;/** Health of the highest-churn files. The interesting number, usually. */- hotspotHealth?: number | null;- hotspotCount?: number;- fileCount?: number;+ hotspotHealth?: number | null | undefined;+ hotspotCount?: number | undefined;+ fileCount?: number | undefined;/** "Full health report →" target. */href: string;- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}/**@@ -61,9 +61,14 @@ export function HealthLede({// pillar and not the other, and the naive version produced "Maintainability// scores 8.6. The three are scored separately" (there were two) or a sentence// starting lowercase when only performance was present.+ // "static performance risk 9.7" read as an alarm and meant the opposite: the+ // figure is a score on the same 1-10 ladder as the other two, where 9.7 is+ // close to clean. The noun has to agree with the direction of the number, so+ // it is named like its siblings and the word "risk" is left to the findings+ // count on the health page, where more genuinely is worse.const pillars: string[] = [];if (maintainability != null) pillars.push(`maintainability ${maintainability.toFixed(1)}`);- if (performance != null) pillars.push(`static performance risk ${performance.toFixed(1)}`);+ if (performance != null) pillars.push(`static performance ${performance.toFixed(1)}`);const pillarSentence =pillars.length === 0? null@@ -93,10 +98,17 @@ export function HealthLede({</strong>{" "}on defect risk, which we rate {band.label.toLowerCase()}.{pillarSentence && ` ${pillarSentence}`}+ {/* This used to open "The files you change most are the weak spot",+ which reads as an indictment of something every codebase does. Hot+ files scoring below the average is the premise the whole product+ rests on, not a failure: it is why ranking by git history finds+ defects that reading the code alone does not. Same two figures,+ stated as the finding they are, and pointed at the files rather+ than at the reader. */}{hotspotCount > 0 && hot && (<>{" "}- The files you change most are the weak spot:{" "}+ Risk is concentrated, as it usually is:{" "}<strong className="font-semibold text-[var(--color-text-primary)]">{hotspotCount.toLocaleString()}{fileCount > 0 ? ` of ${fileCount.toLocaleString()}` : ""} files@@ -105,7 +117,7 @@ export function HealthLede({<strong className="font-semibold" style={{ color: hot.color }}>{hotspotHealth!.toFixed(1)}</strong>- .+ {" "}— which is where the fixes pay off most.</>)}</p>diff --git a/packages/ui/src/overview/hotspot-table.tsx b/packages/ui/src/overview/hotspot-table.tsxindex 802edf961..fad87d16e 100644--- a/packages/ui/src/overview/hotspot-table.tsx+++ b/packages/ui/src/overview/hotspot-table.tsx@@ -1,5 +1,6 @@import * as React from "react";import type { Hotspot } from "@repowise-dev/types/git";+import { formatRelativeTime, formatDateTime } from "../lib/format";function fileName(path: string): string {const i = path.lastIndexOf("/");@@ -14,10 +15,15 @@ function fileDir(path: string): string {/*** Where the risk concentrates, as a table rather than a mini card.*- * The card this replaces rendered a churn bar per file that read "100%" for- * every row, which is no information at all. The columns here are the ones- * that actually rank a file: prior fixes and change frequency mined from full- * git history, plus how many people maintain it.+ * Every column has to vary across the rows, or it is decoration. The card+ * this replaced rendered a churn bar that read "100%" on every row; the churn+ * *percentile* column that succeeded it had the same defect for the same+ * reason — this is the top of a ranking whose primary key is churn, so the+ * five rows read 100.0th, 100.0th, 99.9th, 99.9th, 99.9th and rank nothing.+ * It is replaced by the date of the last fix, which varies, and which the+ * `bug_magnet` field is contractually required to appear beside: that flag is+ * a decayed, recency-weighted claim, so a copy showing it without saying when+ * is asserting something it has not shown.** Placed mid-page, not at the top. On the public landing page this table is* the proof that the product does something git-history-shaped, and a stranger@@ -33,7 +39,7 @@ export function HotspotTable({hotspots: Hotspot[];/** Builds the per-file link. Callers differ on route shape, so it is a fn. */hrefFor: (path: string) => string;- LinkComponent?: React.ElementType;+ LinkComponent?: React.ElementType | undefined;}) {const A = LinkComponent ?? "a";if (hotspots.length === 0) return null;@@ -46,8 +52,8 @@ export function HotspotTable({<thead><tr className="border-b border-[var(--color-border-default)] text-left font-mono text-[9.5px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"><th scope="col" className="pb-2 pr-4 font-medium">File</th>- <th scope="col" className="pb-2 pr-4 font-medium">Churn</th><th scope="col" className="pb-2 pr-4 font-medium">Prior fixes</th>+ <th scope="col" className="pb-2 pr-4 font-medium">Last fix</th><th scope="col" className="pb-2 pr-4 font-medium">Maintainers</th><th scope="col" className="pb-2 text-right font-medium">Commits 90d</th></tr>@@ -75,26 +81,36 @@ export function HotspotTable({)}</A></td>- <td className="py-2.5 pr-4 font-mono tabular-nums text-[var(--color-text-secondary)]">- {h.churn_percentile != null ? (- <>- {h.churn_percentile.toFixed(1)}- <span className="text-[var(--color-text-tertiary)]">th</span>- </>- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- )}- </td><td className="py-2.5 pr-4 font-mono tabular-nums text-[var(--color-text-secondary)]">{h.prior_defect_count ?? 0}+ {/* Quiet, and no longer a red pill. Rule 7 is "mark+ exceptions, not the default": this is a table OF bug+ magnets, so on most rows the flag is the reason the row+ is here rather than news about it, and an alarm colour on+ four rows of five is the loudest thing on the page saying+ the least. Red is also spoken for — it carries a health+ band everywhere else, and a reader arriving from Code+ Health reads it as a score. */}{h.bug_magnet && (- <span className="ml-1.5 whitespace-nowrap rounded-full border border-[color-mix(in_srgb,var(--color-error)_35%,transparent)] bg-[color-mix(in_srgb,var(--color-error)_8%,transparent)] px-1.5 py-0.5 font-sans text-[9.5px] font-medium text-[var(--color-error)]">+ <span className="ml-1.5 whitespace-nowrap font-sans text-[10px] text-[var(--color-text-tertiary)]">bug magnet</span>)}</td>+ <td className="py-2.5 pr-4 font-mono tabular-nums text-[var(--color-text-secondary)]">+ {h.last_fix_at ? (+ <span title={formatDateTime(h.last_fix_at)}>+ {formatRelativeTime(h.last_fix_at)}+ </span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}+ </td><td className="py-2.5 pr-4 font-mono tabular-nums text-[var(--color-text-secondary)]">{h.contributor_count ?? 0}+ {/* This one keeps its colour: a single maintainer is a+ genuine exception among these rows, not the reason they+ were selected. */}{h.bus_factor === 1 && (<span className="mt-0.5 block whitespace-nowrap font-sans text-[10px] text-[var(--color-warning)]">bus factor 1diff --git a/packages/ui/src/overview/index.ts b/packages/ui/src/overview/index.tsindex 3fb498e16..eb72bab34 100644--- a/packages/ui/src/overview/index.ts+++ b/packages/ui/src/overview/index.ts@@ -34,10 +34,27 @@ export type { ChangeLineProps, ChangeStat } from "./change-line";export { CommitRows, DecisionRows } from "./activity-lists";export type { CommitRow, DecisionRow } from "./activity-lists";+export { AttentionAreas } from "./attention-areas";export { AttentionRows } from "./attention-rows";+export { AttentionSources } from "./attention-sources";export type { AttentionRowItem } from "./attention-rows";export { HotspotTable } from "./hotspot-table";export { ExploreList } from "./explore-list";export type { ExploreEntry } from "./explore-list";export { LanguageBar } from "./language-bar";++export { OverviewBody } from "./overview-body";+export type { OverviewBodyProps, OverviewBodySlots } from "./overview-body";++export {+ buildChangeStats,+ buildExplore,+ buildLanguageDistribution,+ buildReads,+ buildRibbon,+ docPageCount,+ previousSnapshotAt,+ resolveOverviewRoutes,+} from "./overview-model";+export type { OverviewRoutes, ResolvedOverviewRoutes } from "./overview-model";diff --git a/packages/ui/src/overview/language-bar.tsx b/packages/ui/src/overview/language-bar.tsxindex 3cd3d0cb1..fb0f7c7ea 100644--- a/packages/ui/src/overview/language-bar.tsx+++ b/packages/ui/src/overview/language-bar.tsx@@ -1,13 +1,51 @@import * as React from "react";+/**+ * Two hues then neutrals, in the order the rule allows. The accent leads+ * because the first segment is the repository's primary language; plum is the+ * pairing `globals.css` already sanctions beside it; the rest recede, which is+ * also the honest encoding, since a 2% slice is not as interesting as a 60%+ * one.+ */+const SEGMENTS: { bg: string; ink: string }[] = [+ // `ink` is a fixed value per fill rather than a theme token. Both fills hold+ // their own lightness in either theme — the orange is light, the plum is+ // dark — so a token that flips with the theme is guaranteed to be wrong on+ // one of them half the time.+ { bg: "var(--color-accent-fill)", ink: "#1a1205" },+ { bg: "var(--color-accent-secondary)", ink: "#f5f1ea" },+ { bg: "var(--color-neutral-1)", ink: "var(--color-text-secondary)" },+ { bg: "var(--color-neutral-2)", ink: "var(--color-text-secondary)" },+ { bg: "var(--color-neutral-3)", ink: "var(--color-text-secondary)" },+];++const OTHER_SEGMENT = {+ bg: "var(--color-bg-inset)",+ ink: "var(--color-text-secondary)",+};++/** Below this share a segment is too narrow to hold its own name legibly. */+const INLINE_LABEL_MIN_PCT = 12;+/*** Language mix as a stacked bar plus a key.** Replaces a donut that spent roughly 200px of height rendering four numbers* you can read faster as text, and did it in four unrelated hues that fought- * every other colour on the page. The bar is one accent stepped down in- * lightness, so proportion still reads at a glance without introducing a- * second palette.+ * every other colour on the page.+ *+ * Two problems with what replaced it, both fixed here.+ *+ * It painted the segments with `--color-ramp-*`, whose own definition says+ * "ramp means magnitude; NOT for unrelated categories, which want either the+ * accent/secondary pair or plain neutrals". Languages are unrelated+ * categories, and five steps of one hue in a 6px bar are not separable — you+ * cannot match a swatch in the key back to a segment. It now uses the pairing+ * the rule sanctions: the accent, the plum secondary, then neutrals.+ *+ * More importantly, the widest segments carry their own name. That removes the+ * matching problem outright rather than making it slightly easier, and the key+ * is left to do the job only the small segments still need.*/export function LanguageBar({distribution,@@ -25,49 +63,62 @@ export function LanguageBar({const shown = entries.slice(0, maxShown);const restCount = entries.slice(maxShown).reduce((s, [, n]) => s + n, 0);- const segments: { name: string; count: number; color: string }[] = shown.map(- ([name, count], i) => ({- name,- count,- // Step the accent down toward the inset surface rather than reaching for- // new hues: proportion is the message, identity of each language is the- // key's job.- color:- i === 0- ? "var(--color-accent-fill)"- : `color-mix(in srgb, var(--color-accent-fill) ${Math.max(12, 70 - i * 16)}%, var(--color-bg-inset))`,- }),- );+ const segments = shown.map(([name, count], i) => ({+ name,+ count,+ ...(SEGMENTS[i] ?? OTHER_SEGMENT),+ pct: (count / total) * 100,+ }));if (restCount > 0) {- segments.push({ name: "Other", count: restCount, color: "var(--color-bg-inset)" });+ segments.push({+ name: "Other",+ count: restCount,+ ...OTHER_SEGMENT,+ pct: (restCount / total) * 100,+ });}return (<div className="flex flex-col gap-2.5">- <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">+ {/* Tall enough to hold type. The 6px bar it replaces could only ever be+ decoded through the key. */}+ <div className="flex h-6 w-full overflow-hidden rounded-md bg-[var(--color-bg-inset)]">{segments.map((s) => (<spankey={s.name}title={`${s.name}: ${s.count.toLocaleString()} files`}- className="h-full"- style={{ width: `${(s.count / total) * 100}%`, background: s.color }}- />+ className="flex h-full min-w-0 items-center justify-center overflow-hidden px-1.5"+ style={{ width: `${s.pct}%`, background: s.bg }}+ >+ {s.pct >= INLINE_LABEL_MIN_PCT && (+ <span+ className="truncate font-mono text-[10px] font-medium"+ style={{ color: s.ink }}+ >+ {s.name} {Math.round(s.pct)}%+ </span>+ )}+ </span>))}</div>+ {/* Only what the bar could not label itself. A key that repeats every+ segment makes the inline labels redundant rather than helpful. */}<div className="flex flex-wrap gap-x-4 gap-y-1 font-mono text-[10px] text-[var(--color-text-tertiary)]">- {segments.map((s) => (- <span key={s.name} className="inline-flex items-center">- <span- aria-hidden- className="mr-1.5 inline-block h-1.5 w-1.5 rounded-sm"- style={{ background: s.color }}- />- {s.name}{" "}- <span className="ml-1 tabular-nums text-[var(--color-text-secondary)]">- {Math.round((s.count / total) * 100)}%+ {segments+ .filter((s) => s.pct < INLINE_LABEL_MIN_PCT)+ .map((s) => (+ <span key={s.name} className="inline-flex items-center">+ <span+ aria-hidden+ className="mr-1.5 inline-block h-1.5 w-1.5 rounded-sm"+ style={{ background: s.bg }}+ />+ {s.name}{" "}+ <span className="ml-1 tabular-nums text-[var(--color-text-secondary)]">+ {Math.round(s.pct)}%+ </span></span>- </span>- ))}+ ))}</div></div>);diff --git a/packages/ui/src/overview/overview-body.tsx b/packages/ui/src/overview/overview-body.tsxnew file mode 100644index 000000000..c6c2b82c8--- /dev/null+++ b/packages/ui/src/overview/overview-body.tsx@@ -0,0 +1,234 @@+import * as React from "react";+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";+import { getDefaultHref } from "../dashboard/attention-href";+import { formatNumber } from "../lib/format";+import { fileEntityPath } from "../shared/entity";+import { StatRibbon } from "../stats/stat-ribbon";+import { AttentionAreas } from "./attention-areas";+import { AttentionRows } from "./attention-rows";+import { CommitRows, DecisionRows, type CommitRow } from "./activity-lists";+import { ChangeLine } from "./change-line";+import { ExploreList } from "./explore-list";+import { HealthLede } from "./health-lede";+import { HotspotTable } from "./hotspot-table";+import { LanguageBar } from "./language-bar";+import {+ buildChangeStats,+ buildExplore,+ buildLanguageDistribution,+ buildReads,+ buildRibbon,+ previousSnapshotAt,+ resolveOverviewRoutes,+ type OverviewRoutes,+} from "./overview-model";+import { ReadsColumn } from "./reads-column";+import { OverviewSection, SectionLink } from "./section";++/** How many rows each list section shows before deferring to its own page. */+const ATTENTION_ROWS = 6;+const HOTSPOT_ROWS = 5;+const DECISION_ROWS = 6;++export interface OverviewBodySlots {+ /** The identity header. Each host builds its own: OSS carries reindex+ * actions, hosted carries a snapshot chip, and neither is expressible as a+ * prop of the other. */+ header?: React.ReactNode;+ /** Under the reads column. Hosted puts its MCP connect card here. */+ afterReads?: React.ReactNode;+ /** A section between Composition and Explore. Hosted's index-coverage+ * panel. */+ beforeExplore?: React.ReactNode;+ /** Contents of the "Ask this codebase" section. Omitted where the host+ * routes to a chat page from Explore instead, and the section then does not+ * render at all rather than rendering empty. */+ ask?: React.ReactNode;+}++export interface OverviewBodyProps {+ summary: OverviewSummaryResponse;+ routes: OverviewRoutes;+ /** Recent commits, already fetched and bounded by the host. */+ commits?: CommitRow[];+ /** Total lines of code. The two hosts source this differently, so it is a+ * prop rather than a payload read. */+ totalNloc?: number | null;+ LinkComponent?: React.ElementType;+ slots?: OverviewBodySlots;+}++/**+ * The repo Overview, once its data has arrived.+ *+ * Renders only — no fetching, no hooks, no host imports. That is what lets OSS+ * call it from a server component and hosted call it from inside a `"use+ * client"` SWR tree, which was the reason the two pages had been copies of+ * each other rather than one component: hosted cannot be a server component+ * (its payload arrives through SWR, and private snapshots have no server-side+ * token), so anything that fetches cannot be shared, and anything that does+ * not fetch can.+ *+ * Section order answers three questions in sequence: what state is this+ * repository in, what needs me, and where do I go. "Needs attention" sits+ * directly under the health hero rather than fourth, because the page is+ * mostly opened by someone who was here last week and wants the delta, not by+ * a stranger who wants the tour.+ */+export function OverviewBody({+ summary,+ routes,+ commits = [],+ totalNloc,+ LinkComponent,+ slots = {},+}: OverviewBodyProps) {+ const resolved = resolveOverviewRoutes(routes);+ const { base } = resolved;+ const { stats, health } = summary;++ const reads = buildReads(summary, routes);+ const ribbon = buildRibbon(summary, routes, totalNloc);+ const explore = buildExplore(summary, routes);+ const changeStats = buildChangeStats(summary);+ const langDistribution = buildLanguageDistribution(summary);++ // The list is capped per source server-side, so its length is not a total.+ // Falling back to the row count on a server that predates the summary keeps+ // the old (correct-for-that-payload) behaviour rather than rendering+ // nothing.+ const attentionTotal = summary.attention_summary?.total ?? summary.attention.length;+ const areas = summary.attention_summary?.areas ?? [];++ return (+ <div className="mx-auto flex w-full max-w-[1280px] flex-col gap-6 p-[var(--page-pad)] sm:gap-8">+ {slots.header}++ <ChangeLine since={previousSnapshotAt(summary)} stats={changeStats} />++ {/* Health keeps the largest number and the leftmost position. The column+ beside it carries the other reasons someone opens Overview, so a+ visitor who came for docs or costs finds their figure at the same+ altitude rather than three scrolls down. */}+ <div className="grid grid-cols-1 items-start gap-8 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-12">+ <HealthLede+ score={health.average_health}+ maintainability={health.maintainability_average}+ performance={health.performance_average}+ hotspotHealth={health.hotspot_health}+ hotspotCount={stats.hotspot_count}+ fileCount={stats.file_count}+ href={`${base}/code-health`}+ LinkComponent={LinkComponent}+ />+ <div className="flex flex-col gap-6">+ <ReadsColumn items={reads} LinkComponent={LinkComponent} />+ {slots.afterReads}+ </div>+ </div>++ {(areas.length > 0 || summary.attention.length > 0) && (+ <OverviewSection+ title="Needs attention"+ description="Every detector, by area of work, each leading with the worst thing in it: code health and the test-quality biomarkers, security, refactoring, documentation drift, decision records, ownership, and dead code."+ // No section link: these span seven pages, so there is no single+ // destination that holds "all of them", and a count linking to one+ // of them would be a lie about where the rest live.+ action={+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">+ {formatNumber(attentionTotal)} open+ </span>+ }+ >+ {areas.length > 0 ? (+ <AttentionAreas areas={areas} prefix={base} LinkComponent={LinkComponent} />+ ) : (+ // A server predating the area rollup still sends ranked items, and+ // rendering those is strictly better than rendering nothing.+ <AttentionRows+ items={summary.attention.slice(0, ATTENTION_ROWS)}+ hrefFor={(item) => getDefaultHref(item, base)}+ LinkComponent={LinkComponent}+ />+ )}+ </OverviewSection>+ )}++ <StatRibbon stats={ribbon} LinkComponent={LinkComponent} />++ <OverviewSection+ title="Recent activity"+ action={+ <SectionLink href={`${base}/commits`} LinkComponent={LinkComponent}>+ All commits+ </SectionLink>+ }+ >+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-10">+ <div className="flex min-w-0 flex-col gap-2">+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Commits+ </h3>+ <CommitRows+ commits={commits}+ hrefFor={(sha) => `${base}/commits?commit=${sha}`}+ LinkComponent={LinkComponent}+ />+ </div>+ <div className="flex min-w-0 flex-col gap-2">+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Decisions+ </h3>+ <DecisionRows+ decisions={summary.recent_decisions.slice(0, DECISION_ROWS)}+ hrefFor={(decisionId) => `${base}/decisions/${encodeURIComponent(decisionId)}`}+ LinkComponent={LinkComponent}+ />+ </div>+ </div>+ </OverviewSection>++ {summary.top_hotspots.length > 0 && (+ <OverviewSection+ title="Where the risk concentrates"+ description="Ranked by prior bug fixes and change frequency, mined from full git history rather than from the code alone."+ action={+ <SectionLink href={`${base}/code-health?tab=triage`} LinkComponent={LinkComponent}>+ {`All ${formatNumber(stats.hotspot_count)} hotspots`}+ </SectionLink>+ }+ >+ <HotspotTable+ hotspots={summary.top_hotspots.slice(0, HOTSPOT_ROWS)}+ hrefFor={(path) => fileEntityPath(base, path)}+ LinkComponent={LinkComponent}+ />+ </OverviewSection>+ )}++ {summary.languages.length > 0 && (+ <OverviewSection+ title="Composition"+ action={+ <SectionLink+ href={resolved.languageGraph}+ LinkComponent={LinkComponent}+ >+ Open the graph+ </SectionLink>+ }+ >+ <LanguageBar distribution={langDistribution} />+ </OverviewSection>+ )}++ {slots.beforeExplore}++ {slots.ask && <OverviewSection title="Ask this codebase">{slots.ask}</OverviewSection>}++ <OverviewSection title="Explore this codebase">+ <ExploreList entries={explore} LinkComponent={LinkComponent} />+ </OverviewSection>+ </div>+ );+}diff --git a/packages/ui/src/overview/overview-model.ts b/packages/ui/src/overview/overview-model.tsnew file mode 100644index 000000000..fdd6456b1--- /dev/null+++ b/packages/ui/src/overview/overview-model.ts@@ -0,0 +1,391 @@+/**+ * Everything the repo Overview derives from its payload, in one place.+ *+ * Both hosts render the same page from the same `OverviewSummaryResponse` and,+ * until this module existed, each rebuilt every row of it by hand: ~460 lines+ * in OSS and ~590 in hosted, computing the same reads, the same ribbon, the+ * same explore list, the same delta thresholds. They had already drifted — a+ * languages link pointing at two different graph views, a coupling route that+ * is a query param on one host and its own page on the other, a savings row+ * fixed on one side only — and every new signal had to be added twice.+ *+ * The split is: this module decides *what the page says*, the host supplies+ * *where its links go* and renders the shell. No fetching and no hooks, so a+ * server component (OSS) and a client component (hosted, which loads through+ * SWR and cannot be a server component) can both call it.+ *+ * Host-specific rows need no flags. Every one of them is already gated on a+ * field the payload either carries or does not: local index size is absent on+ * hosted because hosted has no `.repowise/` directory, agent savings are+ * absent because they come from a CLI-written sidecar, and score validation is+ * absent on OSS because nothing backtests it there. Asking "is the data here"+ * gets the right answer on both hosts without either one declaring which host+ * it is. The one thing that genuinely cannot be inferred is routing, which is+ * why {@link OverviewRoutes} exists and is the whole capability surface.+ */++import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";+import type { ChangeStat } from "./change-line";+import type { ExploreEntry } from "./explore-list";+import type { ReadItem } from "./reads-column";+import type { RibbonStat } from "../stats/stat-ribbon";+import {+ formatBytes,+ formatCost,+ formatLOC,+ formatNumber,+ formatTokens,+} from "../lib/format";++/**+ * Where this host's links go.+ *+ * Only the routes the two hosts disagree about are listed. Everything they+ * agree on (`/files`, `/docs`, `/commits`, `/owners`, `/stats`,+ * `/code-health`, `/architecture`, `/knowledge-graph`, `/decisions`) is built+ * from `base` and is not configurable, because a third spelling of those is a+ * bug rather than a feature.+ *+ * An optional route that is absent means the host does not have that page, and+ * the row that would have linked to it is not rendered. That is the honest+ * behaviour: a row whose link 404s is worse than a missing row.+ */+export interface OverviewRoutes {+ /** Link prefix for this host, e.g. `/repos/{id}` or `/s/{shortId}`. */+ base: string;+ /** Change coupling. OSS renders it as a view of the architecture page;+ * hosted gives it a route of its own. */+ coupling?: string;+ /** The file graph coloured by language. The two hosts spell the view+ * differently (`view=files` vs `view=graph`). */+ languageGraph?: string;+ /** Scoped chat. Hosted only; OSS puts an ask box on the page instead. */+ chat?: string;+ /** Local settings, where the on-disk index lives. OSS only. */+ settings?: string;+ /** Indexing cost breakdown. Linked from the savings read on both hosts, and+ * listed under Explore only where the page exists. */+ costs?: string;+}++/** Every route in {@link OverviewRoutes}, with the shared defaults applied. */+export type ResolvedOverviewRoutes = ReturnType<typeof resolveOverviewRoutes>;++/**+ * Resolved routes, with the defaults both hosts share filled in.+ *+ * Exported so a renderer that needs one of these hrefs outside a built list+ * (the Composition section links to the same language graph the ribbon does)+ * reads it from here rather than rebuilding a list to find one entry in it.+ */+export function resolveOverviewRoutes(routes: OverviewRoutes) {+ const { base } = routes;+ return {+ base,+ coupling: routes.coupling ?? `${base}/architecture?view=coupling`,+ languageGraph:+ routes.languageGraph ?? `${base}/architecture?view=files&colorMode=language`,+ chat: routes.chat,+ settings: routes.settings,+ costs: routes.costs,+ };+}++/**+ * What moved between the last two index snapshots.+ *+ * Measured against snapshots and not against `last_sync_at`: a commit only+ * enters the index when a sync ingests it, and that same sync stamps the+ * timestamp, so "newer than the last sync" is zero by construction.+ */+export function buildChangeStats(summary: OverviewSummaryResponse): ChangeStat[] {+ const stats: ChangeStat[] = [];+ const { deltas } = summary.stats;++ if (deltas.file_count) {+ const d = deltas.file_count;+ stats.push({+ value: `${d > 0 ? "+" : ""}${formatNumber(d)}`,+ label: Math.abs(d) === 1 ? "file" : "files",+ });+ }+ // The 0.05 floor is the point below which a score change is rounding rather+ // than news: both figures render to one decimal, so anything smaller shows+ // as "+0.0".+ for (const [value, label] of [+ [deltas.average_health, "defect risk"],+ [deltas.hotspot_health, "hotspot health"],+ ] as const) {+ if (value != null && Math.abs(value) >= 0.05) {+ stats.push({ value: `${value > 0 ? "+" : ""}${value.toFixed(1)}`, label });+ }+ }+ return stats;+}++/** ISO timestamp of the snapshot the deltas are measured against. */+export function previousSnapshotAt(summary: OverviewSummaryResponse): string | null {+ const history = summary.health.history;+ return history.length >= 2 ? (history[history.length - 2]?.taken_at ?? null) : null;+}++/** Generated page count, however this payload spells it. */+export function docPageCount(summary: OverviewSummaryResponse): number {+ return summary.stats.doc_page_count ?? summary.sync.page_count ?? 0;+}++/**+ * The column beside the health hero: the other reasons someone opens this+ * page, at the same altitude as the score.+ */+export function buildReads(summary: OverviewSummaryResponse, routes: OverviewRoutes): ReadItem[] {+ const r = resolveOverviewRoutes(routes);+ const { stats, health, sync, savings } = summary;+ const docPages = docPageCount(summary);+ const prosePages = stats.doc_prose_page_count;+ const reads: ReadItem[] = [];++ if (docPages > 0) {+ // Pages a model wrote and pages built from the index alone are different+ // things — one costs a generation call and can go stale, the other is free+ // and rebuilt every sync — and a single total hides which you have.+ //+ // The copy says what the query measured ("with model-written prose" /+ // "without") rather than the tempting shorthand "deterministic": a page can+ // lack prose because its provider call failed, and calling that+ // deterministic reports an outage as a design choice.+ const hasSplit = prosePages != null;+ const withoutProse = hasSplit ? Math.max(0, docPages - prosePages) : 0;+ reads.push({+ key: "docs",+ label: "Documentation",+ value: formatNumber(docPages),+ unit: "pages",+ href: `${r.base}/docs`,+ why: hasSplit+ ? `${formatNumber(prosePages)} with model-written prose, ${formatNumber(withoutProse)} built from the index`+ : `Across ${formatNumber(stats.module_count)} modules`,+ ...(hasSplit+ ? {+ bar: [+ {+ fraction: prosePages / docPages,+ color: "var(--color-accent-fill)",+ title: `${formatNumber(prosePages)} pages with model-written prose`,+ },+ {+ fraction: withoutProse / docPages,+ color: "color-mix(in srgb, var(--color-accent-fill) 30%, var(--color-bg-inset))",+ title: `${formatNumber(withoutProse)} pages built from the index alone`,+ },+ ],+ }+ : {}),+ });+ }++ // Backtested precision of the defect ranking. Present wherever the server+ // has run the validation, which today is hosted.+ const accuracy = health.defect_accuracy;+ if (accuracy && accuracy.k > 0) {+ reads.push({+ key: "accuracy",+ label: "Score validation",+ value: `${formatNumber(accuracy.hits)}/${formatNumber(accuracy.k)}`,+ ...(accuracy.lift ? { unit: `${accuracy.lift.toFixed(1)}× baseline` } : {}),+ href: `${r.base}/code-health?tab=triage`,+ why: "Top-ranked files that did go on to need a bug fix",+ });+ }++ // From a CLI-written `.repowise/omissions` sidecar, so this row is simply+ // absent wherever that sidecar cannot exist. No flag, no empty state+ // pitching a CLI the viewer is not running.+ const savedTokens = savings.saved_input_tokens ?? 0;+ if (savings.available && savedTokens > 0 && r.costs) {+ // "Estimated" while any of the total rests on a counterfactual rather than+ // a measured before and after. The two are different claims, and the row+ // is too small to show the split, so it qualifies the label instead.+ const inferred = savings.inferred_saved_input_tokens ?? 0;+ reads.push({+ key: "savings",+ label: inferred > 0 ? "Estimated agent savings" : "Agent savings",+ value: formatTokens(savedTokens),+ ...(savings.estimated_usd_saved ? { unit: formatCost(savings.estimated_usd_saved) } : {}),+ href: r.costs,+ why:+ inferred > 0+ ? "Input tokens your agent did not have to read, part of it estimated"+ : "Input tokens your agent did not have to read",+ });+ }++ if (stats.dead_export_count > 0) {+ reads.push({+ key: "dead-code",+ label: "Dead code",+ value: formatNumber(stats.dead_export_count),+ unit: "exports",+ href: `${r.base}/code-health?tab=dead-code`,+ why: "Unused exports that nothing in the graph reaches",+ });+ }++ // A local-disk figure. Hosted stores indexes elsewhere and never has it.+ if (sync.index_storage_bytes && r.settings) {+ reads.push({+ key: "index",+ label: "Index",+ value: formatBytes(sync.index_storage_bytes),+ href: r.settings,+ why: `Wiki, symbols and vectors on disk · ${Math.round(stats.doc_coverage_pct)}% average doc confidence`,+ });+ }++ return reads;+}++/**+ * The scale ribbon: the whole first-visit orientation job in one row.+ *+ * `totalNloc` is passed in rather than read off the payload because the two+ * hosts source it differently — OSS from the stats endpoint, hosted from a+ * field its backend added ahead of the shared types package. Neither is worth+ * encoding here; the caller has the number.+ */+export function buildRibbon(+ summary: OverviewSummaryResponse,+ routes: OverviewRoutes,+ totalNloc?: number | null,+): RibbonStat[] {+ const r = resolveOverviewRoutes(routes);+ const ribbon: RibbonStat[] = [];+ if (totalNloc != null) {+ ribbon.push({ label: "Lines of code", value: formatLOC(totalNloc) });+ }+ // Linked, because the KPI strip this replaced was five links: without hrefs+ // here, Files and Symbols lose their only entry point from this page.+ ribbon.push(+ { label: "Files", value: formatNumber(summary.stats.file_count), href: `${r.base}/files` },+ {+ label: "Symbols",+ value: formatNumber(summary.stats.symbol_count),+ href: `${r.base}/architecture?view=symbols`,+ },+ {+ label: "Modules",+ value: formatNumber(summary.stats.module_count),+ href: `${r.base}/architecture`,+ },+ {+ label: "Languages",+ value: formatNumber(summary.languages.length),+ href: r.languageGraph,+ },+ );+ return ribbon;+}++/**+ * Front doors to the pages that own each subject.+ *+ * Every row carries a live figure where one exists, which is what keeps this+ * from being the sidebar written out twice: a row that can only describe a+ * feature belongs in navigation, not on a page whose job is to report state.+ */+export function buildExplore(+ summary: OverviewSummaryResponse,+ routes: OverviewRoutes,+): ExploreEntry[] {+ const r = resolveOverviewRoutes(routes);+ const { stats, health } = summary;+ const docPages = docPageCount(summary);+ const entries: ExploreEntry[] = [+ {+ key: "docs",+ label: "Docs",+ href: `${r.base}/docs`,+ description: `${formatNumber(docPages)} pages across ${formatNumber(stats.module_count)} modules`,+ },+ ];++ if (r.chat) {+ entries.push({+ key: "chat",+ label: "Chat",+ href: r.chat,+ description: "Ask this codebase a question and get an answer with its sources.",+ });+ }++ entries.push(+ {+ key: "files",+ label: "Files",+ href: `${r.base}/files`,+ description: `${formatNumber(stats.file_count)} files with per-file docs, health and history`,+ },+ {+ key: "architecture",+ label: "Architecture",+ href: `${r.base}/architecture`,+ description: `Dependency graph, layers, and ${formatNumber(stats.entry_point_count)} entry points`,+ },+ {+ key: "code-health",+ label: "Code health",+ href: `${r.base}/code-health`,+ description: `Per-file scores, ${formatNumber(health.open_findings)} open findings, coverage and refactoring targets`,+ },+ {+ key: "knowledge-graph",+ label: "Knowledge graph",+ href: `${r.base}/knowledge-graph`,+ description: "Entities, communities, and the paths between them",+ },+ {+ key: "coupling",+ label: "Change coupling",+ href: r.coupling,+ description: "Files that keep changing together, mined from commit history",+ },+ {+ key: "commits",+ label: "Commits",+ href: `${r.base}/commits`,+ description: "Change-risk ranked history with agent provenance",+ },+ {+ key: "contributors",+ label: "Contributors",+ href: `${r.base}/owners`,+ description: "Bus factor, per-file maintainers, and the human/agent split",+ },+ {+ key: "stats",+ label: "Stats",+ href: `${r.base}/stats`,+ description: "Size class, origin, lifetime churn, rhythm and records",+ },+ );++ if (r.costs) {+ entries.push({+ key: "costs",+ label: "Costs",+ href: r.costs,+ description: "What indexing this snapshot cost, by model and by run.",+ });+ }++ return entries;+}++/** File counts per language, for the composition bar. */+export function buildLanguageDistribution(+ summary: OverviewSummaryResponse,+): Record<string, number> {+ const distribution: Record<string, number> = {};+ for (const l of summary.languages) distribution[l.language] = l.file_count;+ return distribution;+}diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex bed1bcdea..2979f398a 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -3,43 +3,20 @@ import { notFound } from "next/navigation";import Link from "next/link";import { getOverviewSummary } from "@/lib/api/overview";import { getProviders } from "@/lib/api/providers";-import { getStatsHighlights } from "@/lib/api/stats";import { getCommitsPage } from "@/lib/api/git";import { FirstIndexExperience } from "@/components/repos/first-index-experience";import { QuickActionsWrapper } from "@/components/dashboard/quick-actions-wrapper";import { AskAnythingRow } from "@/components/overview/ask-anything-row";import {- AttentionRows,- ChangeLine,- CommitRows,- DecisionRows,- ExploreList,- HealthLede,- HotspotTable,- LanguageBar,- OverviewSection,- ReadsColumn,+ OverviewBody,RepoIdentityHeader,- SectionLink,- type ChangeStat,- type ExploreEntry,- type ReadItem,+ type OverviewRoutes,type RepoIdentityMeta,} from "@repowise-dev/ui/overview";-import { getDefaultHref } from "@repowise-dev/ui/dashboard/attention-href";-// Direct path, not the `ui/stats` barrel: that barrel re-exports two-// "use client" modules, which would ship them to the browser for a page that-// renders entirely on the server.-import { StatRibbon, type RibbonStat } from "@repowise-dev/ui/stats/stat-ribbon";-import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import {- formatBytes,- formatCost,formatDateTime,formatLOC,- formatNumber,formatRelativeTime,- formatTokens,} from "@repowise-dev/ui/lib/format";export const metadata: Metadata = { title: "Overview" };@@ -60,6 +37,16 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {* the initial HTML instead of waterfalling in after paint. */const COMMIT_LIMIT = 6;+/**+ * The local dashboard's repo Overview.+ *+ * Everything this file does is host-specific: fetch on the server, resolve the+ * `/repos/{id}` route shape, and supply the two panels only the local app has+ * (reindex actions in the header, the ask box). The page itself — what it+ * says, in what order — is `OverviewBody` in the ui package, shared with+ * hosted so a new signal lands on both surfaces at once instead of being added+ * twice and drifting.+ */export default async function OverviewPage({ params }: Props) {const { id } = await params;@@ -67,18 +54,17 @@ export default async function OverviewPage({ params }: Props) {// renders client-side: this is a static read, so a hydration boundary would// only buy a slower first paint and worse indexability. The commits call// replaces a client-side SWR fetch that used to waterfall in after paint.- const [summary, providers, statsHighlights, commitsPage] = await Promise.all([+ const [summary, providers, commitsPage] = await Promise.all([safeFetch(() => getOverviewSummary(id)),safeFetch(() => getProviders()),- safeFetch(() => getStatsHighlights(id)),safeFetch(() => getCommitsPage(id, { sort: "date", limit: COMMIT_LIMIT })),]);if (!summary) notFound();const { repo, stats, health, sync } = summary;const isFresh = stats.file_count === 0;-const base = `/repos/${id}`;+ const totalNloc = stats.total_nloc ?? null;const lastActivityAt = sync.last_sync_at ?? sync.last_resync_at ?? health.last_indexed_at;// ── Identity ───────────────────────────────────────────────────────────@@ -87,8 +73,8 @@ export default async function OverviewPage({ params }: Props) {if (primaryLanguage) meta.push({ label: primaryLanguage, dot: true });meta.push({ label: repo.default_branch, mono: true });if (repo.head_commit) meta.push({ label: repo.head_commit.slice(0, 7), mono: true });- if (statsHighlights) {- meta.push({ label: `${formatLOC(statsHighlights.scale.total_nloc)} lines`, mono: true });+ if (totalNloc != null) {+ meta.push({ label: `${formatLOC(totalNloc)} lines`, mono: true });}if (lastActivityAt) {meta.push({@@ -129,343 +115,24 @@ export default async function OverviewPage({ params }: Props) {);}- // ── What moved between the last two indexes ────────────────────────────- // Deltas, not "things newer than the last sync". A commit only lands in the- // index once a sync ingests it, and that same sync stamps `last_sync_at`, so- // counting commits after that timestamp returns zero on a healthy repo.- // Decisions are worse: the sync run creates them. The snapshot deltas the- // server already computes are the figures that genuinely move.- const commits = commitsPage?.items ?? [];- const history = health.history;- const previousSnapshotAt =- history.length >= 2 ? (history[history.length - 2]?.taken_at ?? null) : null;-- const changeStats: ChangeStat[] = [];- if (stats.deltas.file_count) {- const d = stats.deltas.file_count;- changeStats.push({- value: `${d > 0 ? "+" : ""}${formatNumber(d)}`,- label: Math.abs(d) === 1 ? "file" : "files",- });- }- if (stats.deltas.average_health != null && Math.abs(stats.deltas.average_health) >= 0.05) {- const d = stats.deltas.average_health;- changeStats.push({- value: `${d > 0 ? "+" : ""}${d.toFixed(1)}`,- label: "defect risk",- });- }- if (stats.deltas.hotspot_health != null && Math.abs(stats.deltas.hotspot_health) >= 0.05) {- const d = stats.deltas.hotspot_health;- changeStats.push({- value: `${d > 0 ? "+" : ""}${d.toFixed(1)}`,- label: "hotspot health",- });- }-- // ── The reads beside health ────────────────────────────────────────────- // Health is the hero and keeps the biggest number, but it cannot be the only- // reason to open this page. Each row headlines a subject someone might have- // come for, at the same altitude as the health score and one click from the- // page that owns it.- const docPages = stats.doc_page_count ?? sync.page_count ?? 0;- const prosePages = stats.doc_prose_page_count;- const reads: ReadItem[] = [];-- if (docPages > 0) {- // Pages a model wrote and pages built from the index alone are different- // things — one costs a generation call and can go stale, the other is free- // and rebuilt every sync — and a single total hides which you have.- //- // The copy says exactly what the query measured ("with model-written- // prose" / "without") rather than the tempting shorthand "deterministic".- // A page can lack prose because its provider call failed, and calling that- // deterministic would report an outage as a design choice.- const hasSplit = prosePages != null;- const withoutProse = hasSplit ? Math.max(0, docPages - prosePages) : 0;- reads.push({- key: "docs",- label: "Documentation",- value: formatNumber(docPages),- unit: "pages",- href: `${base}/docs`,- why: hasSplit- ? `${formatNumber(prosePages)} with model-written prose, ${formatNumber(withoutProse)} built from the index`- : `Across ${formatNumber(stats.module_count)} modules`,- ...(hasSplit- ? {- bar: [- {- fraction: prosePages / docPages,- color: "var(--color-accent-fill)",- title: `${formatNumber(prosePages)} pages with model-written prose`,- },- {- fraction: withoutProse / docPages,- color: "color-mix(in srgb, var(--color-accent-fill) 30%, var(--color-bg-inset))",- title: `${formatNumber(withoutProse)} pages built from the index alone`,- },- ],- }- : {}),- });- }-- // Savings come from a CLI-written `.repowise/omissions` sidecar, so this row- // is simply absent wherever that sidecar cannot exist. Hosted composes the- // same component without it — no flag, no empty state pitching a CLI the- // viewer is not running.- const savings = summary.savings;- const savedTokens = savings.saved_input_tokens ?? 0;- if (savings.available && savedTokens > 0) {- // "Estimated" while any of the total rests on a counterfactual rather than- // a measured before and after. The two are different claims, and the row- // is too small to show the split, so it qualifies the label instead.- const inferred = savings.inferred_saved_input_tokens ?? 0;- reads.push({- key: "savings",- label: inferred > 0 ? "Estimated agent savings" : "Agent savings",- value: formatTokens(savedTokens),- ...(savings.estimated_usd_saved- ? { unit: formatCost(savings.estimated_usd_saved) }- : {}),- href: `${base}/costs`,- why:- inferred > 0- ? "Input tokens your agent did not have to read, part of it estimated"- : "Input tokens your agent did not have to read",- });- }-- if (stats.dead_export_count > 0) {- reads.push({- key: "dead-code",- label: "Dead code",- value: formatNumber(stats.dead_export_count),- unit: "exports",- href: `${base}/code-health?tab=dead-code`,- why: "Unused exports that nothing in the graph reaches",- });- }-- // Index storage is a local-disk figure. Hosted stores indexes elsewhere and- // simply never adds this row.- if (sync.index_storage_bytes) {- reads.push({- key: "index",- label: "Index",- value: formatBytes(sync.index_storage_bytes),- href: `${base}/settings`,- why: `Wiki, symbols and vectors on disk · ${Math.round(stats.doc_coverage_pct)}% average doc confidence`,- });- }-- // ── Scale ribbon: the whole first-visit orientation job, in one row ─────- const ribbon: RibbonStat[] = [];- if (statsHighlights) {- ribbon.push({ label: "Lines of code", value: formatLOC(statsHighlights.scale.total_nloc) });- }- // Linked, because the KPI strip this replaces was five links: without hrefs- // here, Files and Symbols lose their only entry point from this page.- ribbon.push(- { label: "Files", value: formatNumber(stats.file_count), href: `${base}/files` },- {- label: "Symbols",- value: formatNumber(stats.symbol_count),- href: `${base}/architecture?view=symbols`,- },- { label: "Modules", value: formatNumber(stats.module_count), href: `${base}/architecture` },- {- label: "Languages",- value: formatNumber(summary.languages.length),- href: `${base}/architecture?view=files&colorMode=language`,- },- );-- // ── Explore ────────────────────────────────────────────────────────────- // Replaces four equal-sized cards that were four different species. Every- // row carries a live figure rather than a description of the feature, which- // makes the list double as a second, quieter set of statistics.- const explore: ExploreEntry[] = [- {- key: "docs",- label: "Docs",- href: `${base}/docs`,- description: `${formatNumber(docPages)} pages across ${formatNumber(stats.module_count)} modules`,- },- {- key: "files",- label: "Files",- href: `${base}/files`,- description: `${formatNumber(stats.file_count)} files with per-file docs, health and history`,- },- {- key: "architecture",- label: "Architecture",- href: `${base}/architecture`,- description: `Dependency graph, layers, and ${formatNumber(stats.entry_point_count)} entry points`,- },- {- key: "code-health",- label: "Code health",- href: `${base}/code-health`,- description: `Per-file scores, ${formatNumber(health.open_findings)} open findings, coverage and refactoring targets`,- },- {- key: "knowledge-graph",- label: "Knowledge graph",- href: `${base}/knowledge-graph`,- description: "Entities, communities, and the paths between them",- },- {- key: "coupling",- label: "Change coupling",- href: `${base}/architecture?view=coupling`,- description: "Files that keep changing together, mined from commit history",- },- {- key: "commits",- label: "Commits",- href: `${base}/commits`,- description: "Change-risk ranked history with agent provenance",- },- {- key: "contributors",- label: "Contributors",- href: `${base}/owners`,- description: "Bus factor, per-file maintainers, and the human/agent split",- },- {- key: "stats",- label: "Stats",- href: `${base}/stats`,- description: "Size class, origin, lifetime churn, rhythm and records",- },- ];-- const langDistribution: Record<string, number> = {};- for (const l of summary.languages) langDistribution[l.language] = l.file_count;+ // Coupling and the language graph take the shared defaults; `chat` is absent+ // because this app answers that need with the ask box below instead of a+ // route, and `settings`/`costs` exist here and are what the index-size and+ // savings reads link to.+ const routes: OverviewRoutes = {+ base,+ settings: `${base}/settings`,+ costs: `${base}/costs`,+ };return (- <div className="mx-auto flex w-full max-w-[1280px] flex-col gap-6 p-[var(--page-pad)] sm:gap-8">- {header}-- <ChangeLine since={previousSnapshotAt} stats={changeStats} />-- {/* Health keeps the largest number and the leftmost position. The column- beside it carries the other reasons someone opens this page, so a- visitor who came for docs or costs finds their figure at the same- altitude rather than three scrolls down. */}- <div className="grid grid-cols-1 items-start gap-8 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-12">- <HealthLede- score={health.average_health}- maintainability={health.maintainability_average}- performance={health.performance_average}- hotspotHealth={health.hotspot_health}- hotspotCount={stats.hotspot_count}- fileCount={stats.file_count}- href={`${base}/code-health`}- LinkComponent={Link}- />- <ReadsColumn items={reads} LinkComponent={Link} />- </div>-- <StatRibbon stats={ribbon} LinkComponent={Link} />-- <OverviewSection- title="Recent activity"- action={- <SectionLink href={`${base}/commits`} LinkComponent={Link}>- All commits- </SectionLink>- }- >- <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-10">- <div className="flex min-w-0 flex-col gap-2">- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Commits- </h3>- <CommitRows- commits={commits}- hrefFor={(sha) => `${base}/commits?commit=${sha}`}- LinkComponent={Link}- />- </div>- <div className="flex min-w-0 flex-col gap-2">- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Decisions- </h3>- <DecisionRows- decisions={summary.recent_decisions.slice(0, 6)}- hrefFor={(decisionId) => `${base}/decisions/${encodeURIComponent(decisionId)}`}- LinkComponent={Link}- />- </div>- </div>- </OverviewSection>-- {summary.attention.length > 0 && (- <OverviewSection- title="Needs attention"- // No section link: these items span decisions, dead code, hotspots- // and ownership, so there is no single page that holds "all of- // them". A count that linked to just one of those would be a lie- // about where the rest live.- action={- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">- {formatNumber(summary.attention.length)} open- </span>- }- >- <AttentionRows- items={summary.attention.slice(0, 5)}- hrefFor={(item) => getDefaultHref(item, base)}- LinkComponent={Link}- />- </OverviewSection>- )}-- {summary.top_hotspots.length > 0 && (- <OverviewSection- title="Where the risk concentrates"- description="Ranked by prior bug fixes and change frequency, mined from full git history rather than from the code alone."- action={- <SectionLink href={`${base}/code-health?tab=triage`} LinkComponent={Link}>- {`All ${formatNumber(stats.hotspot_count)} hotspots`}- </SectionLink>- }- >- <HotspotTable- hotspots={summary.top_hotspots.slice(0, 5)}- hrefFor={(path) => fileEntityPath(base, path)}- LinkComponent={Link}- />- </OverviewSection>- )}-- {summary.languages.length > 0 && (- <OverviewSection- title="Composition"- action={- <SectionLink- href={`${base}/architecture?view=files&colorMode=language`}- LinkComponent={Link}- >- Open the graph- </SectionLink>- }- >- <LanguageBar distribution={langDistribution} />- </OverviewSection>- )}-- <OverviewSection title="Ask this codebase">- <AskAnythingRow repoId={id} />- </OverviewSection>-- <OverviewSection title="Explore this codebase">- <ExploreList entries={explore} LinkComponent={Link} />- </OverviewSection>- </div>+ <OverviewBody+ summary={summary}+ routes={routes}+ commits={commitsPage?.items ?? []}+ totalNloc={totalNloc}+ LinkComponent={Link}+ slots={{ header, ask: <AskAnythingRow repoId={id} /> }}+ />);}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex af4e3bcb2..56ac2d455 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -183,10 +183,13 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: stringBus factor 1</Badge>)}+ {/* Plain outline, like every other chip in this row. It used to carry+ --color-error, which made it the loudest mark on the panel and put+ it in the same colour vocabulary the health bands use. */}{fix?.magnet && (<Badgevariant="outline"- className="text-[10px] border-[var(--color-error)]/40 text-[var(--color-error)]"+ className="text-[10px]"title={`Repeatedly bug-fixed, most recently ${fix.age}.`}><Bug className="h-2.5 w-2.5 mr-1" />diff --git a/tests/unit/server/test_overview_attention.py b/tests/unit/server/test_overview_attention.pynew file mode 100644index 000000000..63b594587--- /dev/null+++ b/tests/unit/server/test_overview_attention.py@@ -0,0 +1,509 @@+"""The merged Overview attention list.++The old builder read three stores and ranked them by which store an item came+from. These cover the two properties that replaced that: severity is the+finding's own, and the total travels with the capped list.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest+from httpx import AsyncClient++from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import DocDriftFinding, SecurityFinding+from repowise.server.services.attention import PER_SOURCE_CAP, build_attention+from tests.unit.server.conftest import create_test_repo+++async def _seed_health_findings(session_factory, repo_id: str, count: int = 3) -> None:+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ {+ "file_path": f"src/mod_{i}.py",+ "biomarker_type": "brain_method",+ "severity": "critical" if i == 0 else "low",+ "function_name": f"fn_{i}",+ # 9.0 leaves a score of 1.0 (critical); 0.5 leaves 9.5.+ "health_impact": 9.0 if i == 0 else 0.5,+ "dimension": "defect",+ }+ for i in range(count)+ ],+ )+++async def _seed_security(session_factory, repo_id: str) -> None:+ async with get_session(session_factory) as session:+ session.add(+ SecurityFinding(+ repository_id=repo_id,+ file_path="config/settings.py",+ kind="aws_access_key",+ severity="high",+ snippet="AKIA…",+ line_number=12,+ commit_sha="",+ detected_at=datetime(2026, 9, 1, tzinfo=UTC),+ )+ )+ await session.commit()+++async def _seed_drift(session_factory, repo_id: str, confidence: float) -> None:+ async with get_session(session_factory) as session:+ session.add(+ DocDriftFinding(+ repository_id=repo_id,+ file_path="README.md",+ kind="missing_path",+ line_number=3,+ target="docs/gone.md",+ confidence=confidence,+ reason="names a file that is not in the tree",+ detected_at=datetime(2026, 9, 1, tzinfo=UTC),+ )+ )+ await session.commit()+++async def test_merges_every_source_and_ranks_by_the_findings_own_severity(+ client: AsyncClient, session_factory+) -> None:+ """A critical health finding outranks a high-severity stale decision.++ This is the behaviour the per-source ladder could not express: the old+ builder's top band was `high`, and every health finding would have been+ flattened into whatever constant its source was assigned.+ """+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ await _seed_health_findings(session_factory, repo_id)+ await _seed_security(session_factory, repo_id)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session,+ repo_id,+ decision_health={+ "stale_decisions": [],+ "proposed_awaiting_review": [],+ "ungoverned_hotspots": [],+ },+ knowledge_silos=[],+ )++ types = [i["type"] for i in result["items"]]+ assert "health_finding" in types+ assert "security_finding" in types++ # Critical leads. The security finding is `high`, so it sits second: within+ # a band the tie-break prefers security, but the band itself wins first.+ assert result["items"][0]["severity"] == "critical"+ assert result["items"][0]["type"] == "health_finding"+ assert result["items"][1]["type"] == "security_finding"+++async def test_security_outranks_an_equally_severe_health_finding(+ client: AsyncClient, session_factory+) -> None:+ """The tie-break, isolated from the severity sort."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ {+ "file_path": "src/a.py",+ "biomarker_type": "brain_method",+ "severity": "high",+ # 5.0 deducted leaves a score of 5.0, which is `high`.+ "health_impact": 5.0,+ "dimension": "defect",+ }+ ],+ )+ await _seed_security(session_factory, repo_id)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ high = [i for i in result["items"] if i["severity"] == "high"]+ assert [i["type"] for i in high][:2] == ["security_finding", "health_finding"]+++async def test_drift_confidence_buckets_onto_the_shared_ladder(+ client: AsyncClient, session_factory+) -> None:+ """Drift has no severity column, so confidence decides its band."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ await _seed_drift(session_factory, repo_id, confidence=0.95)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ drift = [i for i in result["items"] if i["type"] == "doc_drift"]+ assert len(drift) == 1+ # Confident, so `medium` — never `high`, which would let a stale sentence in+ # a README push a credential off a five-row list.+ assert drift[0]["severity"] == "medium"+++async def test_total_counts_everything_the_sources_hold_not_the_capped_list(+ client: AsyncClient, session_factory+) -> None:+ """`len(items)` is not the total, which is the whole reason for the summary."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ over_cap = PER_SOURCE_CAP + 5+ await _seed_health_findings(session_factory, repo_id, count=over_cap)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ health_items = [i for i in result["items"] if i["type"] == "health_finding"]+ assert len(health_items) == PER_SOURCE_CAP+ assert result["by_source"]["health_finding"] == over_cap+ assert result["total"] == over_cap+++async def test_route_serves_the_list_and_its_summary(+ client: AsyncClient, session_factory+) -> None:+ """The payload carries both halves, and the item shape survives the route."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ await _seed_health_findings(session_factory, repo_id, count=2)+ await _seed_security(session_factory, repo_id)++ resp = await client.get(f"/api/repos/{repo_id}/overview-summary")+ assert resp.status_code == 200+ body = resp.json()++ assert body["attention_summary"]["total"] >= 3+ assert body["attention_summary"]["by_source"]["security_finding"] == 1+ # `subtype` is what lets the UI name the biomarker rather than the source.+ health_rows = [i for i in body["attention"] if i["type"] == "health_finding"]+ assert health_rows and health_rows[0]["subtype"] == "brain_method"+++async def test_an_empty_repository_reports_nothing_rather_than_failing(+ client: AsyncClient, session_factory+) -> None:+ repo = await create_test_repo(client)+ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo["id"], decision_health={}, knowledge_silos=[]+ )+ assert result == {"items": [], "total": 0, "by_source": {}, "areas": []}+++async def test_one_source_cannot_own_a_band(client: AsyncClient, session_factory) -> None:+ """The spread, which a plain severity sort does not give at real scale.++ On this repository the health store holds ~16,000 open findings against+ ~20 drift findings, so a strict sort hands every visible row to health and+ the section becomes a code-health list wearing a different title.+ """+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ {+ "file_path": f"src/mod_{i}.py",+ "biomarker_type": "brain_method",+ "severity": "high",+ # Scores 5.00 to 5.35, all inside the `high` band.+ "health_impact": 5.0 - i * 0.05,+ "dimension": "defect",+ }+ for i in range(PER_SOURCE_CAP)+ ],+ )+ await _seed_security(session_factory, repo_id)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ # Security has one `high` row against health's eight, and it is not buried+ # behind all of them.+ types = [i["type"] for i in result["items"]]+ assert types[:2] == ["security_finding", "health_finding"]+++async def test_a_band_never_bleeds_into_the_one_above_it(+ client: AsyncClient, session_factory+) -> None:+ """Round-robin is within a band, so severity still decides absolutely."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ {+ "file_path": "src/bad.py",+ "biomarker_type": "brain_method",+ "severity": "critical",+ "health_impact": 9.0,+ "dimension": "defect",+ },+ {+ "file_path": "src/also_bad.py",+ "biomarker_type": "god_class",+ "severity": "critical",+ "health_impact": 8.0,+ "dimension": "defect",+ },+ ],+ )+ # `high`, and it must not be pulled above either critical just because it+ # is the only row its source has.+ await _seed_security(session_factory, repo_id)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ assert [i["severity"] for i in result["items"][:3]] == ["critical", "critical", "high"]+++async def test_test_files_are_out_of_scope(client: AsyncClient, session_factory) -> None:+ """Production scope. A test file cannot be the most urgent thing in a repo."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_metrics(+ session,+ repo_id,+ [+ {"file_path": "tests/test_thing.py", "nloc": 100, "is_test": True},+ {"file_path": "src/thing.py", "nloc": 100, "is_test": False},+ ],+ )+ await crud.save_health_findings(+ session,+ repo_id,+ [+ {+ "file_path": "tests/test_thing.py",+ "biomarker_type": "brain_method",+ "severity": "critical",+ "health_impact": 9.0,+ "dimension": "defect",+ },+ {+ "file_path": "src/thing.py",+ "biomarker_type": "brain_method",+ "severity": "low",+ "health_impact": 0.5,+ "dimension": "defect",+ },+ ],+ )++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ paths = [i["target_id"] for i in result["items"]]+ assert "src/thing.py" in paths+ # Critical, highest impact, and still absent: scope wins over severity.+ assert "tests/test_thing.py" not in paths+ assert result["by_source"]["health_finding"] == 1+++async def test_areas_roll_up_and_lead_with_the_worst_item(+ client: AsyncClient, session_factory+) -> None:+ """Every area gets a row, whatever the volume in the areas beside it."""+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ await _seed_health_findings(session_factory, repo_id, count=PER_SOURCE_CAP)+ await _seed_security(session_factory, repo_id)+ await _seed_drift(session_factory, repo_id, confidence=0.95)++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ areas = {a["key"]: a for a in result["areas"]}+ # Drift holds one finding against health's eight and still gets a row —+ # the failure the ranked item list has by construction.+ assert set(areas) == {"security", "health", "doc_drift"}+ assert areas["health"]["total"] == PER_SOURCE_CAP+ assert areas["health"]["severity"] == "critical"+ assert areas["health"]["lead"]["subtype"] == "brain_method"+ assert areas["doc_drift"]["total"] == 1+ # Fixed display order, not severity order.+ assert [a["key"] for a in result["areas"]] == ["security", "health", "doc_drift"]+++async def test_the_lead_is_the_heaviest_item_not_the_first_alphabetically(+ client: AsyncClient, session_factory+) -> None:+ """The tie-break inside a band is impact, not the item id.++ It used to fall through to `id`, so the lead of an area was whichever+ member of its worst band sorted first alphabetically — and the health query+ fetches in `health_impact DESC`, an ordering the rank pass then discarded.+ """+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ # Sorts first by path, and matters least.+ {+ "file_path": "src/aaa.py",+ "biomarker_type": "brain_method",+ "severity": "critical",+ "health_impact": 0.2,+ "dimension": "defect",+ },+ {+ "file_path": "src/zzz.py",+ "biomarker_type": "god_class",+ "severity": "critical",+ "health_impact": 8.0,+ "dimension": "defect",+ },+ ],+ )++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ health = next(a for a in result["areas"] if a["key"] == "health")+ assert health["lead"]["target_id"] == "src/zzz.py"+ assert result["items"][0]["target_id"] == "src/zzz.py"+++async def test_a_dormant_silo_never_leads_over_an_active_one(+ client: AsyncClient, session_factory+) -> None:+ """Sole ownership only costs something on code that still changes."""+ repo = await create_test_repo(client)+ silos = [+ {+ "file_path": "docker/entrypoint.sh",+ "owner_email": "[email protected]",+ "owner_pct": 0.95,+ "commit_count_90d": 0,+ "is_hotspot": False,+ },+ {+ "file_path": "src/core/engine.py",+ "owner_email": "[email protected]",+ "owner_pct": 0.85,+ "commit_count_90d": 40,+ "is_hotspot": True,+ },+ ]+ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo["id"], decision_health={}, knowledge_silos=silos+ )++ ownership = next(a for a in result["areas"] if a["key"] == "ownership")+ # Lower concentration, far more activity, and it leads.+ assert ownership["lead"]["target_id"] == "src/core/engine.py"+ assert "40 commits in 90d" in ownership["lead"]["description"]+++async def test_health_leads_with_the_worst_file_not_the_worst_finding(+ client: AsyncClient, session_factory+) -> None:+ """`health_impact` saturates, so ranking findings barely orders the top.++ A file carrying many findings outranks a single finding that happens to sit+ on the per-finding cap, which is what the file's own score already says.+ """+ repo = await create_test_repo(client)+ repo_id = repo["id"]+ async with get_session(session_factory) as session:+ await crud.save_health_findings(+ session,+ repo_id,+ [+ # One finding, on the cap, and the worst band.+ {+ "file_path": "src/one_bad_function.py",+ "biomarker_type": "nested_complexity",+ "severity": "critical",+ "health_impact": 2.5,+ "dimension": "defect",+ },+ # Six findings totalling far more deduction.+ *[+ {+ "file_path": "src/app.py",+ "biomarker_type": "complex_method" if i else "god_class",+ "severity": "high",+ "health_impact": 2.0 if i == 0 else 1.5,+ "dimension": "defect",+ }+ for i in range(6)+ ],+ ],+ )++ async with get_session(session_factory) as session:+ result = await build_attention(+ session, repo_id, decision_health={}, knowledge_silos=[]+ )++ health = [i for i in result["items"] if i["type"] == "health_finding"]+ # One row per file, not per finding.+ assert len(health) == 2+ assert health[0]["target_id"] == "src/app.py"+ assert "6 findings" in health[0]["description"]+ # Named by its own heaviest biomarker.+ assert health[0]["subtype"] == "god_class"+ # Severity describes the file: 9.5 deducted leaves a score of 0.5.+ assert health[0]["severity"] == "critical"+ # And the single capped finding leaves a score of 7.5, which is not.+ assert health[1]["severity"] == "low"+ # The count is still findings, so the row can say how much the area holds.+ assert result["by_source"]["health_finding"] == 7