Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(attention): move the ranking fold into core over plain records (#2506)

Raghav Chamadiyaccd77cf58869
diff --git a/packages/core/src/repowise/core/analysis/attention/__init__.py b/packages/core/src/repowise/core/analysis/attention/__init__.py
new file mode 100644
index 000000000..b695e3927
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/attention/__init__.py
@@ -0,0 +1,50 @@
+"""The ranked attention list, as a fold over per-source results.
+
+Nothing in this package imports ``repowise.server`` or a database session.
+"""
+
+from __future__ import annotations
+
+from .compose import (
+ AREA_OF,
+ AREA_ORDER,
+ ATTENTION_ITEM_TYPES,
+ DRIFT_CONFIDENT,
+ PER_SOURCE_CAP,
+ SEVERITY_RANK,
+ SOURCE_RANK,
+ WEIGHT_KEY,
+ AttentionArea,
+ AttentionItemType,
+ AttentionSource,
+ AttentionView,
+ DecisionAttentionInput,
+ SourceResult,
+ compose_attention,
+ decision_source,
+ severity_of_drift,
+ severity_of_file_score,
+ silo_source,
+)
+
+__all__ = [
+ "AREA_OF",
+ "AREA_ORDER",
+ "ATTENTION_ITEM_TYPES",
+ "DRIFT_CONFIDENT",
+ "PER_SOURCE_CAP",
+ "SEVERITY_RANK",
+ "SOURCE_RANK",
+ "WEIGHT_KEY",
+ "AttentionArea",
+ "AttentionItemType",
+ "AttentionSource",
+ "AttentionView",
+ "DecisionAttentionInput",
+ "SourceResult",
+ "compose_attention",
+ "decision_source",
+ "severity_of_drift",
+ "severity_of_file_score",
+ "silo_source",
+]
diff --git a/packages/core/src/repowise/core/analysis/attention/compose.py b/packages/core/src/repowise/core/analysis/attention/compose.py
new file mode 100644
index 000000000..8cf9b71d3
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/attention/compose.py
@@ -0,0 +1,441 @@
+"""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:`compose_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.
+
+Pure: no I/O, no session, no clock. Fetching each source is the caller's job;
+the fold takes one :class:`SourceResult` per source.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any, Literal, TypedDict, get_args
+
+from repowise.core.analysis.health.grading import HealthBand, band_for
+
+# Mirrored by the TS union in ``packages/ui/src/dashboard/attention-href.ts``;
+# ``test_wire_vocabulary_parity.py`` fails when the two disagree.
+AttentionItemType = Literal[
+ "stale_decision",
+ "knowledge_silo",
+ "ungoverned_hotspot",
+ "dead_code",
+ "proposed_decision",
+ "health_finding",
+ "security_finding",
+ "doc_drift",
+ "refactoring",
+]
+ATTENTION_ITEM_TYPES: frozenset[str] = frozenset(get_args(AttentionItemType))
+
+#: One key per store. The three decision lanes share one total and detail, so
+#: they arrive, and are counted in ``by_source``, under ``decisions``.
+AttentionSource = Literal[
+ "health_finding",
+ "security_finding",
+ "refactoring",
+ "doc_drift",
+ "dead_code",
+ "decisions",
+ "knowledge_silo",
+]
+
+#: 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
+
+
+@dataclass(frozen=True, slots=True)
+class SourceResult:
+ """One store's contribution: its top items, its full count, and a breakdown.
+
+ The producer owns the cap: ``items`` holds at most :data:`PER_SOURCE_CAP`
+ rows per lane, already in that store's own best-first order, while ``total`` counts
+ every row the store holds under the same scope. Each item is a dict with
+ ``id``, ``type``, ``title``, ``description``, ``severity``, ``target_id``,
+ and optionally ``subtype`` and ``weight`` (see :data:`WEIGHT_KEY`).
+ ``detail`` names what ``total`` is made of, where one number would mislead.
+ """
+
+ items: tuple[Mapping[str, Any], ...]
+ total: int
+ detail: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class DecisionAttentionInput:
+ """The two fields of a decision record the attention list shows.
+
+ No staleness score: :func:`decision_source` never re-sorts a lane, so a
+ producer without one passes the stale lane in whatever order it trusts.
+ """
+
+ id: str
+ title: str
+
+
+class AttentionArea(TypedDict):
+ key: str
+ total: int
+ severity: str
+ detail: str
+ lead: dict[str, Any] | None
+
+
+class AttentionView(TypedDict):
+ items: list[Mapping[str, Any]]
+ total: int
+ by_source: dict[str, int]
+ areas: list[AttentionArea]
+
+
+#: 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"
+
+
+def decision_source(
+ stale: Sequence[DecisionAttentionInput],
+ proposed: Sequence[DecisionAttentionInput],
+ ungoverned: Sequence[str],
+) -> SourceResult:
+ """Decision-record problems, in the order the caller 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] = []
+
+ # 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 SourceResult(
+ tuple(items), len(stale) + len(proposed) + len(ungoverned), " · ".join(parts)
+ )
+
+
+def silo_source(knowledge_silos: Sequence[Mapping[str, Any]]) -> SourceResult:
+ """Files whose history sits with one person.
+
+ Each silo needs ``file_path`` and ``owner_pct``; ``commit_count_90d`` is
+ optional and read as dormant when absent.
+ """
+ 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 SourceResult(tuple(items), len(knowledge_silos), "")
+
+
+def _rank(items: list[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
+ """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[Mapping[str, Any]] = []
+ for band in sorted({i["severity"] for i in items}, key=lambda s: SEVERITY_RANK.get(s, 99)):
+ buckets: dict[str, list[Mapping[str, Any]]] = {}
+ 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[Mapping[str, Any]], by_source: dict[str, int], details: dict[str, str]
+) -> list[AttentionArea]:
+ """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, Mapping[str, Any]] = {}
+ for item in items: # already ranked worst-first
+ leads.setdefault(AREA_OF.get(item["type"], item["type"]), item)
+
+ out: list[AttentionArea] = []
+ 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
+
+
+def compose_attention(sources: Mapping[AttentionSource, SourceResult]) -> AttentionView:
+ """Every attention source, merged and ranked worst-first.
+
+ ``total`` counts everything the sources hold, not the capped list, so a
+ caller rendering five rows can honestly say "5 of 231". A source with a
+ zero total is left out of ``by_source``; a source the caller could not
+ fetch is simply absent from ``sources``. ``by_source`` follows the order
+ of ``sources``.
+ """
+ by_source: dict[str, int] = {}
+ details: dict[str, str] = {}
+ items: list[Mapping[str, Any]] = []
+ for source, result in sources.items():
+ if result.total:
+ by_source[source] = result.total
+ if result.detail:
+ details[source] = result.detail
+ items.extend(result.items)
+
+ 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/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index ab0ed5682..6a8f4a665 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -427,7 +427,7 @@ async def overview_summary(
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.
+ # `core/analysis/attention` for what changed and why.
attention_result = await build_attention(
session,
repo_id,
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index 0fc9f500a..af97492b8 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -1,40 +1,29 @@
-"""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.
+"""Fetch side of the Overview attention list.
+
+The ranking lives in :mod:`repowise.core.analysis.attention`; this module reads
+each store into a :class:`SourceResult` and hands them to the fold.
"""
from __future__ import annotations
-from typing import Any
+from collections.abc import Awaitable, Callable
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.health.grading import HealthBand, band_for
+from repowise.core.analysis.attention import (
+ PER_SOURCE_CAP,
+ SEVERITY_RANK,
+ AttentionSource,
+ AttentionView,
+ DecisionAttentionInput,
+ SourceResult,
+ compose_attention,
+ decision_source,
+ severity_of_drift,
+ severity_of_file_score,
+ silo_source,
+)
from repowise.core.persistence.models import (
DeadCodeFinding,
DocDriftFinding,
@@ -44,47 +33,7 @@ from repowise.core.persistence.models import (
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
+__all__ = ["PER_SOURCE_CAP", "build_attention"]
def _test_paths(repo_id: str):
@@ -107,44 +56,6 @@ def _test_paths(repo_id: str):
)
-#: 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.
@@ -208,7 +119,7 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
f"{row.findings} finding{'' if row.findings == 1 else 's'}"
f" · {float(row.impact or 0.0):.1f} deducted"
),
- "severity": _severity_of_file_score(
+ "severity": severity_of_file_score(
max(1.0, 10.0 - float(row.impact or 0.0))
),
"target_id": row.file_path,
@@ -326,7 +237,7 @@ async def _drift_items(session: AsyncSession, repo_id: str) -> tuple[list[dict],
"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),
+ "severity": severity_of_drift(row.confidence),
"target_id": row.file_path,
"subtype": row.kind,
"weight": float(row.confidence or 0.0),
@@ -446,220 +357,30 @@ async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[di
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 _decision_source(decision_health: dict) -> SourceResult:
+ """Adapt ``get_decision_health_summary`` rows to the fold's plain records."""
-def _rank(items: list[dict]) -> list[dict]:
- """Worst band first, and inside a band one item per source before seconds.
+ def lane(key: str) -> list[DecisionAttentionInput]:
+ return [
+ DecisionAttentionInput(id=d.id, title=d.title)
+ for d in decision_health.get(key, []) or []
+ ]
- 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.
+ return decision_source(
+ lane("stale_decisions"),
+ lane("proposed_awaiting_review"),
+ decision_health.get("ungoverned_hotspots", []) or [],
+ )
- 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
+_Fetcher = Callable[[AsyncSession, str], Awaitable[tuple[list[dict], int, str]]]
+_FETCHERS: tuple[tuple[AttentionSource, _Fetcher], ...] = (
+ ("health_finding", _health_items),
+ ("security_finding", _security_items),
+ ("refactoring", _refactoring_items),
+ ("doc_drift", _drift_items),
+ ("dead_code", _dead_code_items),
+)
async def build_attention(
@@ -668,12 +389,11 @@ async def build_attention(
*,
decision_health: dict,
knowledge_silos: list[dict],
-) -> dict[str, Any]:
+) -> AttentionView:
"""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".
+ Returns ``{"items": [...], "total": int, "by_source": {type: count},
+ "areas": [...]}``; see :func:`compose_attention`.
``decision_health`` and ``knowledge_silos`` are passed in rather than
fetched: the Overview route already has both in hand for other parts of its
@@ -685,38 +405,13 @@ async def build_attention(
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:
+ sources: dict[AttentionSource, SourceResult] = {}
+ for key, fetch in _FETCHERS:
try:
- got, total, detail = await fn(session, repo_id)
+ items, total, detail = await fetch(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),
- }
+ continue
+ sources[key] = SourceResult(tuple(items), total, detail)
+ sources["decisions"] = _decision_source(decision_health)
+ sources["knowledge_silo"] = silo_source(knowledge_silos)
+ return compose_attention(sources)
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
index d393fe346..eaf2a5c1e 100644
--- a/packages/types/src/overview.ts
+++ b/packages/types/src/overview.ts
@@ -127,7 +127,7 @@ export interface OverviewAttentionItem {
* 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`.
+ * server-side. See `core/analysis/attention/compose.py`.
*/
severity: HealthSeverity;
/** Decision id, file path, … — what the item points at. */
diff --git a/packages/ui/src/dashboard/attention-href.ts b/packages/ui/src/dashboard/attention-href.ts
index 90195d6ba..4cc7f8f22 100644
--- a/packages/ui/src/dashboard/attention-href.ts
+++ b/packages/ui/src/dashboard/attention-href.ts
@@ -1,5 +1,6 @@
import { fileEntityPath } from "../shared/entity/routes";
+/** Mirrors `AttentionItemType` in `core/analysis/attention/compose.py`; a Python test pins it. */
export type AttentionItemType =
| "stale_decision"
| "knowledge_silo"
@@ -36,7 +37,7 @@ 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
+ * `core/analysis/attention/compose.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.
diff --git a/tests/unit/analysis/test_attention_compose.py b/tests/unit/analysis/test_attention_compose.py
new file mode 100644
index 000000000..0caf29bde
--- /dev/null
+++ b/tests/unit/analysis/test_attention_compose.py
@@ -0,0 +1,98 @@
+"""The attention fold over plain records, with no session behind it."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.attention import (
+ AREA_OF,
+ AREA_ORDER,
+ ATTENTION_ITEM_TYPES,
+ PER_SOURCE_CAP,
+ SOURCE_RANK,
+ DecisionAttentionInput,
+ SourceResult,
+ compose_attention,
+ decision_source,
+ severity_of_file_score,
+ silo_source,
+)
+
+
+def _health(path: str, severity: str, weight: float) -> dict:
+ return {
+ "id": f"health-{path}",
+ "type": "health_finding",
+ "title": path,
+ "description": "",
+ "severity": severity,
+ "target_id": path,
+ "subtype": "brain_method",
+ "weight": weight,
+ }
+
+
+def test_composes_from_plain_records() -> None:
+ view = compose_attention(
+ {
+ "health_finding": SourceResult(
+ (_health("src/a.py", "critical", 9.0), _health("src/b.py", "low", 0.5)), 40
+ ),
+ "decisions": decision_source(
+ [DecisionAttentionInput(id="d1", title="Stale one")], [], ["src/hot.py"]
+ ),
+ "knowledge_silo": silo_source(
+ [{"file_path": "src/a.py", "owner_pct": 0.9, "commit_count_90d": 3}]
+ ),
+ }
+ )
+
+ assert [i["id"] for i in view["items"]] == [
+ "health-src/a.py",
+ "stale-d1",
+ "ungoverned-src/hot.py",
+ "silo-src/a.py",
+ "health-src/b.py",
+ ]
+ assert view["by_source"] == {"health_finding": 40, "decisions": 2, "knowledge_silo": 1}
+ assert view["total"] == 43
+ decisions = next(a for a in view["areas"] if a["key"] == "decisions")
+ assert decisions["detail"] == "1 drifting from the code · 1 hotspots ungoverned"
+
+
+def test_total_comes_from_the_producer_not_the_items() -> None:
+ """A producer that capped its rows still reports the whole store."""
+ view = compose_attention({"dead_code": SourceResult((), 12)})
+ assert view["by_source"] == {"dead_code": 12}
+ assert view["areas"][0]["lead"] is None
+
+
+def test_decision_lanes_truncate_without_reordering() -> None:
+ n = PER_SOURCE_CAP + 3
+ records = [DecisionAttentionInput(id=f"d{i}", title=f"t{i}") for i in range(n)]
+ paths = [f"src/{i}.py" for i in range(n)]
+ result = decision_source(records, records, paths)
+ kept = [d.id for d in records[:PER_SOURCE_CAP]]
+ by_type: dict[str, list[str]] = {}
+ for item in result.items:
+ by_type.setdefault(item["type"], []).append(item["target_id"])
+ assert by_type == {
+ "stale_decision": kept,
+ "proposed_decision": kept,
+ "ungoverned_hotspot": paths[:PER_SOURCE_CAP],
+ }
+ assert result.total == 3 * n
+
+
+def test_every_item_type_is_ranked_and_rolled_up() -> None:
+ """A type missing here would rank last or roll into an area never rendered."""
+ assert set(SOURCE_RANK) == set(AREA_OF) == ATTENTION_ITEM_TYPES
+ assert set(AREA_OF.values()) == set(AREA_ORDER)
+
+
+ ("score", "severity"),
+ [(1.0, "critical"), (4.5, "high"), (6.0, "medium"), (7.5, "low"), (9.0, "low")],
+)
+def test_file_score_maps_every_band(score: float, severity: str) -> None:
+ assert severity_of_file_score(score) == severity
diff --git a/tests/unit/server/golden/attention_build.json b/tests/unit/server/golden/attention_build.json
new file mode 100644
index 000000000..2a3747e16
--- /dev/null
+++ b/tests/unit/server/golden/attention_build.json
@@ -0,0 +1,297 @@
+{
+ "items": [
+ {
+ "id": "health-src/core.py",
+ "type": "health_finding",
+ "title": "src/core.py",
+ "description": "2 findings \u00b7 9.5 deducted",
+ "severity": "critical",
+ "target_id": "src/core.py",
+ "subtype": "god_class",
+ "weight": 9.5
+ },
+ {
+ "id": "security-1",
+ "type": "security_finding",
+ "title": "config/settings.py",
+ "description": "aws_access_key",
+ "severity": "high",
+ "target_id": "config/settings.py",
+ "subtype": "aws_access_key",
+ "weight": 1.0
+ },
+ {
+ "weight": 8.0,
+ "id": "stale-d-stale-1",
+ "type": "stale_decision",
+ "title": "Use SQLite for the local store",
+ "description": "Active decision drifting from the code it governs",
+ "severity": "high",
+ "target_id": "d-stale-1"
+ },
+ {
+ "id": "security-2",
+ "type": "security_finding",
+ "title": "old/keys.py",
+ "description": "hardcoded_secret in commit abcdef1",
+ "severity": "high",
+ "target_id": "old/keys.py",
+ "subtype": "hardcoded_secret",
+ "weight": 0.0
+ },
+ {
+ "weight": 7.0,
+ "id": "stale-d-stale-2",
+ "type": "stale_decision",
+ "title": "One worker per repo",
+ "description": "Active decision drifting from the code it governs",
+ "severity": "high",
+ "target_id": "d-stale-2"
+ },
+ {
+ "id": "refactor-ref1",
+ "type": "refactoring",
+ "title": "Engine.run",
+ "description": "+1.8 health, M effort \u00b7 src/core.py",
+ "severity": "medium",
+ "target_id": "src/core.py",
+ "subtype": "extract_method",
+ "weight": 1.8
+ },
+ {
+ "weight": 8.0,
+ "id": "ungoverned-src/core.py",
+ "type": "ungoverned_hotspot",
+ "title": "src/core.py",
+ "description": "High-churn file with no governing decision",
+ "severity": "medium",
+ "target_id": "src/core.py"
+ },
+ {
+ "id": "drift-1",
+ "type": "doc_drift",
+ "title": "README.md",
+ "description": "names a file that is not in the tree",
+ "severity": "medium",
+ "target_id": "README.md",
+ "subtype": "missing_path",
+ "weight": 0.95
+ },
+ {
+ "weight": 8.0,
+ "id": "proposed-d-prop-1",
+ "type": "proposed_decision",
+ "title": "Cache the graph",
+ "description": "Auto-proposed decision awaiting review",
+ "severity": "medium",
+ "target_id": "d-prop-1"
+ },
+ {
+ "id": "silo-src/core.py",
+ "type": "knowledge_silo",
+ "title": "src/core.py",
+ "description": "90% single-owner concentration, 25 commits in 90d",
+ "severity": "medium",
+ "target_id": "src/core.py",
+ "weight": 25.9
+ },
+ {
+ "weight": 7.0,
+ "id": "ungoverned-src/api.py",
+ "type": "ungoverned_hotspot",
+ "title": "src/api.py",
+ "description": "High-churn file with no governing decision",
+ "severity": "medium",
+ "target_id": "src/api.py"
+ },
+ {
+ "id": "silo-docker/entry.sh",
+ "type": "knowledge_silo",
+ "title": "docker/entry.sh",
+ "description": "100% single-owner concentration, not touched in 90 days",
+ "severity": "medium",
+ "target_id": "docker/entry.sh",
+ "weight": 1.0
+ },
+ {
+ "id": "security-3",
+ "type": "security_finding",
+ "title": "src/run.py",
+ "description": "eval_call",
+ "severity": "low",
+ "target_id": "src/run.py",
+ "subtype": "eval_call",
+ "weight": 1.0
+ },
+ {
+ "id": "health-src/util.py",
+ "type": "health_finding",
+ "title": "src/util.py",
+ "description": "1 finding \u00b7 3.0 deducted",
+ "severity": "low",
+ "target_id": "src/util.py",
+ "subtype": "nested_complexity",
+ "weight": 3.0
+ },
+ {
+ "id": "refactor-ref2",
+ "type": "refactoring",
+ "title": "src/util.py",
+ "description": "+0.6 health \u00b7 src/util.py",
+ "severity": "low",
+ "target_id": "src/util.py",
+ "subtype": "split_class",
+ "weight": 0.6
+ },
+ {
+ "id": "drift-2",
+ "type": "doc_drift",
+ "title": "docs/setup.md",
+ "description": "missing_symbol no longer matches the tree",
+ "severity": "low",
+ "target_id": "docs/setup.md",
+ "subtype": "missing_symbol",
+ "weight": 0.5
+ },
+ {
+ "id": "dead-dead1",
+ "type": "dead_code",
+ "title": "old_helper",
+ "description": "Unreachable function (12 lines)",
+ "severity": "low",
+ "target_id": "src/legacy.py",
+ "subtype": "unused_export",
+ "weight": 0.9
+ },
+ {
+ "id": "health-src/tiny.py",
+ "type": "health_finding",
+ "title": "src/tiny.py",
+ "description": "1 finding \u00b7 0.4 deducted",
+ "severity": "low",
+ "target_id": "src/tiny.py",
+ "subtype": "long_method",
+ "weight": 0.4
+ },
+ {
+ "id": "dead-dead2",
+ "type": "dead_code",
+ "title": "src/orphan.py",
+ "description": "Unreachable symbol (40 lines)",
+ "severity": "low",
+ "target_id": "src/orphan.py",
+ "subtype": "unreachable_file",
+ "weight": 0.7
+ }
+ ],
+ "total": 20,
+ "by_source": {
+ "health_finding": 4,
+ "security_finding": 3,
+ "refactoring": 2,
+ "doc_drift": 2,
+ "dead_code": 2,
+ "decisions": 5,
+ "knowledge_silo": 2
+ },
+ "areas": [
+ {
+ "key": "security",
+ "total": 3,
+ "severity": "high",
+ "detail": "2 in the working tree, 1 in git history",
+ "lead": {
+ "title": "config/settings.py",
+ "description": "aws_access_key",
+ "type": "security_finding",
+ "target_id": "config/settings.py",
+ "subtype": "aws_access_key",
+ "severity": "high"
+ }
+ },
+ {
+ "key": "health",
+ "total": 4,
+ "severity": "critical",
+ "detail": "",
+ "lead": {
+ "title": "src/core.py",
+ "description": "2 findings \u00b7 9.5 deducted",
+ "type": "health_finding",
+ "target_id": "src/core.py",
+ "subtype": "god_class",
+ "severity": "critical"
+ }
+ },
+ {
+ "key": "refactoring",
+ "total": 2,
+ "severity": "medium",
+ "detail": "",
+ "lead": {
+ "title": "Engine.run",
+ "description": "+1.8 health, M effort \u00b7 src/core.py",
+ "type": "refactoring",
+ "target_id": "src/core.py",
+ "subtype": "extract_method",
+ "severity": "medium"
+ }
+ },
+ {
+ "key": "doc_drift",
+ "total": 2,
+ "severity": "medium",
+ "detail": "",
+ "lead": {
+ "title": "README.md",
+ "description": "names a file that is not in the tree",
+ "type": "doc_drift",
+ "target_id": "README.md",
+ "subtype": "missing_path",
+ "severity": "medium"
+ }
+ },
+ {
+ "key": "decisions",
+ "total": 5,
+ "severity": "high",
+ "detail": "2 drifting from the code \u00b7 1 awaiting review \u00b7 2 hotspots ungoverned",
+ "lead": {
+ "title": "Use SQLite for the local store",
+ "description": "Active decision drifting from the code it governs",
+ "type": "stale_decision",
+ "target_id": "d-stale-1",
+ "subtype": null,
+ "severity": "high"
+ }
+ },
+ {
+ "key": "ownership",
+ "total": 2,
+ "severity": "medium",
+ "detail": "",
+ "lead": {
+ "title": "src/core.py",
+ "description": "90% single-owner concentration, 25 commits in 90d",
+ "type": "knowledge_silo",
+ "target_id": "src/core.py",
+ "subtype": null,
+ "severity": "medium"
+ }
+ },
+ {
+ "key": "dead_code",
+ "total": 2,
+ "severity": "low",
+ "detail": "",
+ "lead": {
+ "title": "old_helper",
+ "description": "Unreachable function (12 lines)",
+ "type": "dead_code",
+ "target_id": "src/legacy.py",
+ "subtype": "unused_export",
+ "severity": "low"
+ }
+ }
+ ]
+}
diff --git a/tests/unit/server/test_attention_golden.py b/tests/unit/server/test_attention_golden.py
new file mode 100644
index 000000000..dfa9f3ef7
--- /dev/null
+++ b/tests/unit/server/test_attention_golden.py
@@ -0,0 +1,231 @@
+"""Golden output of ``build_attention`` with every source populated.
+
+Pins items, order, totals, details and areas exactly, so moving the fold
+between packages cannot change what Overview serves. Rewrite with
+``REPOWISE_REWRITE_GOLDEN=1`` only for an intended behaviour change.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from datetime import UTC, datetime
+from pathlib import Path
+from types import SimpleNamespace
+
+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 (
+ DeadCodeFinding,
+ DocDriftFinding,
+ RefactoringSuggestion,
+ SecurityFinding,
+)
+from repowise.server.services import attention
+from repowise.server.services.attention import build_attention
+from tests.unit.server.conftest import create_test_repo
+
+GOLDEN = Path(__file__).parent / "golden" / "attention_build.json"
+_AT = datetime(2026, 9, 1, tzinfo=UTC)
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ await crud.save_health_metrics(
+ session,
+ repo_id,
+ [
+ {"file_path": "tests/test_core.py", "nloc": 50, "is_test": True},
+ {"file_path": "src/core.py", "nloc": 400, "is_test": False},
+ ],
+ )
+ await crud.save_health_findings(
+ session,
+ repo_id,
+ [
+ {
+ "file_path": path,
+ "biomarker_type": biomarker,
+ "severity": "high",
+ "health_impact": impact,
+ "dimension": "defect",
+ }
+ for path, biomarker, impact in [
+ ("src/core.py", "brain_method", 4.0),
+ ("src/core.py", "god_class", 5.5),
+ ("src/util.py", "nested_complexity", 3.0),
+ ("src/tiny.py", "long_method", 0.4),
+ ("tests/test_core.py", "mock_saturation", 9.0),
+ ]
+ ],
+ )
+ session.add_all(
+ [
+ SecurityFinding(
+ id=1,
+ repository_id=repo_id,
+ file_path="config/settings.py",
+ kind="aws_access_key",
+ severity="high",
+ snippet="AKIA****",
+ line_number=12,
+ commit_sha="",
+ detected_at=_AT,
+ ),
+ SecurityFinding(
+ id=2,
+ repository_id=repo_id,
+ file_path="old/keys.py",
+ kind="hardcoded_secret",
+ severity="high",
+ snippet="",
+ line_number=3,
+ commit_sha="abcdef1234567",
+ detected_at=_AT,
+ ),
+ SecurityFinding(
+ id=3,
+ repository_id=repo_id,
+ file_path="src/run.py",
+ kind="eval_call",
+ severity="low",
+ snippet="eval(x)",
+ line_number=7,
+ commit_sha="",
+ detected_at=_AT,
+ ),
+ DocDriftFinding(
+ id=1,
+ repository_id=repo_id,
+ file_path="README.md",
+ kind="missing_path",
+ line_number=3,
+ target="docs/gone.md",
+ confidence=0.95,
+ reason="names a file that is not in the tree",
+ detected_at=_AT,
+ ),
+ DocDriftFinding(
+ id=2,
+ repository_id=repo_id,
+ file_path="docs/setup.md",
+ kind="missing_symbol",
+ line_number=9,
+ target="old_fn",
+ confidence=0.5,
+ reason="",
+ detected_at=_AT,
+ ),
+ RefactoringSuggestion(
+ id="ref1",
+ repository_id=repo_id,
+ refactoring_type="extract_method",
+ file_path="src/core.py",
+ target_symbol="Engine.run",
+ impact_delta=1.8,
+ effort_bucket="M",
+ ),
+ RefactoringSuggestion(
+ id="ref2",
+ repository_id=repo_id,
+ refactoring_type="split_class",
+ file_path="src/util.py",
+ target_symbol="",
+ impact_delta=0.6,
+ effort_bucket="",
+ ),
+ DeadCodeFinding(
+ id="dead1",
+ repository_id=repo_id,
+ kind="unused_export",
+ file_path="src/legacy.py",
+ symbol_name="old_helper",
+ symbol_kind="function",
+ confidence=0.9,
+ lines=12,
+ safe_to_delete=True,
+ ),
+ DeadCodeFinding(
+ id="dead2",
+ repository_id=repo_id,
+ kind="unreachable_file",
+ file_path="src/orphan.py",
+ symbol_name=None,
+ symbol_kind=None,
+ confidence=0.7,
+ lines=40,
+ safe_to_delete=True,
+ ),
+ ]
+ )
+ await session.commit()
+
+
+_DECISION_HEALTH = {
+ "stale_decisions": [
+ SimpleNamespace(id="d-stale-1", title="Use SQLite for the local store"),
+ SimpleNamespace(id="d-stale-2", title="One worker per repo"),
+ ],
+ "proposed_awaiting_review": [SimpleNamespace(id="d-prop-1", title="Cache the graph")],
+ "ungoverned_hotspots": ["src/core.py", "src/api.py"],
+}
+
+_SILOS = [
+ {"file_path": "src/core.py", "owner_pct": 0.9, "commit_count_90d": 25},
+ {"file_path": "docker/entry.sh", "owner_pct": 1.0, "commit_count_90d": 0},
+]
+
+
+async def test_build_attention_matches_the_golden(
+ client: AsyncClient, session_factory
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(session_factory, repo["id"])
+
+ async with get_session(session_factory) as session:
+ result = await build_attention(
+ session,
+ repo["id"],
+ decision_health=_DECISION_HEALTH,
+ knowledge_silos=_SILOS,
+ )
+
+ if os.environ.get("REPOWISE_REWRITE_GOLDEN"):
+ GOLDEN.parent.mkdir(exist_ok=True)
+ GOLDEN.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8", newline="\n")
+ pytest.skip("golden rewritten")
+ golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
+ assert result == golden
+ # Dict equality ignores order; the wire keeps it.
+ assert list(result["by_source"]) == list(golden["by_source"])
+
+
+async def test_a_source_that_raises_is_dropped_with_its_count(
+ client: AsyncClient, session_factory, monkeypatch
+) -> None:
+ async def boom(session, repo_id):
+ raise RuntimeError("table missing")
+
+ fetchers = tuple(
+ (key, boom if key == "security_finding" else fetch) for key, fetch in attention._FETCHERS
+ )
+ monkeypatch.setattr(attention, "_FETCHERS", fetchers)
+ repo = await create_test_repo(client)
+ await _seed(session_factory, repo["id"])
+
+ async with get_session(session_factory) as session:
+ result = await build_attention(
+ session, repo["id"], decision_health=_DECISION_HEALTH, knowledge_silos=_SILOS
+ )
+
+ golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
+ assert "security_finding" not in result["by_source"]
+ assert result["by_source"] == {
+ k: v for k, v in golden["by_source"].items() if k != "security_finding"
+ }
+ assert all(i["type"] != "security_finding" for i in result["items"])
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index 5dbc11b4a..2902b1c6a 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -1,7 +1,8 @@
"""The closed vocabularies cross a language boundary, so pin both ends.
-``ResolutionOrigin``, ``FlowTermination`` and ``UnmatchedReason`` are declared
-in Python and copied into ``packages/types`` for the web surfaces. Nothing else
+``ResolutionOrigin``, ``FlowTermination``, ``UnmatchedReason`` and
+``AttentionItemType`` are declared in Python and copied into ``packages/types``
+(and ``packages/ui``) for the web surfaces. Nothing else
makes the copies agree: a word added on one side renders as "unrecognised"
forever on the other, silently, because both sides degrade rather than throw.
@@ -14,16 +15,18 @@ from __future__ import annotations
import pathlib
import re
+from repowise.core.analysis.attention import AREA_ORDER, ATTENTION_ITEM_TYPES
from repowise.core.analysis.execution_flows import FLOW_TERMINATION_VALUES
from repowise.core.ingestion.models import HERITAGE_KIND_VALUES, RESOLUTION_ORIGIN_VALUES
from repowise.core.workspace.diagnostics import UNMATCHED_REASON_VALUES
-_TYPES_SRC = pathlib.Path(__file__).resolve().parents[3] / "packages/types/src"
+_PACKAGES = pathlib.Path(__file__).resolve().parents[3] / "packages"
+_TYPES_SRC = _PACKAGES / "types/src"
-def _union_members(alias: str, module: str = "graph.ts") -> set[str]:
+def _union_members(alias: str, module: str = "graph.ts", src: pathlib.Path = _TYPES_SRC) -> set[str]:
"""The string members of `export type <alias> = "a" | "b" | ...;`."""
- path = _TYPES_SRC / module
+ path = src / module
match = re.search(rf"export type {alias} =(.*?);", path.read_text(encoding="utf-8"), re.DOTALL)
assert match, f"{alias} is not declared in {path.name}"
return set(re.findall(r'"([a-z_]+)"', match.group(1)))
@@ -47,3 +50,10 @@ def test_heritage_kind_differs_from_python_only_where_documented() -> None:
ts = _union_members("HeritageKind", "symbols.ts")
assert ts - set(HERITAGE_KIND_VALUES) == {"method_implements", "method_overrides"}
assert set(HERITAGE_KIND_VALUES) - ts == {"derive"}
+
+
+def test_attention_vocabularies_match_python() -> None:
+ ui = _union_members("AttentionItemType", "dashboard/attention-href.ts", _PACKAGES / "ui/src")
+ assert ui == set(ATTENTION_ITEM_TYPES)
+ assert _union_members("OverviewAttentionType", "overview.ts") == set(ATTENTION_ITEM_TYPES)
+ assert _union_members("OverviewAttentionArea", "overview.ts") == set(AREA_ORDER)