Skip to content

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

feat(stats): one-page stats report, scoped windows and new records (#2526)

Raghav Chamadiya35a51a83c6f5
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/python.py b/packages/core/src/repowise/core/ingestion/resolvers/python.py
index 8da42b29e..2a9381dc1 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/python.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/python.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import sys
from pathlib import Path
from typing import TYPE_CHECKING
@@ -11,6 +12,15 @@ from .context import ResolverContext
if TYPE_CHECKING:
from ..models import Import
+# Stdlib top-level names, independent of the indexer's own Python: the running
+# interpreter's set drops modules removed in 3.12/3.13 that older code imports.
+_STDLIB_NAMES = sys.stdlib_module_names | {
+ "asynchat", "asyncore", "distutils", "imp", "smtpd", # removed in 3.12
+ "aifc", "audioop", "cgi", "cgitb", "chunk", "crypt", "imghdr", "mailcap",
+ "msilib", "nis", "nntplib", "ossaudiodev", "pipes", "sndhdr", "spwd",
+ "sunau", "telnetlib", "uu", "xdrlib", "lib2to3", # removed in 3.13
+} # fmt: skip
+
def _module_index(ctx: ResolverContext) -> dict[str, str]:
"""Source-root-aware dotted-module → path index, built once per context.
@@ -74,10 +84,19 @@ def resolve_python_import(module_path: str, importer_path: str, ctx: ResolverCon
# Stem-only fallback, Python files only. The stem map holds every indexed
# file, so without the suffix guard ``import httpx`` resolved to a
# ``baselines/httpx.json`` fixture; Ruby and PHP guard theirs the same way.
+ # Stdlib names skip it: a nested ``specs/json.py`` is not what ``import
+ # json`` loads, and that one stem drew 527 false edges on this repo. A
+ # sibling of the importer still wins, as it does for a script run from
+ # its own directory.
stem = module_path.split(".")[-1].lower()
- for candidate in ctx.stem_map.get(stem, ()):
- if candidate.endswith((".py", ".pyi")):
- return candidate
+ if module_path.split(".")[0] in _STDLIB_NAMES:
+ sibling = (importer_dir / f"{module_path.replace('.', '/')}.py").as_posix()
+ if sibling in ctx.path_set:
+ return sibling
+ else:
+ for candidate in ctx.stem_map.get(stem, ()):
+ if candidate.endswith((".py", ".pyi")):
+ return candidate
# Nothing in the repo defines this module, so register it the way every
# other language resolver does: the packages tab and the import counts can
diff --git a/packages/core/src/repowise/core/stats_highlights.py b/packages/core/src/repowise/core/stats_highlights.py
new file mode 100644
index 000000000..a186fdecf
--- /dev/null
+++ b/packages/core/src/repowise/core/stats_highlights.py
@@ -0,0 +1,764 @@
+"""Builders for the Stats ("By the Numbers") page, free of any database.
+
+Every builder takes plain mappings (a dict, or a SQLAlchemy ``RowMapping``) and
+returns the JSON-ready section described by ``packages/types/src/stats.ts``.
+The OSS route feeds them SQL rows; the hosted backend feeds them artifact
+dicts. Keeping the derivations here is what lets both surfaces publish the same
+figures without a second copy of the rules.
+
+Scope is defined by subtraction: only signals no other page already owns.
+Health scores live on Code Health, commit volume on Commits, per-person
+ownership on Contributors, dependencies on Architecture, co-change pairs on
+Coupling.
+
+Timestamps may arrive as aware or naive datetimes (SQLite drops tzinfo) or as
+ISO strings (artifacts); :func:`parse_dt` normalises all three to aware UTC.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from collections.abc import Callable, Iterable, Mapping
+from datetime import UTC, datetime, timedelta
+from itertools import pairwise
+from typing import Any
+
+from repowise.core.author_identity import build_identity_resolver
+from repowise.core.test_paths import is_test_related_path
+
+Row = Mapping[str, Any]
+
+# ---------------------------------------------------------------------------
+# Size class: a playful, NLOC-driven label for "how big is this codebase".
+# ---------------------------------------------------------------------------
+
+_SIZE_CLASSES: tuple[tuple[int, str, str], ...] = (
+ (1_000, "Seedling", "A fresh sprout, small enough to hold in your head."),
+ (5_000, "Hamlet", "A cozy codebase you could read in an afternoon."),
+ (20_000, "Village", "A tidy village. A few neighborhoods, easy to walk."),
+ (60_000, "Town", "A proper town with its own districts and main streets."),
+ (150_000, "City", "A real city: busy, layered, plenty going on."),
+ (500_000, "Metropolis", "A sprawling metropolis with serious infrastructure."),
+)
+_MEGALOPOLIS = ("Megalopolis", "A vast megalopolis, its own self-contained world.")
+
+# Share of dated commits that must carry a UTC offset before the punch card and
+# chronotypes switch from UTC to author-local time. Below it the page stays
+# all-UTC instead of mixing two clocks in one matrix.
+_LOCAL_TIME_COVERAGE = 0.99
+
+# A peak hour drawn from fewer commits than this is noise, not a habit.
+_CHRONOTYPE_MIN_COMMITS = 10
+
+# Automation, excluded from the people-shaped sections. Either an explicit bot
+# marker or a service name matched in full, so "Netlify Johnson" stays a person.
+_BOT_NAME_RE = re.compile(
+ r"(\[bot\]"
+ r"|^bot$"
+ r"|[-_ ]bot$"
+ r"|^(dependabot|renovate(bot)?|greenkeeper|snyk([-_ ]bot)?|imgbot|"
+ r"github[-_ ]?actions|semantic[-_ ]release|allcontributors|codecov|mergify|"
+ r"pre[-_ ]commit[-_ ]ci|netlify|vercel)$)",
+ re.IGNORECASE,
+)
+_BOT_EMAIL_RE = re.compile(
+ r"(\[bot\]@|@bots\.noreply\.github\.com|^(actions@github\.com|"
+ r"noreply@github\.com)$)",
+ re.IGNORECASE,
+)
+
+_FUNCTION_KINDS = frozenset({"function", "method"})
+
+
+def is_bot(name: str | None, email: str | None) -> bool:
+ """True when this author is automation (CI or a coding agent's own identity).
+
+ Identity only: an agent-*assisted* commit still has a human author.
+ """
+ # Imported here: the provenance module loads the whole git indexer package.
+ from repowise.core.ingestion.git_indexer.agent_provenance import agent_from_identity
+
+ if agent_from_identity(name, email):
+ return True
+ if name and _BOT_NAME_RE.search(name):
+ return True
+ return bool(email and _BOT_EMAIL_RE.search(email))
+
+
+def size_class(total_nloc: int) -> dict[str, Any]:
+ for ceiling, name, blurb in _SIZE_CLASSES:
+ if total_nloc < ceiling:
+ return {"name": name, "blurb": blurb, "nloc": total_nloc}
+ name, blurb = _MEGALOPOLIS
+ return {"name": name, "blurb": blurb, "nloc": total_nloc}
+
+
+def parse_dt(raw: Any) -> datetime | None:
+ """An aware UTC datetime from a datetime (naive read as UTC) or ISO string."""
+ if not raw:
+ return None
+ if isinstance(raw, datetime):
+ return raw if raw.tzinfo is not None else raw.replace(tzinfo=UTC)
+ try:
+ parsed = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _iso(dt: datetime | None) -> str | None:
+ return dt.isoformat() if dt is not None else None
+
+
+def _int(raw: Any) -> int:
+ try:
+ return int(raw or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _offset_minutes(raw: Any) -> int | None:
+ # bool is an int subclass; a stray False must not read as a zero offset.
+ if isinstance(raw, bool) or raw is None:
+ return None
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return None
+
+
+def _is_external(node: Row) -> bool:
+ node_id = str(node.get("node_id") or node.get("id") or "")
+ return (
+ node.get("language") == "external"
+ or node_id.startswith("external:")
+ or node.get("external_system_id") is not None
+ )
+
+
+# ---------------------------------------------------------------------------
+# Scale
+# ---------------------------------------------------------------------------
+
+
+def build_scale(file_nodes: Iterable[Row], metrics: Iterable[Row]) -> dict[str, Any]:
+ """Counts, NLOC and the language mix.
+
+ ``file_nodes`` are graph file nodes; external dependency nodes are dropped
+ so the file count describes the repo. Only code languages are counted:
+ JSON, YAML and Markdown are formats a developer would not list as the
+ languages a project is written in.
+ """
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ code = REGISTRY.code_languages()
+ file_count = 0
+ symbol_count = 0
+ langs: Counter[str] = Counter()
+ for node in file_nodes:
+ if _is_external(node):
+ continue
+ file_count += 1
+ symbol_count += _int(node.get("symbol_count"))
+ lang = node.get("language")
+ if lang in code:
+ langs[lang] += 1
+
+ total_nloc = 0
+ test_nloc = 0
+ modules: set[str] = set()
+ for m in metrics:
+ nloc = _int(m.get("nloc"))
+ total_nloc += nloc
+ if m.get("is_test"):
+ test_nloc += nloc
+ if m.get("module"):
+ modules.add(m["module"])
+
+ languages = [{"language": k, "file_count": v} for k, v in langs.most_common()]
+ return {
+ "file_count": file_count,
+ "symbol_count": symbol_count,
+ "module_count": len(modules),
+ "total_nloc": total_nloc,
+ "test_nloc": test_nloc,
+ "language_count": len(languages),
+ "languages": languages,
+ "size_class": size_class(total_nloc),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Commits: origin, rhythm and people, from one pass
+# ---------------------------------------------------------------------------
+
+
+def _punch_card_summary(
+ punch: list[list[int]], dated_total: int, *, timezone_mode: str
+) -> dict[str, Any]:
+ """The weekday x hour matrix plus its hottest cell and marginal peaks."""
+ peak = {"weekday": 0, "hour": 0, "count": 0}
+ for wd in range(7):
+ for hr in range(24):
+ if punch[wd][hr] > peak["count"]:
+ peak = {"weekday": wd, "hour": hr, "count": punch[wd][hr]}
+ weekday_totals = [sum(punch[wd]) for wd in range(7)]
+ hour_totals = [sum(punch[wd][hr] for wd in range(7)) for hr in range(24)]
+ return {
+ "matrix": punch,
+ "peak": peak if peak["count"] > 0 else None,
+ "busiest_weekday": max(range(7), key=lambda wd: weekday_totals[wd]) if dated_total else None,
+ "peak_hour": max(range(24), key=lambda hr: hour_totals[hr]) if dated_total else None,
+ "total": dated_total,
+ "timezone_mode": timezone_mode,
+ }
+
+
+def _commit_velocity(
+ commit_times: list[datetime], last_at: datetime | None, window_start: datetime | None
+) -> dict[str, Any] | None:
+ """The 90 days ending at the newest commit against the 90 before.
+
+ ``window_start`` is the oldest commit the sample holds when the sample is
+ not the whole history. A 90-day window reaching past it would count only
+ part of its commits, so the figure is withheld (None) or, for the prior
+ window alone, the comparison is.
+ """
+ if last_at is None or not commit_times:
+ return None
+ recent_cut = last_at - timedelta(days=90)
+ prior_cut = last_at - timedelta(days=180)
+ if window_start is not None and window_start > recent_cut:
+ return None
+ recent = sum(1 for t in commit_times if t > recent_cut)
+ prior = sum(1 for t in commit_times if prior_cut < t <= recent_cut)
+ prior_covered = window_start is None or window_start <= prior_cut
+ pct_change = round((recent - prior) / prior * 100.0, 1) if prior and prior_covered else None
+ return {"recent_90d": recent, "prior_90d": prior, "pct_change": pct_change}
+
+
+def _longest_streak(commit_days: set[Any]) -> dict[str, Any] | None:
+ """Longest run of consecutive calendar days with at least one commit."""
+ if not commit_days:
+ return None
+ days_sorted = sorted(commit_days)
+ best_len = run_len = 1
+ best_end = days_sorted[0]
+ for prev, cur in pairwise(days_sorted):
+ run_len = run_len + 1 if (cur - prev).days == 1 else 1
+ if run_len > best_len:
+ best_len, best_end = run_len, cur
+ if best_len < 2:
+ return None
+ return {
+ "days": best_len,
+ "start": (best_end - timedelta(days=best_len - 1)).isoformat(),
+ "end": best_end.isoformat(),
+ }
+
+
+def _longest_silence(commit_times: list[datetime]) -> dict[str, Any] | None:
+ """The longest stretch between two consecutive commits."""
+ if len(commit_times) < 2:
+ return None
+ start, end = max(pairwise(sorted(commit_times)), key=lambda p: p[1] - p[0])
+ hours = int((end - start).total_seconds() // 3600)
+ return {"hours": hours, "start": _iso(start), "end": _iso(end)}
+
+
+def _chronotypes(
+ per_author_hours: dict[str, list[int]],
+ per_author_weekdays: dict[str, list[int]],
+ names: dict[str, str],
+) -> list[dict[str, Any]]:
+ """Each frequent contributor's peak commit hour, with a habit label.
+
+ Both marginal histograms ship because the UI names people from them, and
+ which days count as the weekend is the reader's preference.
+ """
+ out: list[dict[str, Any]] = []
+ for key, hours in per_author_hours.items():
+ total = sum(hours)
+ if total < _CHRONOTYPE_MIN_COMMITS:
+ continue
+ peak_hour = max(range(24), key=lambda h: hours[h])
+ night = sum(hours[h] for h in (22, 23, 0, 1, 2, 3, 4))
+ early = sum(hours[h] for h in (5, 6, 7, 8))
+ if peak_hour >= 22 or peak_hour <= 4:
+ label = "night_owl"
+ elif 5 <= peak_hour <= 8:
+ label = "early_bird"
+ elif night / total >= 0.25:
+ label = "night_owl"
+ else:
+ label = "daylight"
+ out.append(
+ {
+ "name": names.get(key, key),
+ "commits": total,
+ "peak_hour": peak_hour,
+ "label": label,
+ "night_pct": round(night / total * 100.0, 1),
+ "early_pct": round(early / total * 100.0, 1),
+ "hour_commits": hours,
+ "weekday_commits": per_author_weekdays.get(key, [0] * 7),
+ }
+ )
+ return sorted(out, key=lambda a: -a["commits"])[:8]
+
+
+def _keep_top(bucket: list[dict[str, Any]], item: dict[str, Any], key: str) -> None:
+ bucket.append(item)
+ bucket.sort(key=lambda c: -c[key])
+ del bucket[3:]
+
+
+class _Awards:
+ """Top three commits by churn, breadth and net deletion.
+
+ Three survive dropping the root commit, which wins every size award on an
+ initial import.
+ """
+
+ def __init__(self) -> None:
+ self.churn: list[dict[str, Any]] = []
+ self.wide: list[dict[str, Any]] = []
+ self.purge: list[dict[str, Any]] = []
+
+ def add(self, row: Row) -> None:
+ base = {"sha": row.get("sha"), "subject": row.get("subject") or ""}
+ added, deleted = _int(row.get("lines_added")), _int(row.get("lines_deleted"))
+ files = _int(row.get("files_changed"))
+ if added + deleted > 0:
+ item = {**base, "lines_changed": added + deleted, "files_changed": files}
+ _keep_top(self.churn, item, "lines_changed")
+ if files > 0:
+ item = {**base, "files_changed": files, "lines_changed": added + deleted}
+ _keep_top(self.wide, item, "files_changed")
+ if deleted > added:
+ item = {**base, "lines_deleted": deleted, "lines_added": added, "net": deleted - added}
+ _keep_top(self.purge, item, "net")
+
+ def winners(self, root_sha: str | None) -> dict[str, Any]:
+ def pick(bucket: list[dict[str, Any]]) -> dict[str, Any] | None:
+ return next((c for c in bucket if c["sha"] != root_sha), None)
+
+ purge = pick(self.purge)
+ return {
+ "biggest_commit": pick(self.churn),
+ "widest_commit": pick(self.wide),
+ "biggest_purge": {k: v for k, v in purge.items() if k != "net"} if purge else None,
+ }
+
+
+def _calendar(
+ stamps: list[tuple[datetime, int | None, str | None]], local_mode: bool, humans: set[str]
+) -> dict[str, Any]:
+ """Punch card, day and month counts and per-person histograms, in one clock."""
+ punch = [[0] * 24 for _ in range(7)]
+ days: Counter[Any] = Counter()
+ months: Counter[str] = Counter()
+ hours: dict[str, list[int]] = {}
+ weekdays: dict[str, list[int]] = {}
+ for moment, offset, key in stamps:
+ local = moment + timedelta(minutes=offset or 0) if local_mode else moment
+ punch[local.weekday()][local.hour] += 1
+ days[local.date()] += 1
+ months[local.strftime("%Y-%m")] += 1
+ if local_mode and key in humans:
+ hours.setdefault(key, [0] * 24)[local.hour] += 1
+ weekdays.setdefault(key, [0] * 7)[local.weekday()] += 1
+ return {"punch": punch, "days": days, "months": months, "hours": hours, "weekdays": weekdays}
+
+
+def _sample_complete(
+ first_at: datetime | None, true_first: datetime | None, total: int, true_total: Any
+) -> bool:
+ """Whether the commit sample reaches the root commit.
+
+ Decided by date where the root is known: the sample walk skips merge
+ commits and the whole-history count does not, so the counts never match on
+ a repo that merges.
+ """
+ if true_first is not None:
+ return first_at is not None and first_at <= true_first + timedelta(seconds=60)
+ return true_total is None or total >= int(true_total)
+
+
+def _most_common(counter: Counter[Any]) -> tuple[Any, int] | None:
+ return counter.most_common(1)[0] if counter else None
+
+
+def build_commit_pass(commits: Iterable[Row], repo_totals: Row | None = None) -> dict[str, Any]:
+ """Origin, rhythm, people and commit awards from one walk over the commits.
+
+ ``commits`` is the indexed commit sample, which is bounded to the newest N
+ commits. Headline totals prefer the whole-history values in
+ ``repo_totals`` (issue #730), and ``rhythm.window`` says how much of the
+ history everything else was drawn from, so the page can name its scope.
+ """
+ totals = repo_totals or {}
+ rows = list(commits)
+ resolve = build_identity_resolver([(r.get("author_name"), r.get("author_email")) for r in rows])
+
+ contributors: set[str] = set()
+ display_name: dict[str, str] = {}
+ humans: set[str] = set()
+ arrival: dict[str, datetime] = {}
+ stamps: list[tuple[datetime, int | None, str | None]] = []
+ first: tuple[datetime, str | None] | None = None
+ awards = _Awards()
+
+ for row in rows:
+ name, email = row.get("author_name"), row.get("author_email")
+ key = resolve(name, email) if (name or email) else None
+ if key:
+ contributors.add(key)
+ display_name.setdefault(key, name or key)
+ if not is_bot(name, email):
+ humans.add(key)
+ awards.add(row)
+ moment = parse_dt(row.get("committed_at"))
+ if moment is None:
+ continue
+ if first is None or moment < first[0]:
+ first = (moment, row.get("sha"))
+ stamps.append((moment, _offset_minutes(row.get("committed_offset_minutes")), key))
+ if key and (key not in arrival or moment < arrival[key]):
+ arrival[key] = moment
+
+ commit_times = [s[0] for s in stamps]
+ first_at = first[0] if first else None
+ complete = _sample_complete(
+ first_at, parse_dt(totals.get("first_commit_at")), len(rows), totals.get("total_commit_count")
+ )
+ local_mode = bool(stamps) and (
+ sum(1 for s in stamps if s[1] is not None) / len(stamps) >= _LOCAL_TIME_COVERAGE
+ )
+ cal = _calendar(stamps, local_mode, humans)
+ rhythm = _rhythm(cal, commit_times, local_mode, complete, first_at, len(rows))
+ arrivals = sorted(
+ (
+ {"name": display_name.get(k, k), "first_commit_at": _iso(v)}
+ for k, v in arrival.items()
+ if k in humans
+ ),
+ key=lambda a: a["first_commit_at"] or "",
+ )
+ return {
+ "origin": _origin(totals, first_at, max(commit_times, default=None), len(rows), len(contributors)),
+ "rhythm": rhythm,
+ "chronotypes": (
+ _chronotypes(cal["hours"], cal["weekdays"], display_name) if local_mode else []
+ ),
+ "arrivals": arrivals,
+ # The oldest sampled commit is the root only when the sample is
+ # complete; otherwise it is an ordinary commit that may rightly win.
+ **awards.winners(first[1] if first and complete else None),
+ }
+
+
+def _origin(
+ totals: Row, first_at: datetime | None, last_at: datetime | None, sampled: int, people: int
+) -> dict[str, Any]:
+ """Founding facts, preferring whole-history totals over the sample."""
+ first = parse_dt(totals.get("first_commit_at")) or first_at
+ true_total = totals.get("total_commit_count")
+ true_people = totals.get("total_contributor_count")
+ return {
+ "first_commit_at": _iso(first),
+ "first_commit_author": totals.get("first_commit_author"),
+ "first_commit_subject": totals.get("first_commit_subject"),
+ "last_commit_at": _iso(last_at),
+ "age_days": (last_at - first).days if (first and last_at) else None,
+ "total_commits": int(true_total) if true_total is not None else sampled,
+ "contributor_count": int(true_people) if true_people is not None else people,
+ }
+
+
+def _rhythm(
+ cal: dict[str, Any],
+ commit_times: list[datetime],
+ local_mode: bool,
+ complete: bool,
+ first_at: datetime | None,
+ sampled: int,
+) -> dict[str, Any]:
+ """The time-shaped section, with the window it was drawn from."""
+ last_at = max(commit_times, default=None)
+ day = _most_common(cal["days"])
+ month = _most_common(cal["months"])
+ return {
+ "window": {
+ "commits": sampled,
+ "first_at": _iso(first_at),
+ "last_at": _iso(last_at),
+ "complete": complete,
+ },
+ "punch_card": _punch_card_summary(
+ cal["punch"], len(commit_times), timezone_mode="author_local" if local_mode else "utc"
+ ),
+ "velocity": _commit_velocity(commit_times, last_at, None if complete else first_at),
+ "busiest_month": {"month": month[0], "total": month[1]} if month else None,
+ "busiest_day": {"date": day[0].isoformat(), "commits": day[1]} if day else None,
+ "longest_streak": _longest_streak(set(cal["days"])),
+ "longest_silence": _longest_silence(commit_times),
+ "active_days": len(cal["days"]),
+ }
+
+
+def build_churn(repo_totals: Row | None) -> dict[str, Any] | None:
+ """Lifetime lines written vs. taken back, from whole-history repo totals.
+
+ Never summed from the bounded commit sample; None when the totals are absent.
+ """
+ totals = repo_totals or {}
+ added, deleted = totals.get("total_lines_added"), totals.get("total_lines_deleted")
+ if added is None or deleted is None or int(added) <= 0:
+ return None
+ added, deleted = int(added), int(deleted)
+ return {
+ "lines_added": added,
+ "lines_deleted": deleted,
+ "net": added - deleted,
+ "deleted_per_hundred": round(deleted / added * 100.0, 1),
+ }
+
+
+def code_half_life(git_metadata: Iterable[Row], last_at: Any) -> int | None:
+ """Median days since each file was last touched, anchored to the newest commit."""
+ anchor = parse_dt(last_at)
+ if anchor is None:
+ return None
+ ages = sorted(
+ (anchor - touched).days
+ for m in git_metadata
+ if (touched := parse_dt(m.get("last_commit_at"))) is not None and touched <= anchor
+ )
+ if not ages:
+ return None
+ mid = len(ages) // 2
+ return ages[mid] if len(ages) % 2 else (ages[mid - 1] + ages[mid]) // 2
+
+
+# ---------------------------------------------------------------------------
+# People: repo-level concentration only
+# ---------------------------------------------------------------------------
+
+
+def build_people(git_metadata: Iterable[Row]) -> dict[str, Any]:
+ """Owner count, single-owner files, directory silos and the truck factor."""
+ from repowise.core.analysis.health.aggregation import module_label
+
+ owners: Counter[str] = Counter()
+ single_owner_files = 0
+ module_owner_files: dict[str, Counter[str]] = {}
+ module_file_totals: Counter[str] = Counter()
+
+ for m in git_metadata:
+ owner = m.get("primary_owner_name")
+ if _int(m.get("bus_factor")) == 1:
+ single_owner_files += 1
+ module = module_label(m.get("file_path"))
+ module_file_totals[module] += 1
+ if owner:
+ owners[owner] += 1
+ module_owner_files.setdefault(module, Counter())[owner] += 1
+
+ silo_count = sum(
+ 1
+ for module, mowners in module_owner_files.items()
+ if max(mowners.values()) / module_file_totals[module] > 0.8
+ )
+
+ # Fewest primary owners who together hold more than half the owned files.
+ owned_total = sum(owners.values())
+ truck_factor: int | None = None
+ if owned_total:
+ cumulative = 0
+ truck_factor = 0
+ for count in sorted(owners.values(), reverse=True):
+ cumulative += count
+ truck_factor += 1
+ if cumulative * 2 > owned_total:
+ break
+
+ return {
+ "owner_count": len(owners),
+ "tracked_files": sum(module_file_totals.values()),
+ "single_owner_files": single_owner_files,
+ "silo_count": silo_count,
+ "truck_factor": truck_factor,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Records: the superlatives
+# ---------------------------------------------------------------------------
+
+
+def build_file_records(
+ metrics: Iterable[Row], git_metadata: Iterable[Row], first_commit_at: Any
+) -> dict[str, Any]:
+ """Largest, gnarliest and most-changed file, and what survives from day one.
+
+ "Oldest file" is replaced by a count: every file added in the root commit
+ ties for it, and naming one of a hundred ties is arbitrary. Files whose
+ history hit the per-file commit cap are left out of both sides, since the
+ cap can cut their root commit off.
+ """
+ out: dict[str, Any] = {}
+ metrics = list(metrics)
+ largest = max(metrics, key=lambda m: _int(m.get("nloc")), default=None)
+ if largest is not None and _int(largest.get("nloc")) > 0:
+ out["largest_file"] = {"path": largest["file_path"], "nloc": _int(largest["nloc"])}
+ gnarliest = max(metrics, key=lambda m: _int(m.get("max_ccn")), default=None)
+ if gnarliest is not None and _int(gnarliest.get("max_ccn")) > 0:
+ out["gnarliest_file"] = {
+ "path": gnarliest["file_path"],
+ "max_ccn": _int(gnarliest["max_ccn"]),
+ }
+
+ root = parse_dt(first_commit_at)
+ most_changed: Row | None = None
+ day_one = 0
+ dated = 0
+ for m in git_metadata:
+ if most_changed is None or _int(m.get("commit_count_total")) > _int(
+ most_changed.get("commit_count_total")
+ ):
+ most_changed = m
+ born = parse_dt(m.get("first_commit_at"))
+ if born is None or m.get("commit_count_capped"):
+ continue
+ dated += 1
+ if root is not None and abs((born - root).total_seconds()) < 60:
+ day_one += 1
+ if most_changed is not None and _int(most_changed.get("commit_count_total")) > 0:
+ out["most_changed_file"] = {
+ "path": most_changed["file_path"],
+ "commit_count": _int(most_changed["commit_count_total"]),
+ }
+ if day_one:
+ out["day_one_files"] = {"count": day_one, "of": dated}
+ return out
+
+
+def most_imported_file(candidates: Iterable[Row]) -> dict[str, Any] | None:
+ """The highest fan-in file that is real project source.
+
+ ``candidates`` carry ``path``, ``in_degree`` and ``pagerank``, best first.
+ The stored ``is_test`` flag can be stale, so the anchored path rules
+ re-check each one (#1103).
+ """
+ for c in candidates:
+ path = str(c.get("path") or "")
+ if not path or path.startswith("external:") or is_test_related_path(path):
+ continue
+ if _int(c.get("in_degree")) <= 0:
+ return None
+ return {
+ "path": path,
+ "pagerank": round(float(c.get("pagerank") or 0.0), 4),
+ "import_count": _int(c.get("in_degree")),
+ }
+ return None
+
+
+def is_test_checker(metrics: Iterable[Row]) -> Callable[[str], bool]:
+ """Whether a path is test code, for the records that skip it.
+
+ Health's stored ``is_test`` answers for the files it scored. It is NULL on
+ rows written before the column, and absent for unscored files; those fall
+ back to the shared path rules, cached per path.
+ """
+ flags = {m["file_path"]: m.get("is_test") for m in metrics}
+ cache: dict[str, bool] = {}
+
+ def check(path: str) -> bool:
+ flag = flags.get(path)
+ if flag is not None:
+ return bool(flag)
+ if path not in cache:
+ cache[path] = is_test_related_path(path)
+ return cache[path]
+
+ return check
+
+
+def symbol_shape(total: int, async_count: int, documented: int) -> dict[str, Any] | None:
+ """What share of the symbols is async, and what share carries a docstring."""
+ if total <= 0:
+ return None
+ return {
+ "total": total,
+ "async_count": async_count,
+ "async_pct": round(async_count / total * 100.0, 1),
+ "documented_count": documented,
+ "documented_pct": round(documented / total * 100.0, 1),
+ }
+
+
+def build_function_records(
+ functions: Iterable[Row], is_test: Callable[[str], bool]
+) -> dict[str, Any]:
+ """Longest function, longest name and the most reused name.
+
+ ``functions`` are function and method symbols. Test code is skipped: test
+ names are sentences by convention and would win every time.
+ """
+ out: dict[str, Any] = {}
+ longest: tuple[int, Row] | None = None
+ longest_name: Row | None = None
+ names: Counter[str] = Counter()
+
+ for s in functions:
+ name = s.get("name") or ""
+ if not name or s.get("kind") not in _FUNCTION_KINDS or is_test(s.get("file_path") or ""):
+ continue
+ if not name.startswith("__"):
+ names[name] += 1
+ if longest_name is None or len(name) > len(longest_name["name"]):
+ longest_name = s
+ lines = _int(s.get("end_line")) - _int(s.get("start_line")) + 1
+ if lines > 1 and (longest is None or lines > longest[0]):
+ longest = (lines, s)
+
+ if longest is not None:
+ lines, s = longest
+ out["longest_function"] = {"name": s["name"], "file_path": s["file_path"], "lines": lines}
+ if longest_name is not None:
+ out["longest_name"] = {
+ "name": longest_name["name"],
+ "file_path": longest_name["file_path"],
+ }
+ if names:
+ name, count = names.most_common(1)[0]
+ if count > 1:
+ out["most_common_name"] = {"name": name, "count": count}
+ return out
+
+
+def most_patched_function(
+ blame: Iterable[Row], is_test: Callable[[str], bool]
+) -> dict[str, Any] | None:
+ """The non-test function whose current lines the most commits own.
+
+ ``mod_count`` is distinct commits across the function's surviving blame, so
+ a wholesale rewrite scores low and a function patched in many places high.
+ """
+ best: Row | None = None
+ for row in blame:
+ if _int(row.get("mod_count")) <= _int((best or {}).get("mod_count")):
+ continue
+ if not row.get("function_name") or is_test(row.get("file_path") or ""):
+ continue
+ best = row
+ if best is None:
+ return None
+ return {
+ "name": best.get("function_name") or "",
+ "file_path": best.get("file_path") or "",
+ "mod_count": _int(best.get("mod_count")),
+ }
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index aebb743e6..1c492483d 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -1,37 +1,24 @@
-"""/api/repos/{repo_id}/stats/highlights — the "By the Numbers" payload.
+"""/api/repos/{repo_id}/stats/highlights: the "By the Numbers" payload.
-A single read-only aggregate powering the repo Stats page. Its scope is defined
-by subtraction: **only signals no other page in the app already shows**. Health
-scores live on Code Health, commit volume and categories on Commits, per-person
-ownership on Contributors, dependencies and communities on Architecture. What is
-left, and what this endpoint serves, is the repo's identity (scale, origin,
-lifetime churn), its rhythm (time-of-day, streaks, how fast code goes cold), and
-its records — none of which have a home anywhere else.
-
-Everything here reads rows the indexer already wrote; nothing recomputes
-analysis. The three source tables are each pulled once, as narrow column
-selects rather than whole ORM rows, and every derived figure rides one of those
-three passes. Sections build defensively: a missing table degrades that section
-to ``None`` / empty rather than 500-ing the page.
+A read-only aggregate for the repo Stats page. The derivations live in
+:mod:`repowise.core.stats_highlights` so the hosted backend can build the same
+payload from its artifacts; this module only reads rows. Every read is a narrow
+column select or a capped ordered query, and nothing recomputes analysis.
"""
from __future__ import annotations
-import re
-from datetime import UTC, datetime, timedelta
-from itertools import pairwise
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import Integer, func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.co_change import parse_partners
-from repowise.core.ingestion.git_indexer import build_identity_resolver
-from repowise.core.ingestion.git_indexer.agent_provenance import agent_from_identity
+from repowise.core import stats_highlights as sh
from repowise.core.persistence import crud
from repowise.core.persistence.models import (
GitCommit,
+ GitFunctionBlame,
GitMetadata,
GraphMetric,
GraphNode,
@@ -39,9 +26,7 @@ from repowise.core.persistence.models import (
HealthFileMetric,
WikiSymbol,
)
-from repowise.core.test_paths import is_test_related_path
from repowise.server.deps import get_db_session, verify_api_key
-from repowise.server.services.module_health import top_level_module
router = APIRouter(
prefix="/api/repos",
@@ -49,713 +34,86 @@ router = APIRouter(
dependencies=[Depends(verify_api_key)],
)
+# Blame rows read for the most-rewritten award. Ordered by the indexed
+# mod_count, so this only needs headroom for test functions to be skipped.
+_BLAME_CANDIDATES = 50
-# ---------------------------------------------------------------------------
-# Size class — a playful, NLOC-driven label for "how big is this codebase".
-# Thresholds are on non-comment lines of code (the health-metric NLOC sum),
-# the most honest single proxy for scale across languages.
-# ---------------------------------------------------------------------------
-
-_SIZE_CLASSES: tuple[tuple[int, str, str], ...] = (
- (1_000, "Seedling", "A fresh sprout — small enough to hold in your head."),
- (5_000, "Hamlet", "A cozy codebase you could read in an afternoon."),
- (20_000, "Village", "A tidy village — a few neighborhoods, easy to walk."),
- (60_000, "Town", "A proper town with its own districts and main streets."),
- (150_000, "City", "A real city — busy, layered, plenty going on."),
- (500_000, "Metropolis", "A sprawling metropolis with serious infrastructure."),
-)
-_MEGALOPOLIS = ("Megalopolis", "A vast megalopolis — its own self-contained world.")
-
-# Share of dated commits that must carry a UTC offset before the punch card and
-# the chronotype awards switch from UTC to author-local time. Below it the page
-# stays honestly all-UTC rather than mixing two clocks in one matrix — a chart
-# where some cells are local and some are not is worse than one that is
-# uniformly shifted. An index written before the offset column existed starts at
-# 0% and fills on `repowise update` (the backfill in
-# ``pipeline.incremental.reconcile_commit_offsets``), so this flips on its own.
-# The backfill is capped per run, so a very deep window may need a few updates.
-_LOCAL_TIME_COVERAGE = 0.99
-
-# Minimum commits before someone is eligible for a chronotype award — a peak
-# hour drawn from three commits is noise, not a habit.
-_CHRONOTYPE_MIN_COMMITS = 10
-
-# Automation, excluded from the people-shaped sections. A bot's "peak hour" is
-# a cron schedule and its "arrival" is the day someone enabled it — both are
-# facts about configuration, not about anyone's working habits, and leaving
-# dependabot in a night-owl leaderboard makes the whole list read as noise.
-# Matched on the author identity rather than on `agent_name`, which marks
-# agent-*assisted* commits a human still authored.
-# Either an explicit bot marker, or a service name matched in FULL. Matching a
-# leading token would read "Netlify Johnson" as automation, and dropping a real
-# person off the page is far worse than keeping one stray bot on it.
-_BOT_NAME_RE = re.compile(
- r"(\[bot\]"
- r"|^bot$"
- r"|[-_ ]bot$"
- r"|^(dependabot|renovate(bot)?|greenkeeper|snyk([-_ ]bot)?|imgbot|"
- r"github[-_ ]?actions|semantic[-_ ]release|allcontributors|codecov|mergify|"
- r"pre[-_ ]commit[-_ ]ci|netlify|vercel)$)",
- re.IGNORECASE,
-)
-_BOT_EMAIL_RE = re.compile(
- r"(\[bot\]@|@bots\.noreply\.github\.com|^(actions@github\.com|"
- r"noreply@github\.com)$)",
- re.IGNORECASE,
-)
-
-
-def _is_bot(name: str | None, email: str | None) -> bool:
- """True when this author is automation rather than a person.
-
- Two sources. Coding agents come from the ingestion layer's provenance
- registry, so "is this Claude / Cursor / Codex?" stays answered in exactly
- one place and the stats page inherits every vendor identity the indexer
- already knows. The regexes above cover the rest of CI automation, which
- provenance has no reason to model.
- Identity only: an agent-*assisted* commit still has a human author, and
- that person belongs in these lists.
- """
- if agent_from_identity(name, email):
- return True
- if name and _BOT_NAME_RE.search(name):
- return True
- return bool(email and _BOT_EMAIL_RE.search(email))
+async def _rows(session: AsyncSession, stmt: Any) -> list[Any]:
+ return list((await session.execute(stmt)).mappings().all())
-def _size_class(total_nloc: int) -> dict[str, Any]:
- for ceiling, name, blurb in _SIZE_CLASSES:
- if total_nloc < ceiling:
- return {"name": name, "blurb": blurb, "nloc": total_nloc}
- name, blurb = _MEGALOPOLIS
- return {"name": name, "blurb": blurb, "nloc": total_nloc}
-
-
-def _iso(dt: Any) -> str | None:
- return dt.isoformat() if dt is not None else None
-
-
-def _as_utc(dt: datetime | None) -> datetime | None:
- """Reinterpret a naive datetime as UTC.
-
- The ``committed_at`` columns are declared ``DateTime(timezone=True)``, but
- SQLite does not persist tzinfo, so a value read back is naive even though it
- was written aware. Anything doing arithmetic or calendar work on it has to
- restore the tz first or it silently mixes aware and naive values (and
- ``.hour`` quietly answers for the wrong clock). Same guard the change-risk
- tool applies for the same reason.
- """
- if dt is None:
- return None
- return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)
-
-
-# ---------------------------------------------------------------------------
-# Scale — what this codebase is, dimensionally.
-# ---------------------------------------------------------------------------
-
-
-async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dict[str, Any]:
- """Graph + NLOC scale signals + the size-class label."""
- file_count = (
- await session.scalar(
- select(func.count(GraphNode.id)).where(
- GraphNode.repository_id == repo_id, GraphNode.node_type == "file"
+async def _largest_cycle(session: AsyncSession, repo_id: str) -> dict[str, Any] | None:
+ """Largest import cycle, off the materialized SCC membership rows."""
+ sizes = (
+ await session.execute(
+ select(func.count())
+ .where(
+ GraphNodeMembership.repository_id == repo_id,
+ GraphNodeMembership.scc_size > 1,
)
+ .group_by(GraphNodeMembership.scc_id)
)
- or 0
- )
- symbol_count = int(
- await session.scalar(
- select(func.sum(GraphNode.symbol_count)).where(GraphNode.repository_id == repo_id)
- )
- or 0
- )
- total_nloc = sum(int(m.nloc or 0) for m in metrics)
-
- lang_rows = await session.execute(
- select(GraphNode.language, func.count(GraphNode.id))
- .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
- .group_by(GraphNode.language)
- )
- languages = sorted(
- ({"language": lang or "other", "file_count": n} for lang, n in lang_rows),
- key=lambda r: -r["file_count"],
- )
- module_count = len({m.module for m in metrics if m.module})
-
- return {
- "file_count": file_count,
- "symbol_count": symbol_count,
- "module_count": module_count,
- "total_nloc": total_nloc,
- "language_count": len(languages),
- "languages": languages,
- "size_class": _size_class(total_nloc),
- }
-
-
-# ---------------------------------------------------------------------------
-# Rhythm — the time-shape of the work. Nothing else in the app has a clock.
-# ---------------------------------------------------------------------------
-
-
-def _punch_card_summary(
- punch: list[list[int]], dated_total: int, *, timezone_mode: str
-) -> dict[str, Any]:
- """Fold the weekday x hour commit matrix into a renderable summary.
-
- ``matrix`` is 7 rows (0=Monday) x 24 hours in *timezone_mode*'s clock. Also
- names the single hottest cell and the busiest weekday / peak hour (by
- marginal totals). The weekend share is deliberately not computed here: which
- days are the weekend is a reader preference, and the matrix already carries
- every weekday total.
- """
- peak = {"weekday": 0, "hour": 0, "count": 0}
- for wd in range(7):
- for hr in range(24):
- if punch[wd][hr] > peak["count"]:
- peak = {"weekday": wd, "hour": hr, "count": punch[wd][hr]}
-
- weekday_totals = [sum(punch[wd]) for wd in range(7)]
- hour_totals = [sum(punch[wd][hr] for wd in range(7)) for hr in range(24)]
- busiest_weekday = max(range(7), key=lambda wd: weekday_totals[wd]) if dated_total else None
- peak_hour = max(range(24), key=lambda hr: hour_totals[hr]) if dated_total else None
-
- return {
- "matrix": punch,
- "peak": peak if peak["count"] > 0 else None,
- "busiest_weekday": busiest_weekday,
- "peak_hour": peak_hour,
- "total": dated_total,
- "timezone_mode": timezone_mode,
- }
-
-
-def _commit_velocity(commit_times: list[Any], last_at: Any) -> dict[str, Any]:
- """Recent-vs-prior commit momentum, anchored to the newest commit.
-
- Anchoring to ``last_at`` (not wall-clock now) keeps the signal meaningful on
- an index that hasn't been synced today: it compares the 90 days ending at
- the latest commit against the 90 before that. ``pct_change`` is None when the
- prior window is empty (a young repo), so the UI can omit a divide-by-zero
- arrow rather than show a fake spike.
- """
- if last_at is None or not commit_times:
- return {"recent_90d": 0, "prior_90d": 0, "pct_change": None}
- recent_cut = last_at - timedelta(days=90)
- prior_cut = last_at - timedelta(days=180)
- recent = sum(1 for t in commit_times if t > recent_cut)
- prior = sum(1 for t in commit_times if prior_cut < t <= recent_cut)
- pct_change = round((recent - prior) / prior * 100.0, 1) if prior else None
- return {"recent_90d": recent, "prior_90d": prior, "pct_change": pct_change}
-
-
-def _longest_streak(commit_days: set[Any]) -> dict[str, Any] | None:
- """Longest run of consecutive calendar days with at least one commit."""
- if not commit_days:
- return None
- days_sorted = sorted(commit_days)
- best_len = run_len = 1
- best_end = days_sorted[0]
- for prev, cur in pairwise(days_sorted):
- run_len = run_len + 1 if (cur - prev).days == 1 else 1
- if run_len > best_len:
- best_len, best_end = run_len, cur
- if best_len < 2:
+ ).all()
+ if not sizes:
return None
- return {
- "days": best_len,
- "start": (best_end - timedelta(days=best_len - 1)).isoformat(),
- "end": best_end.isoformat(),
- }
-
-
-def _chronotypes(
- per_author_hours: dict[str, list[int]],
- per_author_weekdays: dict[str, list[int]],
- names: dict[str, str],
-) -> list[dict[str, Any]]:
- """Each frequent contributor's peak commit hour, with a habit label.
+ return {"files": max(int(n) for (n,) in sizes), "cycle_count": len(sizes)}
- Only meaningful once commits carry their author's UTC offset — the caller
- skips this entirely in UTC mode rather than award "night owl" to whoever
- happens to live furthest east.
- Both marginal histograms ship alongside the label, because the UI names
- people from them and weekday naming has to happen there: which days count
- as the weekend is a reader preference, so a "weekend warrior" decided here
- would be wrong for every team that rests Friday. The joint weekday-by-hour
- distribution is deliberately not sent. It is 168 numbers per person to
- sharpen a single label, and the two marginals answer the same question
- closely enough.
- """
- out: list[dict[str, Any]] = []
- for key, hours in per_author_hours.items():
- total = sum(hours)
- if total < _CHRONOTYPE_MIN_COMMITS:
- continue
- peak_hour = max(range(24), key=lambda h: hours[h])
- # Off-hours share doubles as the tiebreaker for the label: a peak at 9am
- # with a third of commits after midnight is still a night owl.
- night = sum(hours[h] for h in (22, 23, 0, 1, 2, 3, 4))
- early = sum(hours[h] for h in (5, 6, 7, 8))
- if peak_hour >= 22 or peak_hour <= 4:
- label = "night_owl"
- elif 5 <= peak_hour <= 8:
- label = "early_bird"
- elif night / total >= 0.25:
- label = "night_owl"
- else:
- label = "daylight"
- out.append(
- {
- "name": names.get(key, key),
- "commits": total,
- "peak_hour": peak_hour,
- "label": label,
- "night_pct": round(night / total * 100.0, 1),
- "early_pct": round(early / total * 100.0, 1),
- "hour_commits": hours,
- "weekday_commits": per_author_weekdays.get(key, [0] * 7),
- }
+async def _most_central(session: AsyncSession, repo_id: str) -> dict[str, Any] | None:
+ candidates = await _rows(
+ session,
+ select(
+ GraphMetric.node_id.label("path"),
+ GraphMetric.in_degree,
+ GraphMetric.pagerank,
)
- return sorted(out, key=lambda a: -a["commits"])[:8]
-
-
-async def _commit_pass(session: AsyncSession, repo_id: str, repo: Any) -> dict[str, Any]:
- """Single scan of ``git_commits`` producing origin, rhythm and people signals.
-
- One query, one loop. Everything time-shaped the page shows — the punch card,
- streaks, the busiest day, the widest commit, momentum, chronotypes, arrival
- dates — falls out of this pass, because each of them needs per-commit rows
- and a second walk would double the cost for no new data.
-
- Headline totals (commit count, project age, contributor count, founder)
- prefer the whole-history values stamped on the ``Repository`` row at index
- time: ``git_commits`` is bounded to the newest N commits, so deriving them
- from it undercounts a long-lived repo badly (issue #730).
- """
- rows = (
- await session.execute(
- select(
- GitCommit.committed_at,
- GitCommit.committed_offset_minutes,
- GitCommit.author_name,
- GitCommit.author_email,
- GitCommit.sha,
- GitCommit.subject,
- GitCommit.lines_added,
- GitCommit.lines_deleted,
- GitCommit.files_changed,
- ).where(GitCommit.repository_id == repo_id)
+ .join(
+ GraphNode,
+ (GraphNode.repository_id == GraphMetric.repository_id)
+ & (GraphNode.node_id == GraphMetric.node_id),
)
- ).all()
-
- # Fold GitHub noreply variants and same-name real+noreply emails to one
- # identity so the same person isn't counted as several contributors.
- resolve = build_identity_resolver([(name, email) for _, _, name, email, *_ in rows])
-
- total = 0
- dated = 0
- with_offset = 0
- contributors: set[str] = set()
- display_name: dict[str, str] = {}
- human_keys: set[str] = set()
- arrival: dict[str, datetime] = {}
- first_at: datetime | None = None
- first_sha: str | None = None
- last_at: datetime | None = None
- commit_times: list[datetime] = []
- # Normalised (utc, offset) pairs kept for the second, timezone-aware pass:
- # whether the punch card is drawn in UTC or author-local can't be decided
- # until every row has been seen, so the calendar work waits for the verdict.
- stamps: list[tuple[datetime, int | None, str | None]] = []
- # Top-3 by churn and by breadth. The repo's very first commit is excluded
- # from both awards (an initial import would always win), so a couple of
- # spare candidates are enough to survive dropping it.
- top_churn: list[dict[str, Any]] = []
- top_wide: list[dict[str, Any]] = []
-
- for (
- committed_at,
- offset,
- author_name,
- author_email,
- sha,
- subject,
- added,
- deleted,
- files,
- ) in rows:
- total += 1
- key = None
- if author_email or author_name:
- key = resolve(author_name, author_email)
- if key:
- contributors.add(key)
- display_name.setdefault(key, author_name or key)
- if not _is_bot(author_name, author_email):
- human_keys.add(key)
-
- churn = int(added or 0) + int(deleted or 0)
- if churn > 0:
- top_churn.append(
- {
- "sha": sha,
- "subject": subject or "",
- "lines_changed": churn,
- "files_changed": int(files or 0),
- }
- )
- top_churn.sort(key=lambda c: -c["lines_changed"])
- del top_churn[3:]
- if int(files or 0) > 0:
- top_wide.append(
- {
- "sha": sha,
- "subject": subject or "",
- "files_changed": int(files or 0),
- "lines_changed": churn,
- }
- )
- top_wide.sort(key=lambda c: -c["files_changed"])
- del top_wide[3:]
-
- moment = _as_utc(committed_at)
- if moment is None:
- continue
- dated += 1
- if offset is not None:
- with_offset += 1
- if first_at is None or moment < first_at:
- first_at, first_sha = moment, sha
- if last_at is None or moment > last_at:
- last_at = moment
- commit_times.append(moment)
- stamps.append((moment, offset, key))
- if key and (key not in arrival or moment < arrival[key]):
- arrival[key] = moment
-
- # Author-local only once effectively every row can be shifted; see
- # _LOCAL_TIME_COVERAGE. Mixed clocks would make the matrix a lie.
- local_mode = bool(dated) and (with_offset / dated) >= _LOCAL_TIME_COVERAGE
- timezone_mode = "author_local" if local_mode else "utc"
-
- punch = [[0] * 24 for _ in range(7)]
- commit_days: set[Any] = set()
- day_counts: dict[Any, int] = {}
- per_author_hours: dict[str, list[int]] = {}
- per_author_weekdays: dict[str, list[int]] = {}
- for moment, offset, key in stamps:
- local = moment + timedelta(minutes=offset or 0) if local_mode else moment
- punch[local.weekday()][local.hour] += 1
- day = local.date()
- commit_days.add(day)
- day_counts[day] = day_counts.get(day, 0) + 1
- if local_mode and key and key in human_keys:
- per_author_hours.setdefault(key, [0] * 24)[local.hour] += 1
- per_author_weekdays.setdefault(key, [0] * 7)[local.weekday()] += 1
-
- busiest_day = None
- if day_counts:
- day, count = max(day_counts.items(), key=lambda kv: kv[1])
- busiest_day = {"date": day.isoformat(), "commits": count}
-
- months: dict[str, int] = {}
- for moment, offset, _ in stamps:
- local = moment + timedelta(minutes=offset or 0) if local_mode else moment
- month = local.strftime("%Y-%m")
- months[month] = months.get(month, 0) + 1
- busiest_month = None
- if months:
- month, count = max(months.items(), key=lambda kv: kv[1])
- busiest_month = {"month": month, "total": count}
-
- biggest_commit = next((c for c in top_churn if c["sha"] != first_sha), None)
- widest_commit = next((c for c in top_wide if c["sha"] != first_sha), None)
-
- # Prefer the whole-history values stamped on the repo at index time; fall
- # back to the bounded sample when they're absent (older index, non-git
- # repo). Age runs from the true first commit to the latest commit we have.
- true_first = _as_utc(getattr(repo, "first_commit_at", None))
- effective_first = true_first if true_first is not None else first_at
- effective_total = getattr(repo, "total_commit_count", None)
- effective_contributors = getattr(repo, "total_contributor_count", None)
-
- arrivals = sorted(
- (
- {"name": display_name.get(k, k), "first_commit_at": _iso(v)}
- for k, v in arrival.items()
- if k in human_keys
- ),
- key=lambda a: a["first_commit_at"] or "",
- )
-
- return {
- "origin": {
- "first_commit_at": _iso(effective_first),
- "first_commit_author": getattr(repo, "first_commit_author", None),
- "first_commit_subject": getattr(repo, "first_commit_subject", None),
- "last_commit_at": _iso(last_at),
- "age_days": (
- (last_at - effective_first).days if (effective_first and last_at) else None
- ),
- "total_commits": effective_total if effective_total is not None else total,
- "contributor_count": (
- effective_contributors if effective_contributors is not None else len(contributors)
- ),
- },
- "rhythm": {
- "punch_card": _punch_card_summary(punch, dated, timezone_mode=timezone_mode),
- "velocity": _commit_velocity(commit_times, last_at),
- "busiest_month": busiest_month,
- "busiest_day": busiest_day,
- "longest_streak": _longest_streak(commit_days),
- "active_days": len(commit_days),
- },
- "chronotypes": (
- _chronotypes(per_author_hours, per_author_weekdays, display_name) if local_mode else []
- ),
- "arrivals": arrivals,
- "biggest_commit": biggest_commit,
- "widest_commit": widest_commit,
- }
-
-
-def _churn_ledger(repo: Any) -> dict[str, Any] | None:
- """Lifetime lines written vs. taken back, from the repo-level totals.
-
- Deliberately *not* summed from ``git_commits``: that table is bounded to the
- newest N commits, so on a repo with deeper history the sum would be a
- windowed figure presented as a lifetime one. ``None`` when the indexer
- skipped the walk (history too deep) or predates the capture, so the page
- omits the ledger rather than showing a number it can't stand behind.
- """
- added = getattr(repo, "total_lines_added", None)
- deleted = getattr(repo, "total_lines_deleted", None)
- if added is None or deleted is None or added <= 0:
- return None
- return {
- "lines_added": int(added),
- "lines_deleted": int(deleted),
- "net": int(added) - int(deleted),
- "deleted_per_hundred": round(int(deleted) / int(added) * 100.0, 1),
- }
-
-
-def _code_half_life(all_meta: list[Any], last_at: str | None) -> int | None:
- """Median days since each file was last touched.
-
- "Half this codebase hasn't been changed in N days." Anchored to the newest
- commit rather than wall-clock now, so a stale index doesn't inflate it.
- """
- anchor = _as_utc(datetime.fromisoformat(last_at)) if last_at else None
- if anchor is None:
- return None
- ages = sorted(
- (anchor - touched).days
- for m in all_meta
- if (touched := _as_utc(m.last_commit_at)) is not None and touched <= anchor
+ .where(
+ GraphMetric.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ GraphNode.is_test.is_(False),
+ GraphNode.external_system_id.is_(None),
+ ~GraphNode.node_id.like("external:%"),
+ )
+ .order_by(GraphMetric.in_degree.desc())
+ .limit(10),
)
- if not ages:
- return None
- mid = len(ages) // 2
- return ages[mid] if len(ages) % 2 else (ages[mid - 1] + ages[mid]) // 2
-
-
-# ---------------------------------------------------------------------------
-# People — repo-level concentration only. Per-person detail is the Contributors
-# page's job, and duplicating it here would just be a worse version of it.
-# ---------------------------------------------------------------------------
-
-
-def _people(all_meta: list[Any]) -> dict[str, Any]:
- """Ownership concentration: owner count, single-owner files, module silos."""
- owners: dict[str, int] = {}
- single_owner_files = 0
- module_owner_files: dict[str, dict[str, int]] = {}
- module_file_totals: dict[str, int] = {}
-
- for m in all_meta:
- if m.primary_owner_name:
- owners[m.primary_owner_name] = owners.get(m.primary_owner_name, 0) + 1
- if (m.bus_factor or 0) == 1:
- single_owner_files += 1
- module = top_level_module(m.file_path)
- module_file_totals[module] = module_file_totals.get(module, 0) + 1
- if m.primary_owner_name:
- bucket = module_owner_files.setdefault(module, {})
- bucket[m.primary_owner_name] = bucket.get(m.primary_owner_name, 0) + 1
-
- silo_count = 0
- for module, mowners in module_owner_files.items():
- top = max(mowners.values(), default=0)
- if module_file_totals.get(module) and top / module_file_totals[module] > 0.8:
- silo_count += 1
-
- # Truck factor: the fewest primary owners who together hold >50% of owned
- # files — "how many people could walk out before the bus problem bites".
- # A factor of 1 means a single person owns most of the codebase.
- owned_total = sum(owners.values())
- truck_factor: int | None = None
- if owned_total:
- cumulative = 0
- truck_factor = 0
- for count in sorted(owners.values(), reverse=True):
- cumulative += count
- truck_factor += 1
- if cumulative * 2 > owned_total:
- break
-
- return {
- "owner_count": len(owners),
- "single_owner_files": single_owner_files,
- "silo_count": silo_count,
- "truck_factor": truck_factor,
- }
-
-
-# ---------------------------------------------------------------------------
-# Records — the superlatives. Several of these are the only headline treatment
-# their underlying signal gets anywhere in the app (max CCN is otherwise a
-# sortable column; the cycle count has no UI at all).
-# ---------------------------------------------------------------------------
-
-
-async def _records(
- session: AsyncSession, repo_id: str, metrics: list[Any], all_meta: list[Any]
-) -> dict[str, Any]:
- """The "biggest / oldest / gnarliest / most" awards, one row each."""
- out: dict[str, Any] = {}
-
- largest = max(metrics, key=lambda m: m.nloc or 0, default=None)
- if largest is not None and (largest.nloc or 0) > 0:
- out["largest_file"] = {"path": largest.file_path, "nloc": int(largest.nloc)}
-
- # Gnarliest file by cyclomatic complexity. Code Health exposes max_ccn only
- # as a sortable table column, so this is the one place it gets named.
- gnarliest = max(metrics, key=lambda m: m.max_ccn or 0, default=None)
- if gnarliest is not None and (gnarliest.max_ccn or 0) > 0:
- out["gnarliest_file"] = {"path": gnarliest.file_path, "max_ccn": int(gnarliest.max_ccn)}
-
- sym = (
+ hit = sh.most_imported_file(candidates)
+ if hit is not None:
+ return hit
+ # Graph metrics not materialized: fall back to the PageRank pick.
+ central = (
await session.execute(
- select(WikiSymbol.name, WikiSymbol.file_path, WikiSymbol.complexity_estimate)
- .where(WikiSymbol.repository_id == repo_id)
- .order_by(WikiSymbol.complexity_estimate.desc())
+ select(GraphNode.node_id, GraphNode.pagerank)
+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
+ .order_by(GraphNode.pagerank.desc())
.limit(1)
)
).first()
- if sym is not None and (sym[2] or 0) > 0:
- out["most_complex_symbol"] = {
- "name": sym[0],
- "file_path": sym[1],
- "complexity": int(sym[2]),
- }
-
- most_changed = max(all_meta, key=lambda m: m.commit_count_total or 0, default=None)
- if most_changed is not None and (most_changed.commit_count_total or 0) > 0:
- out["most_changed_file"] = {
- "path": most_changed.file_path,
- "commit_count": int(most_changed.commit_count_total),
- }
- dated = [m for m in all_meta if m.first_commit_at is not None]
- if dated:
- oldest = min(dated, key=lambda m: _as_utc(m.first_commit_at))
- out["oldest_file"] = {
- "path": oldest.file_path,
- "first_commit_at": _iso(_as_utc(oldest.first_commit_at)),
- }
-
- # Most imported file — highest fan-in among non-test file nodes, the
- # legible version of "most central". External and test nodes are excluded
- # so the award names real project source, and the top candidates are then
- # re-checked against the shared test-path rules.
- #
- # The re-check is not redundant with the SQL filter. `is_test` is *stored*,
- # stamped when the file was last traversed, so an index written before the
- # current rules can carry a stale answer — and the file this award is most
- # likely to hand to is `tests/conftest.py`, which tops fan-in in any repo
- # that shares fixtures widely (713 imports in this one, more than double the
- # runner-up). The rules themselves now come from one place rather than the
- # unanchored regex this used to hold, which read `src/latest/api.py` and
- # `protest/main.py` as tests and passed the award to the runner-up (#1103).
- #
- # Falls back to the PageRank pick when graph metrics were not materialized.
- candidates = (
- await session.execute(
- select(GraphMetric.node_id, GraphMetric.in_degree, GraphMetric.pagerank)
- .join(
- GraphNode,
- (GraphNode.repository_id == GraphMetric.repository_id)
- & (GraphNode.node_id == GraphMetric.node_id),
- )
- .where(
- GraphMetric.repository_id == repo_id,
- GraphNode.node_type == "file",
- GraphNode.is_test.is_(False),
- GraphNode.external_system_id.is_(None),
- ~GraphNode.node_id.like("external:%"),
- )
- .order_by(GraphMetric.in_degree.desc())
- .limit(10)
- )
- ).all()
- imported = next((c for c in candidates if not is_test_related_path(c[0])), None)
- if imported is not None and (imported[1] or 0) > 0:
- out["most_central_file"] = {
- "path": imported[0],
- "pagerank": round(float(imported[2] or 0.0), 4),
- "import_count": int(imported[1]),
- }
- else:
- central = (
- await session.execute(
- select(GraphNode.node_id, GraphNode.pagerank)
- .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
- .order_by(GraphNode.pagerank.desc())
- .limit(1)
- )
- ).first()
- if central is not None and (central[1] or 0) > 0:
- out["most_central_file"] = {
- "path": central[0],
- "pagerank": round(float(central[1]), 4),
- }
-
- # The pair with the most shared commits. Counted, not weighted: the card
- # renders it as "changed together N times".
- best_pair: dict[str, Any] | None = None
- for m in all_meta:
- for p in parse_partners(m.co_change_partners_json):
- if best_pair is None or p.support > best_pair["count"]:
- best_pair = {"a": m.file_path, "b": p.file_path, "count": p.support}
- if best_pair and best_pair["count"] > 0:
- out["strongest_coupling"] = best_pair
+ if central is None or not (central[1] or 0) > 0:
+ return None
+ return {"path": central[0], "pagerank": round(float(central[1]), 4)}
- # Largest import cycle — strongly-connected components with more than one
- # member. One aggregate over the materialized membership rows (no graph
- # rebuild). Nothing else in the app surfaces cycles at all.
- scc_rows = (
- await session.execute(
- select(func.count())
- .where(
- GraphNodeMembership.repository_id == repo_id,
- GraphNodeMembership.scc_size > 1,
- )
- .group_by(GraphNodeMembership.scc_id)
- )
- ).all()
- if scc_rows:
- out["largest_cycle"] = {
- "files": max(int(n) for (n,) in scc_rows),
- "cycle_count": len(scc_rows),
- }
- # Symbol-shape shares: what fraction of this codebase is async, and what
- # fraction carries a docstring. One aggregate row, three counters.
+async def _symbol_records(
+ session: AsyncSession, repo_id: str, is_test: Any
+) -> dict[str, Any]:
+ """Function, symbol-shape and function-blame records."""
+ functions = await _rows(
+ session,
+ select(
+ WikiSymbol.name,
+ WikiSymbol.kind,
+ WikiSymbol.file_path,
+ WikiSymbol.start_line,
+ WikiSymbol.end_line,
+ ).where(WikiSymbol.repository_id == repo_id, WikiSymbol.kind.in_(("function", "method"))),
+ )
shape = (
await session.execute(
select(
@@ -764,93 +122,128 @@ async def _records(
func.count(WikiSymbol.docstring),
).where(WikiSymbol.repository_id == repo_id)
)
- ).one_or_none()
- if shape and shape[0]:
- total_symbols = int(shape[0])
- async_count = int(shape[1] or 0)
- documented = int(shape[2] or 0)
- out["symbol_shape"] = {
- "total": total_symbols,
- "async_count": async_count,
- "async_pct": round(async_count / total_symbols * 100.0, 1),
- "documented_count": documented,
- "documented_pct": round(documented / total_symbols * 100.0, 1),
- }
-
+ ).one()
+ complex_sym = (
+ await session.execute(
+ select(WikiSymbol.name, WikiSymbol.file_path, WikiSymbol.complexity_estimate)
+ .where(WikiSymbol.repository_id == repo_id)
+ .order_by(WikiSymbol.complexity_estimate.desc())
+ .limit(1)
+ )
+ ).first()
+ blame = await _rows(
+ session,
+ select(GitFunctionBlame.function_name, GitFunctionBlame.file_path, GitFunctionBlame.mod_count)
+ .where(GitFunctionBlame.repository_id == repo_id)
+ .order_by(GitFunctionBlame.mod_count.desc())
+ .limit(_BLAME_CANDIDATES),
+ )
+ out = sh.build_function_records(functions, is_test)
+ optional = {
+ "most_complex_symbol": (
+ {"name": complex_sym[0], "file_path": complex_sym[1], "complexity": int(complex_sym[2])}
+ if complex_sym is not None and (complex_sym[2] or 0) > 0
+ else None
+ ),
+ "symbol_shape": sh.symbol_shape(int(shape[0] or 0), int(shape[1] or 0), int(shape[2] or 0)),
+ "most_patched_function": sh.most_patched_function(blame, is_test),
+ }
+ out.update({k: v for k, v in optional.items() if v})
return out
-# ---------------------------------------------------------------------------
-# Endpoint
-# ---------------------------------------------------------------------------
-
-
@router.get("/{repo_id}/stats/highlights")
async def stats_highlights(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
) -> dict:
- """Everything the Stats ("By the Numbers") page needs, in one call.
-
- Three narrow column selects (health metrics, git metadata, commits) plus a
- handful of aggregates. Deliberately no health summary, findings, dead-code,
- dependency, decision or cost reads: every one of those belongs to a page
- that already owns the subject, and pulling them here cost the page its two
- slowest queries for numbers shown better elsewhere.
- """
+ """Everything the Stats page needs, in one call."""
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
- # Narrow selects, not whole ORM rows: the page needs four health columns and
- # seven git-metadata ones out of the ~20 each table carries, and the unread
- # remainder includes the large JSON blobs.
- metrics = (
- await session.execute(
- select(
- HealthFileMetric.file_path,
- HealthFileMetric.nloc,
- HealthFileMetric.module,
- HealthFileMetric.max_ccn,
- ).where(HealthFileMetric.repository_id == repo_id)
- )
- ).all()
- all_meta = (
- await session.execute(
- select(
- GitMetadata.file_path,
- GitMetadata.primary_owner_name,
- GitMetadata.bus_factor,
- GitMetadata.commit_count_total,
- GitMetadata.first_commit_at,
- GitMetadata.last_commit_at,
- GitMetadata.co_change_partners_json,
- ).where(GitMetadata.repository_id == repo_id)
- )
- ).all()
-
- commits = await _commit_pass(session, repo_id, repo)
- records = await _records(session, repo_id, metrics, all_meta)
- # Computed on the commit scan for cost, but they are awards, so the payload
- # files them under records.
- for key in ("biggest_commit", "widest_commit"):
- value = commits.pop(key, None)
- if value:
- records[key] = value
-
- rhythm = commits["rhythm"]
- rhythm["code_half_life_days"] = _code_half_life(all_meta, commits["origin"]["last_commit_at"])
-
- people = _people(all_meta)
- people["contributor_count"] = commits["origin"]["contributor_count"]
- people["chronotypes"] = commits.pop("chronotypes", [])
- people["arrivals"] = commits.pop("arrivals", [])
+ totals = {
+ "total_commit_count": repo.total_commit_count,
+ "first_commit_at": repo.first_commit_at,
+ "total_contributor_count": repo.total_contributor_count,
+ "first_commit_author": repo.first_commit_author,
+ "first_commit_subject": repo.first_commit_subject,
+ "total_lines_added": repo.total_lines_added,
+ "total_lines_deleted": repo.total_lines_deleted,
+ }
+ file_nodes = await _rows(
+ session,
+ select(
+ GraphNode.node_id,
+ GraphNode.language,
+ GraphNode.symbol_count,
+ GraphNode.external_system_id,
+ ).where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file"),
+ )
+ metrics = await _rows(
+ session,
+ select(
+ HealthFileMetric.file_path,
+ HealthFileMetric.nloc,
+ HealthFileMetric.module,
+ HealthFileMetric.max_ccn,
+ HealthFileMetric.is_test,
+ ).where(HealthFileMetric.repository_id == repo_id),
+ )
+ all_meta = await _rows(
+ session,
+ select(
+ GitMetadata.file_path,
+ GitMetadata.primary_owner_name,
+ GitMetadata.bus_factor,
+ GitMetadata.commit_count_total,
+ GitMetadata.commit_count_capped,
+ GitMetadata.first_commit_at,
+ GitMetadata.last_commit_at,
+ ).where(GitMetadata.repository_id == repo_id),
+ )
+ commits = await _rows(
+ session,
+ select(
+ GitCommit.committed_at,
+ GitCommit.committed_offset_minutes,
+ GitCommit.author_name,
+ GitCommit.author_email,
+ GitCommit.sha,
+ GitCommit.subject,
+ GitCommit.lines_added,
+ GitCommit.lines_deleted,
+ GitCommit.files_changed,
+ ).where(GitCommit.repository_id == repo_id),
+ )
+ activity = sh.build_commit_pass(commits, totals)
+ records = {
+ **sh.build_file_records(metrics, all_meta, totals["first_commit_at"]),
+ **await _symbol_records(session, repo_id, sh.is_test_checker(metrics)),
+ }
+ optional = {
+ "most_central_file": await _most_central(session, repo_id),
+ "largest_cycle": await _largest_cycle(session, repo_id),
+ "biggest_commit": activity.pop("biggest_commit"),
+ "widest_commit": activity.pop("widest_commit"),
+ "biggest_purge": activity.pop("biggest_purge"),
+ }
+ records.update({k: v for k, v in optional.items() if v})
+
+ rhythm = activity["rhythm"]
+ rhythm["code_half_life_days"] = sh.code_half_life(all_meta, activity["origin"]["last_commit_at"])
+ people = {
+ **sh.build_people(all_meta),
+ "contributor_count": activity["origin"]["contributor_count"],
+ "chronotypes": activity["chronotypes"],
+ "arrivals": activity["arrivals"],
+ }
return {
"repo": {"id": repo.id, "name": repo.name},
- "scale": await _scale(session, repo_id, metrics),
- "origin": commits["origin"],
- "churn": _churn_ledger(repo),
+ "scale": sh.build_scale(file_nodes, metrics),
+ "origin": activity["origin"],
+ "churn": sh.build_churn(totals),
"rhythm": rhythm,
"people": people,
"records": records,
diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.ts
index 0e1ddcbc6..405aec991 100644
--- a/packages/types/src/stats.ts
+++ b/packages/types/src/stats.ts
@@ -5,8 +5,9 @@
* (packages/server/.../routers/stats.py). Scope is defined by subtraction:
* only signals no other page in the app already owns. Health scores belong to
* Code Health, commit volume and categories to Commits, per-person ownership to
- * Contributors, dependencies and communities to Architecture — none of those
- * appear here.
+ * Contributors, dependencies and communities to Architecture. None of those
+ * appear here. The server derivations live in `repowise.core.stats_highlights`,
+ * shared by the OSS route and the hosted backend.
*
* Every section is independently built server-side and degrades to null/empty
* rather than failing the page, so most leaf fields are nullable.
@@ -28,6 +29,9 @@ export interface StatsScale {
symbol_count: number;
module_count: number;
total_nloc: number;
+ /** The share of `total_nloc` in files health analysis marked as tests. */
+ test_nloc?: number;
+ /** Code languages only: data and markup formats are not counted. */
language_count: number;
languages: StatsLanguage[];
size_class: StatsSizeClass;
@@ -50,7 +54,7 @@ export interface StatsOrigin {
* Lifetime lines written vs. taken back.
*
* Read from repo-level totals captured at index time, never summed from the
- * commit table — that table is bounded to the newest N commits, so summing it
+ * commit table: that table is bounded to the newest N commits, so summing it
* would present a windowed figure as a lifetime one. Null when the history was
* too deep to walk or the index predates the capture.
*/
@@ -66,7 +70,7 @@ export interface StatsChurn {
* Coding-rhythm heatmap: commit counts by weekday (0=Monday) x hour (0-23).
*
* `timezone_mode` says which clock the matrix is drawn in. `author_local` means
- * every commit was shifted by its author's own UTC offset — the honest version
+ * every commit was shifted by its author's own UTC offset, the honest version
* of "when do people work". `utc` is the fallback for indexes written before
* the offset was captured; it resolves itself on the next `repowise update`.
*/
@@ -86,18 +90,37 @@ export interface StatsPunchCard {
export interface StatsVelocity {
recent_90d: number;
prior_90d: number;
- /** Percent change recent-vs-prior. Null when the prior window is empty. */
+ /** Percent change recent-vs-prior. Null when the prior window is empty or
+ * reaches past the indexed commit sample. */
pct_change: number | null;
}
+/**
+ * How much history the rhythm and people sections were drawn from.
+ *
+ * The indexed commit table is bounded to the newest N commits. `complete` is
+ * false when the repo has more history than that, and the page then names the
+ * window instead of presenting a sample as the repo's whole life.
+ */
+export interface StatsWindow {
+ commits: number;
+ first_at: string | null;
+ last_at: string | null;
+ complete: boolean;
+}
+
/** The time-shape of the work. Nothing else in the app has a clock. */
export interface StatsRhythm {
+ window?: StatsWindow;
punch_card: StatsPunchCard;
- velocity: StatsVelocity;
+ /** Null when the 90-day window reaches past the indexed commit sample. */
+ velocity: StatsVelocity | null;
busiest_month: { month: string; total: number } | null;
busiest_day: { date: string; commits: number } | null;
/** Longest run of consecutive days with at least one commit. */
longest_streak: { days: number; start: string; end: string } | null;
+ /** Longest stretch between two consecutive commits. */
+ longest_silence?: { hours: number; start: string; end: string } | null;
/** Distinct calendar days carrying at least one commit. */
active_days: number;
/** Median days since each file was last touched, anchored to the newest
@@ -105,7 +128,7 @@ export interface StatsRhythm {
code_half_life_days: number | null;
}
-/** A contributor's commit-hour habit. Only emitted in author-local mode —
+/** A contributor's commit-hour habit. Only emitted in author-local mode:
* awarding "night owl" off UTC would just name whoever lives furthest east. */
export interface StatsChronotype {
name: string;
@@ -134,13 +157,15 @@ export interface StatsArrival {
export interface StatsPeople {
owner_count: number;
contributor_count: number;
+ /** Files with git history: the denominator for `single_owner_files`. */
+ tracked_files?: number;
single_owner_files: number;
silo_count: number;
/** Fewest primary owners who together hold >50% of owned files. 1 means a
* single person owns most of the codebase. Null when no ownership data. */
truck_factor: number | null;
chronotypes: StatsChronotype[];
- /** Contributors ordered by their first commit — the arrivals timeline. */
+ /** Contributors ordered by their first commit inside the window. */
arrivals: StatsArrival[];
}
@@ -155,11 +180,11 @@ export interface StatsRecords {
gnarliest_file?: { path: string; max_ccn: number };
most_complex_symbol?: { name: string; file_path: string; complexity: number };
most_changed_file?: { path: string; commit_count: number };
- oldest_file?: { path: string; first_commit_at: string | null };
+ /** Files whose first commit is the root commit, out of every dated file. */
+ day_one_files?: { count: number; of: number };
/** `import_count` present when graph metrics were materialized — the award
* is then "most imported"; without it, it degrades to the PageRank pick. */
most_central_file?: { path: string; pagerank: number; import_count?: number };
- strongest_coupling?: { a: string; b: string; count: number };
/** Biggest strongly-connected import cycle, and how many exist. */
largest_cycle?: { files: number; cycle_count: number };
/** What fraction of this codebase is async, and what fraction is documented. */
@@ -184,6 +209,20 @@ export interface StatsRecords {
files_changed: number;
lines_changed: number;
};
+ /** Non-initial commit that removed the most lines net. */
+ biggest_purge?: {
+ sha: string;
+ subject: string;
+ lines_deleted: number;
+ lines_added: number;
+ };
+ /** Function and record awards skip test code. */
+ longest_function?: { name: string; file_path: string; lines: number };
+ longest_name?: { name: string; file_path: string };
+ most_common_name?: { name: string; count: number };
+ /** Distinct commits that own a surviving line of the function, from
+ * function blame. High for many small patches, low for a rewrite. */
+ most_patched_function?: { name: string; file_path: string; mod_count: number };
}
export interface StatsRepo {
diff --git a/packages/ui/__tests__/stats/size-class-hero.test.tsx b/packages/ui/__tests__/stats/size-class-hero.test.tsx
deleted file mode 100644
index 6a52761b9..000000000
--- a/packages/ui/__tests__/stats/size-class-hero.test.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import type { StatsScale } from "@repowise-dev/types/stats";
-import { describe, expect, it } from "vitest";
-import { SizeClassHero } from "../../src/stats/size-class-hero.js";
-
-function makeScale(overrides: Partial<StatsScale> = {}): StatsScale {
- return {
- file_count: 1_234_567,
- symbol_count: 98_432,
- module_count: 80,
- total_nloc: 4_200_000,
- language_count: 3,
- languages: [],
- size_class: {
- name: "Metropolis",
- blurb: "A large codebase.",
- nloc: 4_200_000,
- },
- ...overrides,
- };
-}
-
-describe("SizeClassHero", () => {
- it("names the size class and its blurb", () => {
- render(<SizeClassHero scale={makeScale()} repoName="acme" />);
-
- expect(screen.getByRole("heading", { name: "Metropolis" })).toBeInTheDocument();
- expect(screen.getByText("A large codebase.")).toBeInTheDocument();
- expect(screen.getByText("acme")).toBeInTheDocument();
- });
-
- it("renders no figures of its own", () => {
- // The headline counts moved to StatRibbon. Rendering them here too put a
- // boxed number directly above the hairline row carrying the same number,
- // so the hero is now identity-only and this guards against them creeping
- // back in.
- render(<SizeClassHero scale={makeScale()} />);
-
- expect(screen.queryByText("1.2M")).not.toBeInTheDocument();
- expect(screen.queryByText("98.4K")).not.toBeInTheDocument();
- expect(screen.queryByText(/Lines of code/i)).not.toBeInTheDocument();
- expect(screen.queryByText(/Symbols/i)).not.toBeInTheDocument();
- });
-
- it("omits the eyebrow when no repo name is given", () => {
- const { container } = render(<SizeClassHero scale={makeScale()} />);
- expect(container.querySelector(".tracking-\\[0\\.2em\\]")).toBeNull();
- });
-});
diff --git a/packages/ui/__tests__/stats/stat-ribbon.test.tsx b/packages/ui/__tests__/stats/stat-ribbon.test.tsx
index 3cf20e09e..8a0be60a5 100644
--- a/packages/ui/__tests__/stats/stat-ribbon.test.tsx
+++ b/packages/ui/__tests__/stats/stat-ribbon.test.tsx
@@ -42,4 +42,15 @@ describe("StatRibbon", () => {
const { container } = render(<StatRibbon stats={[{ label: "Files", value: "" }]} />);
expect(container).toBeEmptyDOMElement();
});
+
+ it("keeps a linked cell's caption", () => {
+ render(<StatRibbon stats={[{ label: "Contributors", value: "96", sub: "people", href: "/owners" }]} />);
+ expect(screen.getByRole("link")).toHaveTextContent("people");
+ });
+
+ it("sizes the grid to the cells, so four figures leave no empty column", () => {
+ const stats = ["a", "b", "c", "d"].map((label) => ({ label, value: "1" }));
+ const { container } = render(<StatRibbon stats={stats} />);
+ expect(container.querySelector("dl")).toHaveClass("lg:grid-cols-4");
+ });
});
diff --git a/packages/ui/__tests__/stats/stats-report.test.tsx b/packages/ui/__tests__/stats/stats-report.test.tsx
new file mode 100644
index 000000000..792c52757
--- /dev/null
+++ b/packages/ui/__tests__/stats/stats-report.test.tsx
@@ -0,0 +1,133 @@
+import { render, screen } from "@testing-library/react";
+import type { StatsHighlights } from "@repowise-dev/types/stats";
+import { describe, expect, it } from "vitest";
+import { RecordsList } from "../../src/stats/records-list.js";
+import { StatsReport } from "../../src/stats/stats-report.js";
+
+function makeData(overrides: Partial<StatsHighlights["rhythm"]> = {}): StatsHighlights {
+ const matrix = Array.from({ length: 7 }, () => Array<number>(24).fill(0));
+ matrix[2]![14] = 6;
+ return {
+ repo: { id: "r1", name: "acme" },
+ scale: {
+ file_count: 120,
+ symbol_count: 900,
+ module_count: 4,
+ total_nloc: 17_000,
+ test_nloc: 7_000,
+ language_count: 1,
+ languages: [{ language: "python", file_count: 120 }],
+ size_class: { name: "Village", blurb: "A tidy village.", nloc: 17_000 },
+ },
+ origin: {
+ first_commit_at: "2024-01-01T00:00:00+00:00",
+ first_commit_author: "Ada",
+ first_commit_subject: "Initial commit",
+ last_commit_at: "2024-06-01T00:00:00+00:00",
+ age_days: 152,
+ total_commits: 5_000,
+ contributor_count: 3,
+ },
+ churn: null,
+ rhythm: {
+ window: {
+ commits: 6,
+ first_at: "2024-05-01T00:00:00+00:00",
+ last_at: "2024-06-01T00:00:00+00:00",
+ complete: false,
+ },
+ punch_card: {
+ matrix,
+ peak: { weekday: 2, hour: 14, count: 6 },
+ busiest_weekday: 2,
+ peak_hour: 14,
+ total: 6,
+ timezone_mode: "utc",
+ },
+ velocity: null,
+ busiest_month: null,
+ busiest_day: null,
+ longest_streak: null,
+ longest_silence: null,
+ active_days: 3,
+ code_half_life_days: null,
+ ...overrides,
+ },
+ people: {
+ owner_count: 2,
+ contributor_count: 3,
+ single_owner_files: 10,
+ silo_count: 0,
+ truck_factor: 1,
+ chronotypes: [],
+ arrivals: [{ name: "Bea", first_commit_at: "2024-05-01T00:00:00+00:00" }],
+ },
+ records: {},
+ };
+}
+
+describe("StatsReport", () => {
+ it("leads with the size figure and the test ratio", () => {
+ render(<StatsReport data={makeData()} />);
+ expect(screen.getByText("17,000")).toBeInTheDocument();
+ expect(screen.getByText("70 lines of tests")).toBeInTheDocument();
+ });
+
+ it("names the commit window when it is not the whole history", () => {
+ render(<StatsReport data={makeData()} />);
+ expect(screen.getByText(/Drawn from the latest 6 of 5,000 commits/)).toBeInTheDocument();
+ // Arrivals inside a partial window are first appearances, and say so.
+ expect(screen.getByRole("heading", { name: "First seen" })).toBeInTheDocument();
+ });
+
+ it("scopes commit records to the sample they came from", () => {
+ const data = makeData();
+ data.records.biggest_commit = { sha: "a", subject: "Big", lines_changed: 9, files_changed: 1 };
+ render(<StatsReport data={data} />);
+ expect(screen.getByRole("heading", { name: "Commits, latest 6" })).toBeInTheDocument();
+ });
+
+ it("calls a complete history arrivals", () => {
+ const data = makeData();
+ data.rhythm.window!.complete = true;
+ render(<StatsReport data={data} />);
+ expect(screen.getByRole("heading", { name: "Arrivals" })).toBeInTheDocument();
+ expect(screen.queryByText(/Drawn from the latest/)).not.toBeInTheDocument();
+ });
+});
+
+describe("RecordsList", () => {
+ it("drops the gnarliest file when the most complex symbol already names it", () => {
+ render(
+ <RecordsList
+ records={{
+ gnarliest_file: { path: "src/flow.tsx", max_ccn: 90 },
+ most_complex_symbol: { name: "Flow", file_path: "src/flow.tsx", complexity: 90 },
+ }}
+ />,
+ );
+ expect(screen.queryByText("Gnarliest file")).not.toBeInTheDocument();
+ expect(screen.getByText("Flow")).toBeInTheDocument();
+ });
+
+ it("links records to their file and commit, with the full path", () => {
+ const path = "packages/a/very/deep/directory/structure/that/used/to/be/cut/module.py";
+ render(
+ <RecordsList
+ records={{
+ largest_file: { path, nloc: 900 },
+ biggest_commit: { sha: "abc123", subject: "Big one", lines_changed: 10, files_changed: 2 },
+ }}
+ fileHref={(p) => `/files/${p}`}
+ commitHref={(sha) => `/commits?commit=${sha}`}
+ />,
+ );
+ // Wrap points after each slash split the text, so match on content, not name.
+ const fileLink = screen.getAllByRole("link").find((a) => a.textContent === path);
+ expect(fileLink).toHaveAttribute("href", `/files/${path}`);
+ expect(screen.getByRole("link", { name: "Big one" })).toHaveAttribute(
+ "href",
+ "/commits?commit=abc123",
+ );
+ });
+});
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
index 7bc35f5e8..392389fed 100644
--- a/packages/ui/src/lib/format.ts
+++ b/packages/ui/src/lib/format.ts
@@ -21,9 +21,14 @@ export function parseDate(date: Timestamp): Date {
return new Date(date);
}
-/** Format a number with commas: 1234567 → "1,234,567" */
+const NUMBER_FORMAT = new Intl.NumberFormat("en-US");
+
+/** Format a number with commas: 1234567 → "1,234,567".
+ * Pinned to en-US like `formatDate`: the runtime default differs between the
+ * server and the browser (en-IN groups 1261599 as 12,61,599), which broke
+ * hydration on every server-rendered figure over 99,999. */
export function formatNumber(n: number): string {
- return new Intl.NumberFormat().format(n);
+ return NUMBER_FORMAT.format(n);
}
/** Format large counts compactly: 1234567 → "1.2M", 98432 → "98.4K", 999 → "999" */
diff --git a/packages/ui/src/stats/arrivals-timeline.tsx b/packages/ui/src/stats/arrivals-timeline.tsx
index a41ee8617..1537c9583 100644
--- a/packages/ui/src/stats/arrivals-timeline.tsx
+++ b/packages/ui/src/stats/arrivals-timeline.tsx
@@ -15,7 +15,14 @@ const INITIAL_SHOWN = 12;
* timeline axis would compress the early years into nothing on a repo whose
* hiring accelerated.
*/
-export function ArrivalsTimeline({ arrivals }: { arrivals: StatsArrival[] }) {
+export function ArrivalsTimeline({
+ arrivals,
+ partialSince = null,
+}: {
+ arrivals: StatsArrival[];
+ /** Start of the indexed commit window when it is not the whole history. */
+ partialSince?: string | null | undefined;
+}) {
const [expanded, setExpanded] = React.useState(false);
const dated = (arrivals ?? []).filter((a) => a.first_commit_at);
if (dated.length === 0) return null;
@@ -26,22 +33,30 @@ export function ArrivalsTimeline({ arrivals }: { arrivals: StatsArrival[] }) {
return (
<section aria-label="Contributor arrivals" className="flex flex-col gap-4">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
- <h3 className="text-base font-semibold text-[var(--color-text-primary)]">Arrivals</h3>
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- {formatNumber(dated.length)} contributors
+ <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ {partialSince ? "First seen" : "Arrivals"}
+ </h3>
+ <span className="font-mono text-[10px] uppercase tabular-nums tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {formatNumber(dated.length)} people
</span>
</div>
+ {partialSince && (
+ <p className="-mt-2 text-xs text-[var(--color-text-secondary)]">
+ The index holds commits from {formatDate(partialSince)} on, so this is when each person
+ first appears in that window. Anyone here may have arrived before it.
+ </p>
+ )}
<ol className="flex flex-col divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
{shown.map((a, i) => (
<li key={`${a.name}-${a.first_commit_at}`} className="flex items-baseline gap-3 py-2.5">
- <span className="w-6 shrink-0 font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ <span className="w-6 shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
{i + 1}
</span>
- <span className="min-w-0 flex-1 truncate text-sm text-[var(--color-text-primary)]">
+ <span className="min-w-0 flex-1 break-words text-[15px] text-[var(--color-text-primary)]">
{a.name}
</span>
- <span className="shrink-0 font-mono text-[11px] tabular-nums text-[var(--color-text-secondary)]">
+ <span className="shrink-0 font-mono text-xs tabular-nums text-[var(--color-text-secondary)]">
{formatDate(a.first_commit_at as string)}
</span>
</li>
diff --git a/packages/ui/src/stats/chronotype-list.tsx b/packages/ui/src/stats/chronotype-list.tsx
index 24d21aab5..86f2bec84 100644
--- a/packages/ui/src/stats/chronotype-list.tsx
+++ b/packages/ui/src/stats/chronotype-list.tsx
@@ -4,16 +4,17 @@ import { formatNumber } from "../lib/format";
import { DEFAULT_WEEKEND_PRESET } from "./weekend";
import { contributorArchetype, NAME_MIN_COMMITS } from "./archetype";
-/** Icon and colour per earned name. Anything unlisted reads as neutral. */
-const BADGES: Record<string, { icon: typeof Moon; color: string }> = {
- "Night Owl": { icon: Moon, color: "var(--color-info)" },
- "Dawn Patrol": { icon: Sunrise, color: "var(--color-warning)" },
- "Weekend Warrior": { icon: CalendarHeart, color: "var(--color-accent-primary)" },
- "Nine to Fiver": { icon: Briefcase, color: "var(--color-text-tertiary)" },
- Clockwork: { icon: Clock, color: "var(--color-info)" },
- "The Closer": { icon: Sunset, color: "var(--color-warning)" },
- "Afternoon Regular": { icon: Sun, color: "var(--color-text-tertiary)" },
- Daylight: { icon: Sun, color: "var(--color-text-tertiary)" },
+/** Icon per earned name. Neutral ink throughout: a habit is not a warning,
+ * and the name already says which habit it is. */
+const BADGE_ICONS: Record<string, typeof Moon> = {
+ "Night Owl": Moon,
+ "Dawn Patrol": Sunrise,
+ "Weekend Warrior": CalendarHeart,
+ "Nine to Fiver": Briefcase,
+ Clockwork: Clock,
+ "The Closer": Sunset,
+ "Afternoon Regular": Sun,
+ Daylight: Sun,
};
/** Fallback for people under the naming floor, or payloads without histograms. */
@@ -54,10 +55,10 @@ export function ChronotypeList({
return (
<section aria-label="Commit-hour habits" className="flex flex-col gap-4">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
- <h3 className="text-base font-semibold text-[var(--color-text-primary)]">
+ <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">
How everyone ships
</h3>
- <span className="font-mono text-[11px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Each person&apos;s local time
</span>
</div>
@@ -65,9 +66,7 @@ export function ChronotypeList({
<ul className="flex flex-col divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
{people.map((p) => {
const earned = contributorArchetype(p, weekendDays);
- const badge = earned ? BADGES[earned.name] : undefined;
- const Icon = badge?.icon ?? Sun;
- const color = badge?.color ?? "var(--color-text-tertiary)";
+ const Icon = (earned && BADGE_ICONS[earned.name]) || Sun;
const text = earned?.name ?? PLAIN[p.label] ?? PLAIN.daylight;
const why = earned
? `${earned.because}, over ${formatNumber(p.commits)} commits.`
@@ -75,7 +74,7 @@ export function ChronotypeList({
return (
<li key={p.name} className="flex items-center gap-4 py-3">
<div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium text-[var(--color-text-primary)]">
+ <p className="break-words text-[15px] font-medium text-[var(--color-text-primary)]">
{p.name}
</p>
<p className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
@@ -83,11 +82,10 @@ export function ChronotypeList({
</p>
</div>
<span
- className="flex shrink-0 cursor-help items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium"
- style={{ color, borderColor: color }}
+ className="flex shrink-0 cursor-help items-center gap-1.5 text-xs font-medium text-[var(--color-text-secondary)]"
title={why}
>
- <Icon className="h-3.5 w-3.5" />
+ <Icon className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" aria-hidden />
{text}
</span>
</li>
diff --git a/packages/ui/src/stats/churn-ledger.tsx b/packages/ui/src/stats/churn-ledger.tsx
index 61069e883..adb422a14 100644
--- a/packages/ui/src/stats/churn-ledger.tsx
+++ b/packages/ui/src/stats/churn-ledger.tsx
@@ -23,11 +23,11 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
const figures = [
{ label: "Written", value: data.lines_added, tone: "var(--color-text-primary)" },
- { label: "Taken back", value: data.lines_deleted, tone: "var(--color-error)" },
+ { label: "Taken back", value: data.lines_deleted, tone: "var(--color-text-secondary)" },
// `standing`, not the server's `net`: a repo that has deleted more than it
// ever added (a big vendored-tree removal) drives net negative, which would
// read as "-40,000 still standing" beside a bar showing zero.
- { label: "Still standing", value: standing, tone: "var(--color-success)" },
+ { label: "Still standing", value: standing, tone: "var(--color-text-primary)" },
];
return (
@@ -40,10 +40,10 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
)} were later deleted`}
>
<div
- className="relative shrink-0 bg-[var(--color-success-muted)]"
+ className="relative shrink-0 bg-[var(--color-bg-elevated)]"
style={{ width: `${standingPct}%` }}
>
- <span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[11px] uppercase tracking-[0.06em] text-[var(--color-success)]">
+ <span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--color-text-primary)]">
{formatNumber(standing)} standing
</span>
</div>
@@ -53,10 +53,10 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
// Hatching rather than a flat fill: the deleted share is a texture
// over the same track, not a separate quantity beside it.
background:
- "repeating-linear-gradient(-45deg, var(--color-error-muted) 0 6px, transparent 6px 12px)",
+ "repeating-linear-gradient(-45deg, var(--color-border-default) 0 6px, transparent 6px 12px)",
}}
>
- <span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[11px] uppercase tracking-[0.06em] text-[var(--color-error)]">
+ <span className="absolute inset-0 flex items-center truncate px-3 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--color-text-secondary)]">
{formatNumber(deleted)} cut
</span>
</div>
@@ -69,7 +69,7 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
{f.label}
</p>
<p
- className="text-2xl font-semibold tabular-nums leading-tight"
+ className="text-[22px] font-semibold tabular-nums leading-tight"
style={{ color: f.tone }}
>
{formatNumber(f.value)}
@@ -80,7 +80,7 @@ export function ChurnLedger({ data }: { data: StatsChurn }) {
<p className="text-[15px] text-[var(--color-text-primary)]">
For every 100 lines ever written here,{" "}
- <strong className="font-semibold text-[var(--color-accent-primary)]">
+ <strong className="font-semibold">
{Math.round(data.deleted_per_hundred)} were taken back
</strong>
.
diff --git a/packages/ui/src/stats/index.ts b/packages/ui/src/stats/index.ts
index af6f1ba9f..78bca43fd 100644
--- a/packages/ui/src/stats/index.ts
+++ b/packages/ui/src/stats/index.ts
@@ -1,4 +1,3 @@
-export { SizeClassHero } from "./size-class-hero";
export {
StatCallout,
NLOC_HINT,
@@ -9,7 +8,8 @@ export {
export { OriginBlock } from "./origin-block";
export { ChurnLedger } from "./churn-ledger";
export { StatRibbon, type RibbonStat } from "./stat-ribbon";
-export { RecordsGrid } from "./records-grid";
+export { RecordsList, type RecordLinks } from "./records-list";
+export { StatsReport, type StatsReportProps } from "./stats-report";
export { ChronotypeList } from "./chronotype-list";
export { ArrivalsTimeline } from "./arrivals-timeline";
export { PunchCard } from "./punch-card";
diff --git a/packages/ui/src/stats/origin-block.tsx b/packages/ui/src/stats/origin-block.tsx
index 42cc79563..f8bc77ef7 100644
--- a/packages/ui/src/stats/origin-block.tsx
+++ b/packages/ui/src/stats/origin-block.tsx
@@ -8,7 +8,7 @@ import { formatAgeDays, formatNumber, parseDate } from "../lib/format";
* it locally would show two different birthdays to two people looking at the
* same repo (and slip a day for anyone far enough east or west). */
function foundingDate(iso: string): string {
- return parseDate(iso).toLocaleDateString(undefined, {
+ return parseDate(iso).toLocaleDateString("en-US", {
day: "numeric",
month: "short",
year: "numeric",
@@ -20,7 +20,7 @@ function foundingDate(iso: string): string {
* The repo's opening line, set as a commit rather than a statistic.
*
* Every other date on this page is a measurement; this one is the project's
- * origin story, so it gets the page's only quotation treatment — an amber rule,
+ * origin story, so it gets the page's only quotation treatment: a heavier rule,
* the subject in mono at display size, and the prose underneath doing the work
* that a "Project age: 1,232 days" tile never could.
*
@@ -37,9 +37,9 @@ export function OriginBlock({ data }: { data: StatsOrigin }) {
return (
<section
aria-label="Project origin"
- className="border-l-2 border-[var(--color-accent-primary)] pl-5"
+ className="border-l-2 border-[var(--color-border-hover)] pl-5"
>
- <p className="font-mono text-[11px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Root commit · {foundingDate(data.first_commit_at)}
</p>
@@ -49,7 +49,7 @@ export function OriginBlock({ data }: { data: StatsOrigin }) {
</p>
)}
- <p className="mt-2.5 text-sm text-[var(--color-text-secondary)]">
+ <p className="mt-2.5 text-[15px] text-[var(--color-text-secondary)]">
{age ? (
<>
It started{" "}
diff --git a/packages/ui/src/stats/punch-card.tsx b/packages/ui/src/stats/punch-card.tsx
index 3032ec02d..bacab587a 100644
--- a/packages/ui/src/stats/punch-card.tsx
+++ b/packages/ui/src/stats/punch-card.tsx
@@ -4,7 +4,7 @@ import * as React from "react";
import type { StatsPunchCard } from "@repowise-dev/types/stats";
import { DEFAULT_WEEKEND_PRESET, weekendShare } from "./weekend";
import { repoArchetype } from "./archetype";
-import { parseDate } from "../lib/format";
+import { formatNumber, parseDate } from "../lib/format";
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
/** One gap value on both axes, so the cells read as an even lattice. */
@@ -40,7 +40,7 @@ function spanLabel(first: string | null, last: string | null): string | null {
? null
: // UTC deliberately: this is a coarse month label on an absolute instant,
// and rendering it in the viewer's zone can slip it across a boundary.
- d.toLocaleDateString(undefined, { month: "short", year: "numeric", timeZone: "UTC" });
+ d.toLocaleDateString("en-US", { month: "short", year: "numeric", timeZone: "UTC" });
};
const a = fmt(first);
const b = fmt(last);
@@ -161,10 +161,10 @@ export function PunchCard({
>
<div className="flex min-w-0 flex-1 flex-col gap-4">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
- <h3 className="text-base font-semibold text-[var(--color-text-primary)]">Coding rhythm</h3>
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">Coding rhythm</h3>
+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
<b className="font-medium text-[var(--color-text-secondary)]">
- {data.total.toLocaleString()}
+ {formatNumber(data.total)}
</b>{" "}
commits{span ? ` · ${span}` : ""} ·{" "}
<b className="font-medium text-[var(--color-text-secondary)]">{weekendPct}%</b> on
@@ -175,7 +175,7 @@ export function PunchCard({
{/* The readout is the chart's title line, so it holds its height rather
than reflowing the lattice every time the pointer moves. */}
<p
- className={`min-h-[1.25rem] text-sm transition-colors ${
+ className={`min-h-[1.25rem] text-[15px] transition-colors ${
hover
? "font-medium text-[var(--color-text-primary)]"
: "text-[var(--color-text-secondary)]"
@@ -356,10 +356,10 @@ export function PunchCard({
<span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Ships like a
</span>
- <span className="text-xl font-semibold leading-tight text-[var(--color-accent-primary)]">
+ <span className="text-[22px] font-semibold leading-tight text-[var(--color-text-primary)]">
{archetype.name}
</span>
- <span className="text-[11px] leading-snug text-[var(--color-text-tertiary)]">
+ <span className="text-xs leading-snug text-[var(--color-text-secondary)]">
{archetype.because}
</span>
</div>
@@ -370,7 +370,7 @@ export function PunchCard({
<span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Quietest stretch
</span>
- <p className="text-[13px] leading-snug text-[var(--color-text-secondary)]">
+ <p className="text-xs leading-snug text-[var(--color-text-secondary)]">
No commit has ever landed between{" "}
<span className="font-mono">{hourLabel(quiet.from)}</span> and{" "}
<span className="font-mono">{hourLabel((quiet.to + 1) % 24)}</span>.
@@ -382,7 +382,7 @@ export function PunchCard({
<span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Hottest slot
</span>
- <p className="text-[13px] leading-snug text-[var(--color-text-secondary)]">
+ <p className="text-xs leading-snug text-[var(--color-text-secondary)]">
<span className="font-mono">
{weekdayLong(data.peak.weekday).slice(0, 3)} {hourLabel(data.peak.hour)}
</span>
diff --git a/packages/ui/src/stats/records-grid.tsx b/packages/ui/src/stats/records-grid.tsx
deleted file mode 100644
index 42287fad6..000000000
--- a/packages/ui/src/stats/records-grid.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-import * as React from "react";
-import {
- Boxes,
- FileText,
- GitCommitHorizontal,
- Hourglass,
- Network,
- Repeat,
- Ruler,
- ScrollText,
- Spline,
- Workflow,
- Zap,
-} from "lucide-react";
-import type { StatsRecords } from "@repowise-dev/types/stats";
-import { formatNumber, formatRelativeTimeOrNull, truncatePath } from "../lib/format";
-
-interface AwardRow {
- key: string;
- icon: React.ComponentType<{ className?: string }>;
- title: string;
- primary: string;
- detail: string;
-}
-
-function buildAwards(s: StatsRecords): AwardRow[] {
- const rows: AwardRow[] = [];
- if (s.largest_file) {
- rows.push({
- key: "largest",
- icon: FileText,
- title: "Largest file",
- primary: truncatePath(s.largest_file.path, 42),
- detail: `${formatNumber(s.largest_file.nloc)} lines`,
- });
- }
- if (s.gnarliest_file) {
- rows.push({
- key: "gnarliest",
- icon: Spline,
- title: "Gnarliest file",
- primary: truncatePath(s.gnarliest_file.path, 42),
- detail: `cyclomatic complexity ${formatNumber(s.gnarliest_file.max_ccn)}`,
- });
- }
- if (s.most_complex_symbol) {
- rows.push({
- key: "complex",
- icon: Workflow,
- title: "Most complex symbol",
- primary: s.most_complex_symbol.name,
- detail: `complexity ${formatNumber(s.most_complex_symbol.complexity)} · ${truncatePath(
- s.most_complex_symbol.file_path,
- 32,
- )}`,
- });
- }
- if (s.most_changed_file) {
- rows.push({
- key: "changed",
- icon: GitCommitHorizontal,
- title: "Most-changed file",
- primary: truncatePath(s.most_changed_file.path, 42),
- detail: `${formatNumber(s.most_changed_file.commit_count)} commits`,
- });
- }
- if (s.oldest_file) {
- rows.push({
- key: "oldest",
- icon: Hourglass,
- title: "Oldest file",
- primary: truncatePath(s.oldest_file.path, 42),
- detail: `first commit ${formatRelativeTimeOrNull(s.oldest_file.first_commit_at)}`,
- });
- }
- if (s.most_central_file) {
- const central = s.most_central_file;
- rows.push({
- key: "central",
- icon: Network,
- title: central.import_count != null ? "Most imported file" : "Most central file",
- primary: truncatePath(central.path, 42),
- detail:
- central.import_count != null
- ? `imported by ${formatNumber(central.import_count)} files · PageRank ${central.pagerank.toFixed(4)}`
- : `PageRank ${central.pagerank.toFixed(4)}`,
- });
- }
- if (s.biggest_commit) {
- rows.push({
- key: "biggest-commit",
- icon: Zap,
- title: "Biggest commit",
- primary: s.biggest_commit.subject || s.biggest_commit.sha.slice(0, 10),
- detail: `${formatNumber(s.biggest_commit.lines_changed)} lines across ${formatNumber(
- s.biggest_commit.files_changed,
- )} files — in one commit`,
- });
- }
- if (s.widest_commit) {
- rows.push({
- key: "widest-commit",
- icon: Ruler,
- title: "Widest commit",
- primary: s.widest_commit.subject || s.widest_commit.sha.slice(0, 10),
- detail: `touched ${formatNumber(s.widest_commit.files_changed)} files at once`,
- });
- }
- if (s.strongest_coupling) {
- rows.push({
- key: "coupling",
- icon: Boxes,
- title: "Strongest hidden coupling",
- primary: `${truncatePath(s.strongest_coupling.a, 26)} ↔ ${truncatePath(
- s.strongest_coupling.b,
- 26,
- )}`,
- detail: `changed together ${formatNumber(Math.round(s.strongest_coupling.count))}×`,
- });
- }
- // Import cycles have no other surface in the app — Architecture visualises the
- // graph but never detects or counts circular imports.
- if (s.largest_cycle && s.largest_cycle.files > 1) {
- rows.push({
- key: "cycle",
- icon: Repeat,
- title: "Largest import cycle",
- primary: `${formatNumber(s.largest_cycle.files)} files in a loop`,
- detail: `${formatNumber(s.largest_cycle.cycle_count)} circular cluster${
- s.largest_cycle.cycle_count === 1 ? "" : "s"
- } in total`,
- });
- }
- if (s.symbol_shape && s.symbol_shape.total > 0) {
- const shape = s.symbol_shape;
- rows.push({
- key: "documented",
- icon: ScrollText,
- title: "Documented symbols",
- primary: `${Math.round(shape.documented_pct)}% carry a docstring`,
- detail: `${formatNumber(shape.documented_count)} of ${formatNumber(shape.total)} symbols · ${Math.round(
- shape.async_pct,
- )}% async`,
- });
- }
- return rows;
-}
-
-/**
- * The repo's records — biggest, oldest, gnarliest, most tangled.
- *
- * Several of these are the only headline treatment their signal gets anywhere:
- * cyclomatic complexity is otherwise a sortable column on Code Health, and
- * import cycles have no UI at all. Renders only awards that have data, so a
- * young repo shows a short grid rather than a wall of dashes.
- */
-export function RecordsGrid({ records }: { records: StatsRecords }) {
- const awards = buildAwards(records);
- if (awards.length === 0) return null;
-
- return (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {awards.map((a) => {
- const Icon = a.icon;
- return (
- <div
- key={a.key}
- className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4"
- >
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <Icon className="h-4 w-4" />
- <span className="text-[11px] font-medium uppercase tracking-wider">{a.title}</span>
- </div>
- <p
- className="mt-2 truncate text-sm font-semibold text-[var(--color-text-primary)]"
- title={a.primary}
- >
- {a.primary}
- </p>
- <p
- className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]"
- title={a.detail}
- >
- {a.detail}
- </p>
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/packages/ui/src/stats/records-list.tsx b/packages/ui/src/stats/records-list.tsx
new file mode 100644
index 000000000..bcec27440
--- /dev/null
+++ b/packages/ui/src/stats/records-list.tsx
@@ -0,0 +1,248 @@
+import * as React from "react";
+import type { StatsRecords } from "@repowise-dev/types/stats";
+import { formatNumber } from "../lib/format";
+
+export interface RecordLinks {
+ fileHref?: ((path: string) => string) | undefined;
+ commitHref?: ((sha: string) => string) | undefined;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+interface RecordRow {
+ key: string;
+ title: string;
+ /** The subject: a path, a symbol, a commit subject or a sentence. Never truncated. */
+ primary: string;
+ mono?: boolean;
+ detail: string;
+ href?: string | undefined;
+}
+
+type Href = (value: string) => string | undefined;
+
+/** A path that wraps after a slash instead of mid-name. */
+function breakable(text: string): React.ReactNode {
+ const parts = text.split("/");
+ return parts.map((part, i) => (
+ <React.Fragment key={i}>
+ {part}
+ {i < parts.length - 1 && (
+ <>
+ /<wbr />
+ </>
+ )}
+ </React.Fragment>
+ ));
+}
+
+function fileName(path: string): string {
+ return path.split("/").pop() || path;
+}
+
+function fileRow(key: string, title: string, path: string, detail: string, file: Href): RecordRow {
+ return { key, title, primary: path, mono: true, detail, href: file(path) };
+}
+
+function fileRows(r: StatsRecords, file: Href): RecordRow[] {
+ const rows: RecordRow[] = [];
+ if (r.largest_file) {
+ const f = r.largest_file;
+ rows.push(fileRow("largest", "Largest file", f.path, `${formatNumber(f.nloc)} lines of code`, file));
+ }
+ // Usually the file holding the most complex symbol, which that row already
+ // names with the function attached.
+ if (r.gnarliest_file && r.most_complex_symbol?.file_path !== r.gnarliest_file.path) {
+ const f = r.gnarliest_file;
+ const detail = `cyclomatic complexity ${formatNumber(f.max_ccn)} in one function`;
+ rows.push(fileRow("gnarliest", "Gnarliest file", f.path, detail, file));
+ }
+ if (r.most_changed_file) {
+ const f = r.most_changed_file;
+ const detail = `changed in ${formatNumber(f.commit_count)} commits`;
+ rows.push(fileRow("changed", "Most-changed file", f.path, detail, file));
+ }
+ if (r.most_central_file) {
+ const c = r.most_central_file;
+ const title = c.import_count != null ? "Most imported file" : "Most central file";
+ const detail =
+ c.import_count != null
+ ? `imported by ${formatNumber(c.import_count)} files`
+ : `PageRank ${c.pagerank.toFixed(4)}`;
+ rows.push(fileRow("central", title, c.path, detail, file));
+ }
+ if (r.day_one_files) {
+ const d = r.day_one_files;
+ rows.push({
+ key: "day-one",
+ title: "Here since day one",
+ primary: `${formatNumber(d.count)} ${d.count === 1 ? "file dates" : "files date"} back to the root commit`,
+ detail: `of ${formatNumber(d.of)} files with a full history`,
+ });
+ }
+ return rows;
+}
+
+function functionRow(
+ key: string,
+ title: string,
+ f: { name: string; file_path: string },
+ detail: string,
+ file: Href,
+): RecordRow {
+ return {
+ key,
+ title,
+ primary: f.name,
+ mono: true,
+ detail: `${detail}, in ${fileName(f.file_path)}`,
+ href: file(f.file_path),
+ };
+}
+
+function functionRows(r: StatsRecords, file: Href): RecordRow[] {
+ const rows: RecordRow[] = [];
+ if (r.longest_function) {
+ const f = r.longest_function;
+ rows.push(functionRow("longest-fn", "Longest function", f, `${formatNumber(f.lines)} lines`, file));
+ }
+ if (r.most_patched_function) {
+ const f = r.most_patched_function;
+ const detail = `${formatNumber(f.mod_count)} commits own its current lines`;
+ rows.push(functionRow("patched", "Most patched function", f, detail, file));
+ }
+ if (r.most_complex_symbol) {
+ const s = r.most_complex_symbol;
+ const f = { name: s.name, file_path: s.file_path };
+ rows.push(functionRow("complex", "Most complex symbol", f, `complexity ${formatNumber(s.complexity)}`, file));
+ }
+ if (r.longest_name) {
+ const f = r.longest_name;
+ rows.push(functionRow("longest-name", "Longest name", f, `${f.name.length} characters`, file));
+ }
+ if (r.most_common_name) {
+ const c = r.most_common_name;
+ rows.push({
+ key: "common-name",
+ title: "Most reused name",
+ primary: c.name,
+ mono: true,
+ detail: `${formatNumber(c.count)} different functions share it`,
+ });
+ }
+ if (r.symbol_shape && r.symbol_shape.total > 0) {
+ const s = r.symbol_shape;
+ rows.push({
+ key: "documented",
+ title: "Documented symbols",
+ primary: `${Math.round(s.documented_pct)}% carry a docstring`,
+ detail: `${formatNumber(s.documented_count)} of ${formatNumber(s.total)} symbols, and ${Math.round(
+ s.async_pct,
+ )}% of them are async`,
+ });
+ }
+ return rows;
+}
+
+function commitRows(r: StatsRecords, commit: Href): RecordRow[] {
+ const row = (key: string, title: string, c: { sha: string; subject: string }, detail: string) => ({
+ key,
+ title,
+ primary: c.subject || c.sha.slice(0, 10),
+ detail,
+ href: commit(c.sha),
+ });
+ const rows: RecordRow[] = [];
+ if (r.biggest_commit) {
+ const c = r.biggest_commit;
+ const detail = `${formatNumber(c.lines_changed)} lines across ${formatNumber(c.files_changed)} files`;
+ rows.push(row("biggest", "Biggest commit", c, detail));
+ }
+ if (r.widest_commit) {
+ const c = r.widest_commit;
+ rows.push(row("widest", "Widest commit", c, `touched ${formatNumber(c.files_changed)} files at once`));
+ }
+ if (r.biggest_purge) {
+ const c = r.biggest_purge;
+ const detail = `removed ${formatNumber(c.lines_deleted - c.lines_added)} more lines than it added`;
+ rows.push(row("purge", "Biggest cleanup", c, detail));
+ }
+ return rows;
+}
+
+function structureRows(r: StatsRecords): RecordRow[] {
+ const c = r.largest_cycle;
+ if (!c || c.files <= 1) return [];
+ return [
+ {
+ key: "cycle",
+ title: "Largest import cycle",
+ primary: `${formatNumber(c.files)} files import each other in a loop`,
+ detail: `${formatNumber(c.cycle_count)} circular cluster${c.cycle_count === 1 ? "" : "s"} in total`,
+ },
+ ];
+}
+
+/**
+ * The repo's records: biggest, longest, most patched, most tangled.
+ *
+ * Hairline rows grouped by subject. The subject is never truncated, and a row
+ * whose subject has a page links to it. `commitScope` qualifies the commit
+ * group when it was drawn from part of the history.
+ */
+export function RecordsList({
+ records,
+ commitScope,
+ ...links
+}: { records: StatsRecords; commitScope?: string | undefined } & RecordLinks) {
+ const file: Href = (path) => links.fileHref?.(path);
+ const commit: Href = (sha) => links.commitHref?.(sha);
+ const groups = [
+ { title: "Files", rows: fileRows(records, file) },
+ { title: "Functions", rows: functionRows(records, file) },
+ { title: commitScope ? `Commits, ${commitScope}` : "Commits", rows: commitRows(records, commit) },
+ { title: "Structure", rows: structureRows(records) },
+ ].filter((g) => g.rows.length > 0);
+ if (groups.length === 0) return null;
+ const A = links.LinkComponent ?? "a";
+
+ return (
+ <div className="grid grid-cols-1 gap-x-10 gap-y-8 lg:grid-cols-2">
+ {groups.map((g) => (
+ <section key={g.title} aria-label={g.title} className="min-w-0">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {g.title}
+ </h3>
+ <dl className="mt-2 divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {g.rows.map((row) => {
+ const text = row.mono ? breakable(row.primary) : row.primary;
+ return (
+ <div key={row.key} className="min-w-0 py-3">
+ <dt className="text-xs text-[var(--color-text-tertiary)]">{row.title}</dt>
+ <dd
+ className={`mt-0.5 break-words text-[15px] font-medium text-[var(--color-text-primary)] ${
+ row.mono ? "font-mono" : ""
+ }`}
+ >
+ {row.href ? (
+ <A
+ href={row.href}
+ className="text-[var(--color-text-primary)] underline decoration-[var(--color-border-default)] underline-offset-4 hover:text-[var(--color-accent-primary)] hover:decoration-current focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-accent-primary)]"
+ >
+ {text}
+ </A>
+ ) : (
+ text
+ )}
+ </dd>
+ <dd className="mt-0.5 text-xs tabular-nums text-[var(--color-text-secondary)]">
+ {row.detail}
+ </dd>
+ </div>
+ );
+ })}
+ </dl>
+ </section>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/ui/src/stats/size-class-hero.tsx b/packages/ui/src/stats/size-class-hero.tsx
deleted file mode 100644
index ff5e34942..000000000
--- a/packages/ui/src/stats/size-class-hero.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import * as React from "react";
-import {
- Sprout,
- Home,
- Building,
- Building2,
- Landmark,
- Globe2,
-} from "lucide-react";
-import type { StatsScale } from "@repowise-dev/types/stats";
-
-const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {
- Seedling: Sprout,
- Hamlet: Home,
- Village: Home,
- Town: Building,
- City: Building2,
- Metropolis: Landmark,
- Megalopolis: Globe2,
-};
-
-interface SizeClassHeroProps {
- scale: StatsScale;
- /** Repo name, rendered as the eyebrow above the size-class label. */
- repoName?: string;
-}
-
-/**
- * The Stats page's opening statement: a warm-washed banner naming the
- * codebase's "size class" (derived from NLOC).
- *
- * Identity only. The headline figures used to sit here as four bordered tiles,
- * which put a boxed number immediately above the hairline ribbon carrying the
- * same four numbers — the ribbon owns them now, and the hero says the one thing
- * a count can't: what kind of place this is.
- */
-export function SizeClassHero({ scale, repoName }: SizeClassHeroProps) {
- const Icon = SIZE_ICON[scale.size_class.name] ?? Building2;
-
- return (
- <div
- className="relative overflow-hidden rounded-2xl border border-[var(--color-border-default)] p-6 sm:p-8"
- style={{ background: "var(--gradient-warm-wash, var(--color-bg-surface))" }}
- >
- <div className="min-w-0">
- {repoName && (
- <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--color-text-tertiary)]">
- {repoName}
- </p>
- )}
- <div className="mt-2 flex items-center gap-3">
- <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-[var(--color-accent-muted,var(--color-bg-elevated))] text-[var(--color-accent-primary)]">
- <Icon className="h-6 w-6" />
- </span>
- <div className="min-w-0">
- <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- This codebase is a
- </p>
- <h2 className="text-2xl font-bold leading-tight text-[var(--color-text-primary)] sm:text-3xl">
- {scale.size_class.name}
- </h2>
- </div>
- </div>
- <p className="mt-3 max-w-md text-sm text-[var(--color-text-secondary)]">
- {scale.size_class.blurb}
- </p>
- </div>
- </div>
- );
-}
diff --git a/packages/ui/src/stats/stat-callout.tsx b/packages/ui/src/stats/stat-callout.tsx
index f0a74ff51..e3912a49d 100644
--- a/packages/ui/src/stats/stat-callout.tsx
+++ b/packages/ui/src/stats/stat-callout.tsx
@@ -6,7 +6,7 @@ export type CalloutTone = "default" | "accent" | "success" | "warning" | "info";
// Canonical clarifications for the two most-misread stats, shared by every
// surface that shows them (stats tabs, overview teaser, size-class hero).
export const NLOC_HINT =
- "Lines of code in the repo today: non-blank, non-comment lines, excluding lockfiles, generated and vendored files. Not a historical total — deleted code doesn't count.";
+ "Lines of code in the repo today: non-blank, non-comment lines, excluding lockfiles, generated and vendored files. Not a historical total: deleted code doesn't count.";
export const AGENT_PCT_HINT =
"Share of commits with a verifiable agent signature: known bot identities, agent commit footers, or Co-authored-by agent trailers. Squash merges that drop trailers and agents committing under a human git identity can't be detected, so the true share may be higher.";
diff --git a/packages/ui/src/stats/stat-ribbon.tsx b/packages/ui/src/stats/stat-ribbon.tsx
index 596b75ff6..688a90eb8 100644
--- a/packages/ui/src/stats/stat-ribbon.tsx
+++ b/packages/ui/src/stats/stat-ribbon.tsx
@@ -42,6 +42,25 @@ export interface RibbonStat {
* Rendered as a `<dl>` because that is what it is — labelled values, not a
* layout grid.
*/
+// Column counts follow the number of cells, so four figures fill the row
+// instead of leaving a blank fifth column. Static class names for Tailwind.
+const BASE_COLS = ["", "grid-cols-1", "grid-cols-2"];
+const SM_COLS = ["", "sm:grid-cols-1", "sm:grid-cols-2", "sm:grid-cols-3"];
+const LG_COLS = ["", "lg:grid-cols-1", "lg:grid-cols-2", "lg:grid-cols-3", "lg:grid-cols-4", "lg:grid-cols-5"];
+
+/** Hairlines between cells only; the outer edges come from the wrapper's border-y. */
+function hairlines(i: number, n: number): string {
+ const [base, sm, lg] = [Math.min(n, 2), Math.min(n, 3), Math.min(n, 5)];
+ return [
+ i % base ? "border-l" : "border-l-0",
+ i >= base ? "border-t" : "border-t-0",
+ i % sm ? "sm:border-l" : "sm:border-l-0",
+ i >= sm ? "sm:border-t" : "sm:border-t-0",
+ i % lg ? "lg:border-l" : "lg:border-l-0",
+ i >= lg ? "lg:border-t" : "lg:border-t-0",
+ ].join(" ");
+}
+
export function StatRibbon({
stats,
LinkComponent,
@@ -53,27 +72,18 @@ export function StatRibbon({
const shown = stats.filter((s) => s.value);
if (shown.length === 0) return null;
const A = LinkComponent ?? "a";
+ const n = shown.length;
return (
- <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3 lg:grid-cols-5">
+ <dl
+ className={`grid border-y border-[var(--color-border-default)] ${BASE_COLS[Math.min(n, 2)]} ${
+ SM_COLS[Math.min(n, 3)]
+ } ${LG_COLS[Math.min(n, 5)]}`}
+ >
{shown.map((s, i) => (
<div
key={s.label}
- className={[
- s.href ? "" : "px-4 py-3.5",
- // Hairlines between cells only — the outer edges come from the
- // wrapper's border-y, so cells never double up on the boundary.
- "border-[var(--color-border-default)]",
- i % 2 === 1 ? "border-l" : "",
- i >= 2 ? "border-t" : "",
- "sm:border-l sm:border-t-0",
- i % 3 === 0 ? "sm:border-l-0" : "",
- i >= 3 ? "sm:border-t" : "",
- "lg:border-l lg:border-t-0",
- i % 5 === 0 ? "lg:border-l-0" : "",
- ]
- .filter(Boolean)
- .join(" ")}
+ className={`${s.href ? "" : "px-4 py-3.5"} border-[var(--color-border-default)] ${hairlines(i, n)}`}
>
{s.href ? (
// The link wraps the whole cell rather than the value, so the
@@ -96,6 +106,11 @@ export function StatRibbon({
>
{s.value}
</dd>
+ {s.sub && (
+ <dd className="mt-0.5 text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {s.sub}
+ </dd>
+ )}
</A>
) : (
<>
diff --git a/packages/ui/src/stats/stats-report.tsx b/packages/ui/src/stats/stats-report.tsx
new file mode 100644
index 000000000..e3ec67613
--- /dev/null
+++ b/packages/ui/src/stats/stats-report.tsx
@@ -0,0 +1,266 @@
+import * as React from "react";
+import type { StatsHighlights } from "@repowise-dev/types/stats";
+import { PageLede } from "../shared/page-lede";
+import { formatAgeDays, formatDate, formatNumber } from "../lib/format";
+import { ArrivalsTimeline } from "./arrivals-timeline";
+import { ChronotypeList } from "./chronotype-list";
+import { ChurnLedger } from "./churn-ledger";
+import { OriginBlock } from "./origin-block";
+import { PunchCard } from "./punch-card";
+import { RecordsList, type RecordLinks } from "./records-list";
+import { NLOC_HINT } from "./stat-callout";
+import { StatRibbon, type RibbonStat } from "./stat-ribbon";
+import { DEFAULT_WEEKEND_PRESET } from "./weekend";
+
+export interface StatsReportProps extends RecordLinks {
+ data: StatsHighlights;
+ /** Weekday indices (0 = Monday) the reader counts as the weekend. */
+ weekendDays?: readonly number[];
+ contributorsHref?: string | undefined;
+}
+
+function Section({
+ title,
+ lede,
+ children,
+}: {
+ title: string;
+ lede?: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <section aria-label={title} className="flex flex-col gap-5">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-[22px] font-semibold text-[var(--color-text-primary)]">{title}</h2>
+ {lede && (
+ <p className="max-w-[72ch] text-xs text-[var(--color-text-secondary)]">{lede}</p>
+ )}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function monthLabel(key: string): string {
+ const [y, m] = key.split("-");
+ // Built from parts so the browser's offset can never nudge it across a month.
+ return new Date(Number(y), Number(m) - 1, 1).toLocaleDateString("en-US", {
+ month: "short",
+ year: "numeric",
+ });
+}
+
+function hoursLabel(hours: number): string {
+ if (hours < 48) return `${hours} hours`;
+ return formatAgeDays(Math.floor(hours / 24));
+}
+
+function span(start: string, end: string): string {
+ return `${formatDate(start)} to ${formatDate(end)}`;
+}
+
+function languageMix(data: StatsHighlights): string | undefined {
+ const langs = data.scale.languages ?? [];
+ const total = langs.reduce((a, l) => a + l.file_count, 0);
+ if (total === 0) return undefined;
+ return langs
+ .slice(0, 2)
+ .map((l) => `${l.language} ${Math.round((l.file_count / total) * 100)}%`)
+ .join(", ");
+}
+
+function identityStats(data: StatsHighlights): RibbonStat[] {
+ const { scale, origin } = data;
+ return [
+ { label: "Files", value: formatNumber(scale.file_count) },
+ { label: "Symbols", value: formatNumber(scale.symbol_count) },
+ { label: "Modules", value: formatNumber(scale.module_count) },
+ {
+ label: "Languages",
+ value: formatNumber(scale.language_count),
+ sub: languageMix(data),
+ hint: "Programming languages by file count. Data and markup formats such as JSON, YAML and Markdown are not counted.",
+ },
+ { label: "Commits", value: formatNumber(origin.total_commits) },
+ ];
+}
+
+function rhythmStats(rhythm: StatsHighlights["rhythm"]): RibbonStat[] {
+ const { longest_streak: streak, longest_silence: silence, busiest_day: day } = rhythm;
+ const v = rhythm.velocity;
+ const month = rhythm.busiest_month;
+ const cells: (RibbonStat | null)[] = [
+ streak
+ ? { label: "Longest streak", value: `${formatNumber(streak.days)} days`, sub: span(streak.start, streak.end) }
+ : null,
+ silence
+ ? {
+ label: "Longest silence",
+ value: hoursLabel(silence.hours),
+ sub: span(silence.start, silence.end),
+ hint: "The longest gap between two consecutive commits.",
+ }
+ : null,
+ day
+ ? { label: "Busiest day", value: `${formatNumber(day.commits)} commits`, sub: formatDate(day.date) }
+ : null,
+ rhythm.code_half_life_days != null
+ ? {
+ label: "Code half-life",
+ value: `${formatNumber(rhythm.code_half_life_days)} days`,
+ sub: "half the files have gone unchanged this long",
+ hint: "Median time since each file was last changed, measured from the newest commit.",
+ }
+ : null,
+ v && v.pct_change != null
+ ? {
+ label: "Momentum",
+ value: `${v.pct_change >= 0 ? "+" : ""}${v.pct_change}%`,
+ sub: `${formatNumber(v.recent_90d)} commits in 90 days vs ${formatNumber(v.prior_90d)} before`,
+ hint: "The 90 days ending at the newest commit, against the 90 before it.",
+ }
+ : month
+ ? { label: "Busiest month", value: monthLabel(month.month), sub: `${formatNumber(month.total)} commits` }
+ : null,
+ ];
+ return cells.filter((s): s is RibbonStat => s !== null);
+}
+
+function peopleStats(people: StatsHighlights["people"], contributorsHref: string | undefined): RibbonStat[] {
+ const tf = people.truck_factor;
+ const cells: (RibbonStat | null)[] = [
+ {
+ label: "Contributors",
+ value: formatNumber(people.contributor_count),
+ sub: "people who have committed",
+ ...(contributorsHref ? { href: contributorsHref } : {}),
+ },
+ { label: "Owners", value: formatNumber(people.owner_count), sub: "own at least one file" },
+ tf != null
+ ? {
+ label: "Truck factor",
+ value: formatNumber(tf),
+ sub: tf === 1 ? "person owns most of the code" : "people own most of the code",
+ hint: "The fewest primary owners who together hold more than half the owned files.",
+ }
+ : null,
+ {
+ label: "Single-owner files",
+ value: formatNumber(people.single_owner_files),
+ sub: people.tracked_files ? `of ${formatNumber(people.tracked_files)} files` : undefined,
+ hint: "Files where one author made at least 80% of the commits.",
+ },
+ {
+ label: "Knowledge silos",
+ value: formatNumber(people.silo_count),
+ sub: "top-level folders with one dominant owner",
+ hint: "Top-level folders where one person is the primary owner of more than 80% of the files.",
+ },
+ ];
+ return cells.filter((s): s is RibbonStat => s !== null);
+}
+
+function windowSentence(data: StatsHighlights): string | undefined {
+ const sample = data.rhythm.window;
+ if (!sample?.first_at || !sample.last_at) return undefined;
+ const days = `across ${formatNumber(data.rhythm.active_days)} active days`;
+ const range = span(sample.first_at, sample.last_at);
+ return sample.complete
+ ? `Every commit from ${range}, ${days}.`
+ : `Drawn from the latest ${formatNumber(sample.commits)} of ${formatNumber(
+ data.origin.total_commits,
+ )} commits, ${range}, ${days}.`;
+}
+
+function SizeLede({ data }: { data: StatsHighlights }) {
+ const { scale } = data;
+ const testNloc = scale.test_nloc ?? 0;
+ const sourceNloc = scale.total_nloc - testNloc;
+ return (
+ <PageLede
+ label="Lines of code"
+ labelHint={NLOC_HINT}
+ value={formatNumber(scale.total_nloc)}
+ band={{ label: scale.size_class.name }}
+ layout="beside"
+ >
+ <p>
+ {data.repo.name ? `${data.repo.name} is a ${scale.size_class.name}. ` : ""}
+ {scale.size_class.blurb}
+ {testNloc > 0 && sourceNloc > 0 && (
+ <>
+ {" "}For every 100 lines of source there are{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {Math.round((testNloc / sourceNloc) * 100)} lines of tests
+ </strong>
+ .
+ </>
+ )}
+ </p>
+ </PageLede>
+ );
+}
+
+/**
+ * The whole Stats page: what the repo is, its records, when the work happens,
+ * and who does it. One scroll, because every section is already in the single
+ * payload and tabs only hid most of it.
+ *
+ * Shared by every host; the host supplies the weekend preference and whatever
+ * routes it has.
+ */
+export function StatsReport({
+ data,
+ weekendDays = DEFAULT_WEEKEND_PRESET.days,
+ contributorsHref,
+ ...links
+}: StatsReportProps) {
+ const { origin, churn, rhythm, people, records } = data;
+ const sample = rhythm.window;
+ const partial = sample != null && !sample.complete;
+ const rhythmCells = rhythmStats(rhythm);
+
+ return (
+ <div className="flex flex-col gap-12">
+ <div className="flex flex-col gap-8">
+ <SizeLede data={data} />
+ <StatRibbon stats={identityStats(data)} />
+ <OriginBlock data={origin} />
+ {churn && <ChurnLedger data={churn} />}
+ </div>
+
+ <Section
+ title="Records"
+ lede="The biggest, longest and most tangled things in the codebase. The length, naming and patch records leave test code out."
+ >
+ <RecordsList
+ records={records}
+ commitScope={partial ? `latest ${formatNumber(sample.commits)}` : undefined}
+ {...links}
+ />
+ </Section>
+
+ <Section title="When the work happens" lede={windowSentence(data)}>
+ <PunchCard
+ data={rhythm.punch_card}
+ weekendDays={weekendDays}
+ firstCommitAt={sample?.first_at ?? origin.first_commit_at}
+ lastCommitAt={sample?.last_at ?? origin.last_commit_at}
+ />
+ {rhythmCells.length > 0 && <StatRibbon stats={rhythmCells} />}
+ </Section>
+
+ <Section title="Who does it">
+ <StatRibbon stats={peopleStats(people, contributorsHref)} LinkComponent={links.LinkComponent} />
+ <ChronotypeList people={people.chronotypes} weekendDays={weekendDays} />
+ {people.chronotypes.length === 0 && rhythm.punch_card.timezone_mode === "utc" && (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ Commit-hour habits need each commit&apos;s local time, which this index does not
+ carry.
+ </p>
+ )}
+ <ArrivalsTimeline arrivals={people.arrivals} partialSince={partial ? sample.first_at : null} />
+ </Section>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/stats/page.tsx b/packages/web/src/app/repos/[id]/stats/page.tsx
index e90985cbb..c2b832d7c 100644
--- a/packages/web/src/app/repos/[id]/stats/page.tsx
+++ b/packages/web/src/app/repos/[id]/stats/page.tsx
@@ -3,7 +3,7 @@ import { notFound } from "next/navigation";
import { BarChart3 } from "lucide-react";
import { getStatsHighlights } from "@/lib/api/stats";
import { PageShell } from "@repowise-dev/ui/shared";
-import { StatsTabs } from "@/components/stats/stats-tabs";
+import { StatsView } from "@/components/stats/stats-view";
export const metadata: Metadata = { title: "Stats" };
@@ -25,10 +25,10 @@ export default async function StatsPage({ params }: Props) {
<PageShell
title="By the Numbers"
icon={<BarChart3 className="h-5 w-5" />}
- description="The things about this codebase you can't see anywhere else — how big it got, when it started, when the work actually happens, and the records it holds."
+ description="The things about this codebase you can't see anywhere else: how big it got, when it started, when the work happens, and the records it holds."
maxWidth="wide"
>
- <StatsTabs data={data} repoId={id} />
+ <StatsView data={data} repoId={id} />
</PageShell>
);
}
diff --git a/packages/web/src/components/stats/by-the-numbers-tab.tsx b/packages/web/src/components/stats/by-the-numbers-tab.tsx
deleted file mode 100644
index b933f2ea7..000000000
--- a/packages/web/src/components/stats/by-the-numbers-tab.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import {
- ChurnLedger,
- NLOC_HINT,
- OriginBlock,
- RecordsGrid,
- SizeClassHero,
- StatRibbon,
- type RibbonStat,
-} from "@repowise-dev/ui/stats";
-import { formatLOC, formatNumber } from "@repowise-dev/ui/lib/format";
-
-/**
- * Tab 1 — what this repo *is*: scale, origin, lifetime churn, records.
- *
- * Deliberately carries no health scores, commit volume or dependency counts:
- * each of those has a page that owns the subject and shows it with filtering
- * and drill-down this page could never justify. What is left is the repo's
- * fingerprint, which nothing else draws.
- */
-export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {
- const { scale, origin, churn, records, rhythm } = data;
-
- const ribbon: RibbonStat[] = [
- { label: "Lines of code", value: formatLOC(scale.total_nloc), hint: NLOC_HINT },
- { label: "Files", value: formatNumber(scale.file_count) },
- { label: "Symbols", value: formatNumber(scale.symbol_count) },
- { label: "Modules", value: formatNumber(scale.module_count) },
- { label: "Languages", value: formatNumber(scale.language_count) },
- ];
-
- return (
- <div className="flex flex-col gap-8">
- <SizeClassHero scale={scale} repoName={data.repo.name} />
-
- <OriginBlock data={origin} />
-
- <StatRibbon stats={ribbon} />
-
- {churn && <ChurnLedger data={churn} />}
-
- <section className="flex flex-col gap-4">
- <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
- <h3 className="text-base font-semibold text-[var(--color-text-primary)]">
- Records &amp; superlatives
- </h3>
- {rhythm.longest_streak && (
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- longest streak · {formatNumber(rhythm.longest_streak.days)} days
- </span>
- )}
- </div>
- <RecordsGrid records={records} />
- </section>
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/people-tab.tsx b/packages/web/src/components/stats/people-tab.tsx
deleted file mode 100644
index 4f259e7dc..000000000
--- a/packages/web/src/components/stats/people-tab.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { AlertTriangle, Users } from "lucide-react";
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { ArrivalsTimeline, ChronotypeList, StatCallout } from "@repowise-dev/ui/stats";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-import { useWeekendDays } from "@/lib/hooks/use-weekend";
-
-/**
- * Tab 3 — the human shape of the repo.
- *
- * Repo-level concentration and human-interest angles only. Per-person ownership
- * share, hotspots owned and dead-code burden all belong to the Contributors
- * page, which opens with a distribution bar and links straight into each
- * profile — a "top owners" list here would just be a worse copy of it, so this
- * tab points there instead.
- */
-export function PeopleTab({ data, repoId }: { data: StatsHighlights; repoId: string }) {
- const { people } = data;
- const utcMode = data.rhythm.punch_card.timezone_mode === "utc";
- // Same preset the punch card reads, so a person's "weekend warrior" and the
- // repo's weekend share can never disagree about which days those are.
- const weekendDays = useWeekendDays();
-
- return (
- <div className="flex flex-col gap-8">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="Contributors"
- value={formatNumber(people.contributor_count)}
- icon={<Users className="h-4 w-4" />}
- sub={`${formatNumber(people.owner_count)} own at least one file`}
- href={`/repos/${repoId}/owners`}
- LinkComponent={Link}
- />
- {people.truck_factor != null && (
- <StatCallout
- label="Truck factor"
- value={formatNumber(people.truck_factor)}
- icon={<AlertTriangle className="h-4 w-4" />}
- tone={people.truck_factor <= 2 ? "warning" : "default"}
- sub="people who together own most of the code"
- hint="The fewest primary owners who between them hold more than half the owned files. A factor of 1 means one person owns most of the codebase."
- />
- )}
- <StatCallout
- label="Single-owner files"
- value={formatNumber(people.single_owner_files)}
- tone="warning"
- sub="only one person has ever really touched them"
- />
- <StatCallout
- label="Knowledge silos"
- value={formatNumber(people.silo_count)}
- tone={people.silo_count > 0 ? "warning" : "default"}
- sub="modules where one person owns over 80%"
- />
- </div>
-
- {people.chronotypes.length > 0 ? (
- <ChronotypeList people={people.chronotypes} weekendDays={weekendDays} />
- ) : (
- utcMode && (
- <p className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 text-sm text-[var(--color-text-secondary)]">
- Commit-hour habits need each commit&apos;s local timezone, which this index was built
- before repowise captured. Run{" "}
- <code className="rounded bg-[var(--color-bg-inset)] px-1.5 py-0.5 font-mono text-xs">
- repowise update
- </code>{" "}
- to backfill it, no re-index required.
- </p>
- )
- )}
-
- <ArrivalsTimeline arrivals={people.arrivals} />
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/rhythm-tab.tsx b/packages/web/src/components/stats/rhythm-tab.tsx
deleted file mode 100644
index aa08b4975..000000000
--- a/packages/web/src/components/stats/rhythm-tab.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-"use client";
-
-import { CalendarDays, Flame, Snowflake, TrendingDown, TrendingUp } from "lucide-react";
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { PunchCard, StatCallout } from "@repowise-dev/ui/stats";
-import { formatDate, formatNumber } from "@repowise-dev/ui/lib/format";
-import { useWeekendDays } from "@/lib/hooks/use-weekend";
-
-function monthLabel(key: string): string {
- const [y, m] = key.split("-");
- // Constructed from parts rather than parsed from a string so the value is
- // never nudged across a month boundary by the browser's offset. Day is
- // pinned to the 1st and only month/year are ever displayed.
- return new Date(Number(y), Number(m) - 1, 1).toLocaleDateString(undefined, {
- month: "short",
- year: "numeric",
- });
-}
-
-/**
- * Tab 2 — when the work happens.
- *
- * The one subject with no competing page: Commits ranks individual commits by
- * risk and charts their categories over calendar time, but nothing anywhere
- * else in the app has a clock. Time-of-day, streaks, peaks, and how fast code
- * goes cold all live here.
- */
-export function RhythmTab({ data }: { data: StatsHighlights }) {
- const { rhythm } = data;
- const weekendDays = useWeekendDays();
- const vel = rhythm.velocity;
-
- const rising = vel?.pct_change != null && vel.pct_change >= 0;
- const momentum =
- vel?.pct_change != null
- ? `${rising ? "+" : ""}${vel.pct_change}%`
- : formatNumber(vel?.recent_90d ?? 0);
-
- return (
- <div className="flex flex-col gap-8">
- <PunchCard
- data={rhythm.punch_card}
- weekendDays={weekendDays}
- firstCommitAt={data.origin.first_commit_at}
- lastCommitAt={data.origin.last_commit_at}
- />
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="Momentum"
- value={momentum}
- icon={rising ? <TrendingUp className="h-4 w-4" /> : <TrendingDown className="h-4 w-4" />}
- tone={vel?.pct_change == null ? "default" : rising ? "success" : "warning"}
- sub={
- vel?.pct_change != null
- ? `${formatNumber(vel.recent_90d)} commits in 90d vs ${formatNumber(vel.prior_90d)} before`
- : `${formatNumber(vel?.recent_90d ?? 0)} commits in the last 90 days`
- }
- hint="The 90 days ending at the newest commit, against the 90 before it. Anchored to the latest commit rather than today, so a stale index doesn't read as a slowdown."
- />
-
- {rhythm.longest_streak && (
- <StatCallout
- label="Longest streak"
- value={`${formatNumber(rhythm.longest_streak.days)} days`}
- icon={<Flame className="h-4 w-4" />}
- tone="accent"
- sub={`${formatDate(rhythm.longest_streak.start)} – ${formatDate(
- rhythm.longest_streak.end,
- )}`}
- />
- )}
-
- {rhythm.busiest_day && (
- <StatCallout
- label="Busiest day"
- value={formatNumber(rhythm.busiest_day.commits)}
- icon={<CalendarDays className="h-4 w-4" />}
- sub={`commits on ${formatDate(rhythm.busiest_day.date)}`}
- />
- )}
-
- {rhythm.code_half_life_days != null && (
- <StatCallout
- label="Code half-life"
- value={`${formatNumber(rhythm.code_half_life_days)} days`}
- icon={<Snowflake className="h-4 w-4" />}
- tone="info"
- sub="half the files haven't been touched in longer than this"
- hint="Median time since each file was last changed, measured from the newest commit."
- />
- )}
- </div>
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
- {rhythm.busiest_month && (
- <StatCallout
- label="Busiest month"
- value={monthLabel(rhythm.busiest_month.month)}
- sub={`${formatNumber(rhythm.busiest_month.total)} commits`}
- />
- )}
- <StatCallout
- label="Active days"
- value={formatNumber(rhythm.active_days)}
- sub="distinct days with at least one commit"
- />
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/stats-tabs.tsx b/packages/web/src/components/stats/stats-tabs.tsx
deleted file mode 100644
index 452f77ead..000000000
--- a/packages/web/src/components/stats/stats-tabs.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-"use client";
-
-import { parseAsStringLiteral, useQueryState } from "nuqs";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/tabs";
-import { ErrorBoundary } from "@repowise-dev/ui/shared";
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { ByTheNumbersTab } from "./by-the-numbers-tab";
-import { RhythmTab } from "./rhythm-tab";
-import { PeopleTab } from "./people-tab";
-
-/**
- * Three tabs, down from five.
- *
- * "Code & Quality" and "Architecture" were removed outright: every figure on
- * them had a richer counterpart on Code Health, Architecture or Knowledge
- * Graph, and "Growth & Activity" was almost entirely the Commits page. The
- * legacy tab values still resolve so an old bookmark lands somewhere sensible
- * rather than on an empty page.
- */
-const TAB_VALUES = ["numbers", "rhythm", "people"] as const;
-type TabValue = (typeof TAB_VALUES)[number];
-
-const LEGACY_TABS: Record<string, TabValue> = {
- growth: "rhythm",
- quality: "numbers",
- architecture: "numbers",
-};
-
-export function StatsTabs({ data, repoId }: { data: StatsHighlights; repoId: string }) {
- const [raw, setTab] = useQueryState(
- "tab",
- parseAsStringLiteral([...TAB_VALUES, ...Object.keys(LEGACY_TABS)]).withDefault("numbers"),
- );
- const tab = (LEGACY_TABS[raw] ?? raw) as TabValue;
-
- return (
- <Tabs value={tab} onValueChange={(v) => setTab(v as TabValue)}>
- <TabsList>
- <TabsTrigger value="numbers">By the Numbers</TabsTrigger>
- <TabsTrigger value="rhythm">Rhythm</TabsTrigger>
- <TabsTrigger value="people">People</TabsTrigger>
- </TabsList>
- <TabsContent value="numbers" className="mt-4">
- <ErrorBoundary title="Couldn't load stats">
- <ByTheNumbersTab data={data} />
- </ErrorBoundary>
- </TabsContent>
- <TabsContent value="rhythm" className="mt-4">
- <ErrorBoundary title="Couldn't load rhythm">
- <RhythmTab data={data} />
- </ErrorBoundary>
- </TabsContent>
- <TabsContent value="people" className="mt-4">
- <ErrorBoundary title="Couldn't load contributors">
- <PeopleTab data={data} repoId={repoId} />
- </ErrorBoundary>
- </TabsContent>
- </Tabs>
- );
-}
diff --git a/packages/web/src/components/stats/stats-view.tsx b/packages/web/src/components/stats/stats-view.tsx
new file mode 100644
index 000000000..90cde2e65
--- /dev/null
+++ b/packages/web/src/components/stats/stats-view.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import Link from "next/link";
+import type { StatsHighlights } from "@repowise-dev/types/stats";
+import { StatsReport } from "@repowise-dev/ui/stats/stats-report";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { useWeekendDays } from "@/lib/hooks/use-weekend";
+
+/** Client boundary for the Stats page: the weekend preference lives in
+ * localStorage, and the route builders are functions a server component
+ * cannot pass down. */
+export function StatsView({ data, repoId }: { data: StatsHighlights; repoId: string }) {
+ const weekendDays = useWeekendDays();
+ const prefix = `/repos/${repoId}`;
+ return (
+ <StatsReport
+ data={data}
+ weekendDays={weekendDays}
+ contributorsHref={`${prefix}/owners`}
+ fileHref={(path) => fileEntityPath(prefix, path)}
+ commitHref={(sha) => `${prefix}/commits?commit=${encodeURIComponent(sha)}`}
+ LinkComponent={Link}
+ />
+ );
+}
diff --git a/tests/unit/ingestion/test_python_resolver_external.py b/tests/unit/ingestion/test_python_resolver_external.py
index 83589407a..8febcc74a 100644
--- a/tests/unit/ingestion/test_python_resolver_external.py
+++ b/tests/unit/ingestion/test_python_resolver_external.py
@@ -53,6 +53,38 @@ def test_stdlib_miss_is_external_too() -> None:
assert ctx.graph.nodes["external:subprocess"]["language"] == "external"
+def test_stdlib_import_never_stem_matches_a_nested_file() -> None:
+ path = "pkg/specs/json.py"
+ ctx = ResolverContext(path_set={*PATHS, path}, stem_map={"json": [path]}, graph=nx.DiGraph())
+ assert resolve_python_import("json", "app.py", ctx) == "external:json"
+
+
+def test_removed_stdlib_names_are_still_stdlib() -> None:
+ """``distutils`` left the stdlib in 3.12 but old setup.py files import it."""
+ path = "pkg/tools/distutils.py"
+ ctx = ResolverContext(
+ path_set={*PATHS, path}, stem_map={"distutils": [path]}, graph=nx.DiGraph()
+ )
+ assert resolve_python_import("distutils", "app.py", ctx) == "external:distutils"
+
+
+def test_a_script_sibling_shadows_the_stdlib_module() -> None:
+ """A script's own directory comes first on sys.path, so its sibling wins."""
+ paths = {"tools/deploy.py", "tools/secrets.py"}
+ ctx = ResolverContext(
+ path_set=paths, stem_map={"secrets": ["tools/secrets.py"]}, graph=nx.DiGraph()
+ )
+ assert resolve_python_import("secrets", "tools/deploy.py", ctx) == "tools/secrets.py"
+
+
+def test_non_stdlib_stem_fallback_still_resolves() -> None:
+ path = "pkg/helpers/shared.py"
+ ctx = ResolverContext(
+ path_set={*PATHS, path}, stem_map={"shared": [path]}, graph=nx.DiGraph()
+ )
+ assert resolve_python_import("shared", "app.py", ctx) == path
+
+
def test_relative_miss_stays_none_and_adds_nothing() -> None:
ctx = _ctx()
assert resolve_python_import(".missing", "app.py", ctx) is None
diff --git a/tests/unit/server/test_stats_bot_filter.py b/tests/unit/server/test_stats_bot_filter.py
index ef92e0925..7493ec69f 100644
--- a/tests/unit/server/test_stats_bot_filter.py
+++ b/tests/unit/server/test_stats_bot_filter.py
@@ -13,7 +13,7 @@ from __future__ import annotations
import pytest
-from repowise.server.routers.stats import _is_bot
+from repowise.core.stats_highlights import is_bot as _is_bot
AGENTS = [
# Coding agents, recognised via the ingestion layer's provenance registry.
diff --git a/tests/unit/server/test_stats_contributors.py b/tests/unit/server/test_stats_contributors.py
index 16e1dc7f5..1c918294d 100644
--- a/tests/unit/server/test_stats_contributors.py
+++ b/tests/unit/server/test_stats_contributors.py
@@ -1,4 +1,4 @@
-"""Contributor-count dedup on the /stats/highlights activity payload.
+"""Contributor-count dedup on the stats commit pass.
The "By the Numbers" contributor count keys on commit author identity; GitHub
noreply variants and a person's same-name real+noreply emails must fold to one
@@ -9,13 +9,7 @@ from __future__ import annotations
from datetime import UTC, datetime
-import pytest
-from httpx import AsyncClient
-
-from repowise.core.persistence.crud import get_repository, upsert_git_commits_bulk
-from repowise.core.persistence.database import get_session
-from repowise.server.routers.stats import _commit_pass
-from tests.unit.server.conftest import create_test_repo
+from repowise.core.stats_highlights import build_commit_pass
def _commit(sha: str, name: str, email: str, ts: int) -> dict:
@@ -28,68 +22,41 @@ def _commit(sha: str, name: str, email: str, ts: int) -> dict:
"lines_added": 5,
"lines_deleted": 1,
"files_changed": 1,
- "dirs_changed": 1,
- "subsystems_changed": 1,
- "entropy": 0.1,
- "is_fix": False,
- "change_risk_score": 1.0,
- "change_risk_level": "low",
}
-async def test_contributor_count_folds_noreply_and_same_name(client: AsyncClient, app) -> None:
- repo = await create_test_repo(client)
+def test_contributor_count_folds_noreply_and_same_name() -> None:
rows = [
- # Jane: real email + two noreply variants (numeric id changed) — one person.
+ # Jane: real email + two noreply variants (numeric id changed), one person.
_commit("a1", "Jane Doe", "[email protected]", 1000),
_commit("a2", "Jane Doe", "[email protected]", 1100),
_commit("a3", "Jane Doe", "[email protected]", 1200),
- # Bob: a genuinely separate contributor.
_commit("b1", "Bob", "[email protected]", 1300),
]
- async with get_session(app.state.session_factory) as session:
- await upsert_git_commits_bulk(session, repo["id"], rows)
-
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- activity = (await _commit_pass(session, repo["id"], repo_row))["origin"]
+ origin = build_commit_pass(rows)["origin"]
+ assert origin["total_commits"] == 4
+ assert origin["contributor_count"] == 2
- # No whole-history totals stored on the repo, so the count folds the
- # bounded sample's author identities (Jane + Bob, not 4).
- assert activity["total_commits"] == 4
- assert activity["contributor_count"] == 2
-
-async def test_activity_prefers_whole_history_totals(client: AsyncClient, app) -> None:
- """When the repo carries index-time totals, the headline reads those, not
- the bounded ``git_commits`` sample (issue #730)."""
- repo = await create_test_repo(client)
- # Two sampled commits from one author, ~1 day apart.
+def test_activity_prefers_whole_history_totals() -> None:
+ """Index-time totals win over the bounded commit sample (issue #730)."""
rows = [
_commit("a1", "Jane Doe", "[email protected]", 1_600_000_000),
_commit("a2", "Jane Doe", "[email protected]", 1_600_086_400),
]
- async with get_session(app.state.session_factory) as session:
- await upsert_git_commits_bulk(session, repo["id"], rows)
-
- # Stamp true whole-history values on the repo, far larger than the sample.
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- repo_row.total_commit_count = 5000
- repo_row.total_contributor_count = 42
- repo_row.first_commit_at = datetime.fromtimestamp(1_300_000_000, tz=UTC)
- repo_row.first_commit_author = "Ada Lovelace"
- await session.flush()
-
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- activity = (await _commit_pass(session, repo["id"], repo_row))["origin"]
-
- assert activity["total_commits"] == 5000
- assert activity["contributor_count"] == 42
- assert activity["first_commit_author"] == "Ada Lovelace"
- # Age runs from the true first commit to the latest sampled commit, so it is
- # far larger than the ~1 day the sample alone would show.
- assert activity["age_days"] > 3000
+ totals = {
+ "total_commit_count": 5000,
+ "total_contributor_count": 42,
+ # Naive, the way SQLite hands it back.
+ "first_commit_at": datetime(2011, 3, 13, 7, 6, 40),
+ "first_commit_author": "Ada Lovelace",
+ }
+ out = build_commit_pass(rows, totals)
+ origin = out["origin"]
+ assert origin["total_commits"] == 5000
+ assert origin["contributor_count"] == 42
+ assert origin["first_commit_author"] == "Ada Lovelace"
+ assert origin["age_days"] > 3000
+ # Two commits of 5,000 is a sample, and the payload says so.
+ assert out["rhythm"]["window"]["complete"] is False
+ assert out["rhythm"]["window"]["commits"] == 2
diff --git a/tests/unit/server/test_stats_signals.py b/tests/unit/server/test_stats_signals.py
index 263d22319..c079d4ec0 100644
--- a/tests/unit/server/test_stats_signals.py
+++ b/tests/unit/server/test_stats_signals.py
@@ -1,31 +1,24 @@
"""Unit tests for the Stats page's derived signals.
Covers the punch-card fold, commit velocity, the truck-factor rollup, and the
-single ``_commit_pass`` scan that produces the origin / rhythm / people sections
+single ``build_commit_pass`` scan that produces the origin / rhythm / people sections
from one read of the commits table.
"""
from __future__ import annotations
-from datetime import UTC, datetime
-from types import SimpleNamespace
+from datetime import UTC, datetime, timedelta
-import pytest
-from httpx import AsyncClient
-
-from repowise.core.persistence.crud import get_repository, upsert_git_commits_bulk
-from repowise.core.persistence.database import get_session
-from repowise.server.routers.stats import (
+from repowise.core.stats_highlights import (
_chronotypes,
- _commit_pass,
_commit_velocity,
- _people,
_punch_card_summary,
+ build_commit_pass,
+ build_people,
)
-from tests.unit.server.conftest import create_test_repo
-def _commit(sha: str, dt: datetime, risk: str = "low") -> dict:
+def _commit(sha: str, dt: datetime | str) -> dict:
return {
"sha": sha,
"author_name": "Jane Doe",
@@ -35,12 +28,6 @@ def _commit(sha: str, dt: datetime, risk: str = "low") -> dict:
"lines_added": 5,
"lines_deleted": 1,
"files_changed": 1,
- "dirs_changed": 1,
- "subsystems_changed": 1,
- "entropy": 0.1,
- "is_fix": False,
- "change_risk_score": 1.0,
- "change_risk_level": risk,
}
@@ -106,32 +93,46 @@ def test_chronotypes_default_weekdays_when_missing() -> None:
def test_commit_velocity_rising_and_no_prior() -> None:
anchor = datetime(2026, 6, 1, tzinfo=UTC)
- from datetime import timedelta
-
recent = [anchor - timedelta(days=d) for d in (1, 10, 40, 80)] # 4 in last 90d
prior = [anchor - timedelta(days=d) for d in (100, 150)] # 2 in prior 90d
- out = _commit_velocity(recent + prior, anchor)
+ out = _commit_velocity(recent + prior, anchor, None)
assert out["recent_90d"] == 4
assert out["prior_90d"] == 2
assert out["pct_change"] == 100.0 # 4 vs 2
# No prior window → pct_change is None rather than a divide-by-zero spike.
- young = _commit_velocity(recent, anchor)
+ young = _commit_velocity(recent, anchor, None)
assert young["prior_90d"] == 0
assert young["pct_change"] is None
def test_commit_velocity_empty() -> None:
- assert _commit_velocity([], None) == {"recent_90d": 0, "prior_90d": 0, "pct_change": None}
+ assert _commit_velocity([], None, None) is None
+
+
+def test_commit_velocity_withheld_when_the_sample_is_shorter_than_the_window() -> None:
+ """A sample that starts inside the 90-day window would undercount it."""
+ anchor = datetime(2026, 6, 1, tzinfo=UTC)
+ times = [anchor - timedelta(days=d) for d in (1, 10, 40)]
+ assert _commit_velocity(times, anchor, anchor - timedelta(days=40)) is None
+
+
+def test_commit_velocity_drops_the_comparison_when_the_prior_window_is_cut() -> None:
+ anchor = datetime(2026, 6, 1, tzinfo=UTC)
+ times = [anchor - timedelta(days=d) for d in (1, 10, 100, 120)]
+ out = _commit_velocity(times, anchor, anchor - timedelta(days=120))
+ assert out is not None
+ assert out["recent_90d"] == 2
+ assert out["pct_change"] is None
# ---------------------------------------------------------------------------
-# Truck factor (pure logic over _people)
+# Truck factor (pure logic over build_people)
# ---------------------------------------------------------------------------
-def _meta(owner: str, path: str) -> SimpleNamespace:
- return SimpleNamespace(primary_owner_name=owner, bus_factor=1, file_path=path)
+def _meta(owner: str | None, path: str, bus_factor: int = 1) -> dict:
+ return {"primary_owner_name": owner, "bus_factor": bus_factor, "file_path": path}
def test_truck_factor_single_dominant_owner() -> None:
@@ -140,7 +141,7 @@ def test_truck_factor_single_dominant_owner() -> None:
_meta("Bob", "b.py"),
_meta("Cara", "c.py"),
]
- out = _people(metas)
+ out = build_people(metas)
assert out["truck_factor"] == 1
@@ -152,96 +153,68 @@ def test_truck_factor_spread_ownership() -> None:
+ [_meta("Cara", f"c{i}.py") for i in range(2)]
+ [_meta("Dan", f"d{i}.py") for i in range(2)]
)
- out = _people(metas)
+ out = build_people(metas)
assert out["truck_factor"] == 2
def test_truck_factor_none_without_owners() -> None:
- out = _people([SimpleNamespace(primary_owner_name=None, bus_factor=0, file_path="x.py")])
+ out = build_people([_meta(None, "x.py", bus_factor=0)])
assert out["truck_factor"] is None
# ---------------------------------------------------------------------------
-# End-to-end through _commit_pass on a seeded commits table
+# The commit pass on plain rows
# ---------------------------------------------------------------------------
-async def test_punch_card_buckets_commits(client: AsyncClient, app) -> None:
- repo = await create_test_repo(client)
+def test_punch_card_buckets_commits() -> None:
rows = [
- # Wednesday 2024-01-03 at 14:00 UTC — weekday 2, hour 14.
- _commit("w1", datetime(2024, 1, 3, 14, 0, tzinfo=UTC), risk="high"),
- _commit("w2", datetime(2024, 1, 3, 14, 30, tzinfo=UTC), risk="high"),
- # Saturday 2024-01-06 at 11:00 — weekend.
- _commit("s1", datetime(2024, 1, 6, 11, 0, tzinfo=UTC), risk="moderate"),
- # Sunday 2024-01-07 at 12:00 — weekend.
- _commit("s2", datetime(2024, 1, 7, 12, 0, tzinfo=UTC), risk="low"),
+ # Wednesday 2024-01-03 at 14:00 UTC: weekday 2, hour 14.
+ _commit("w1", datetime(2024, 1, 3, 14, 0, tzinfo=UTC)),
+ _commit("w2", datetime(2024, 1, 3, 14, 30, tzinfo=UTC)),
+ _commit("s1", datetime(2024, 1, 6, 11, 0, tzinfo=UTC)),
+ _commit("s2", datetime(2024, 1, 7, 12, 0, tzinfo=UTC)),
]
- async with get_session(app.state.session_factory) as session:
- await upsert_git_commits_bulk(session, repo["id"], rows)
-
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- out = await _commit_pass(session, repo["id"], repo_row)
-
- pc = out["rhythm"]["punch_card"]
- assert pc["matrix"][2][14] == 2 # both Wednesday-2pm commits landed in one cell
+ pc = build_commit_pass(rows)["rhythm"]["punch_card"]
+ assert pc["matrix"][2][14] == 2
assert pc["peak"] == {"weekday": 2, "hour": 14, "count": 2}
- # Weekend rows carry their commits; which days count as the weekend is a
- # reader preference resolved in the UI, not here.
assert pc["matrix"][5][11] + pc["matrix"][6][12] == 2
- # No commit carries an offset, so the card stays honestly in UTC rather
- # than mixing clocks.
+ # No commit carries an offset, so the card stays in UTC.
assert pc["timezone_mode"] == "utc"
-async def test_commit_pass_degrades_on_empty_repo(client: AsyncClient, app) -> None:
- """Every section is fully shaped on a repo with no commits at all, so the
- page renders an empty state rather than throwing on a missing key."""
- repo = await create_test_repo(client)
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- out = await _commit_pass(session, repo["id"], repo_row)
-
+def test_commit_pass_degrades_on_empty_repo() -> None:
+ out = build_commit_pass([])
assert out["rhythm"]["punch_card"]["total"] == 0
assert out["rhythm"]["punch_card"]["peak"] is None
assert out["rhythm"]["longest_streak"] is None
+ assert out["rhythm"]["longest_silence"] is None
assert out["rhythm"]["busiest_day"] is None
- assert out["rhythm"]["velocity"] == {"recent_90d": 0, "prior_90d": 0, "pct_change": None}
+ assert out["rhythm"]["velocity"] is None
assert out["chronotypes"] == []
assert out["arrivals"] == []
assert out["origin"]["age_days"] is None
-async def test_punch_card_uses_author_local_time_when_offsets_present(
- client: AsyncClient, app
-) -> None:
- """With every commit carrying its UTC offset, hours are shifted into the
- author's own clock — the whole point of storing the offset. A commit at
- 18:30 UTC with a +05:30 offset is midnight local, i.e. the next weekday."""
- repo = await create_test_repo(client)
+def test_punch_card_uses_author_local_time_when_offsets_present() -> None:
+ """18:30 UTC at +05:30 is midnight local, on the next weekday."""
rows = [
- {
- **_commit("a1", datetime(2024, 1, 3, 18, 30, tzinfo=UTC)),
- "committed_offset_minutes": 330,
- },
- {
- **_commit("a2", datetime(2024, 1, 3, 18, 45, tzinfo=UTC)),
- "committed_offset_minutes": 330,
- },
+ {**_commit("a1", datetime(2024, 1, 3, 18, 30)), "committed_offset_minutes": 330},
+ {**_commit("a2", datetime(2024, 1, 3, 18, 45)), "committed_offset_minutes": 330},
]
- async with get_session(app.state.session_factory) as session:
- await upsert_git_commits_bulk(session, repo["id"], rows)
-
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- out = await _commit_pass(session, repo["id"], repo_row)
-
- pc = out["rhythm"]["punch_card"]
+ pc = build_commit_pass(rows)["rhythm"]["punch_card"]
assert pc["timezone_mode"] == "author_local"
- # Wednesday 18:30 UTC + 5:30 = Thursday 00:00 local → weekday 3, hour 0.
assert pc["matrix"][3][0] == 2
assert pc["matrix"][2][18] == 0
+
+
+def test_longest_silence_and_iso_string_timestamps() -> None:
+ """Artifact rows carry ISO strings; the gap is measured between commits."""
+ rows = [
+ _commit("a", "2024-01-01T10:00:00Z"),
+ _commit("b", "2024-01-01T12:00:00+00:00"),
+ _commit("c", "2024-01-04T12:00:00+00:00"),
+ ]
+ silence = build_commit_pass(rows)["rhythm"]["longest_silence"]
+ assert silence["hours"] == 72
+ assert silence["start"].startswith("2024-01-01T12:00")
diff --git a/tests/unit/server/test_stats_superlatives.py b/tests/unit/server/test_stats_superlatives.py
index 351a5ec96..a1be968ad 100644
--- a/tests/unit/server/test_stats_superlatives.py
+++ b/tests/unit/server/test_stats_superlatives.py
@@ -1,9 +1,8 @@
-"""Ride-along awards on the /stats/highlights activity scan.
+"""The Stats page's records and scale, from plain rows and through the route.
-``biggest_commit`` must skip the repo's very first commit (every initial
-import would win otherwise) and ``longest_streak`` counts consecutive UTC
-days with at least one commit. ``most_central_file`` names the most-imported
-file that is not a test.
+``biggest_commit`` skips the repo's very first commit (every initial import
+would win otherwise), ``most_central_file`` names the most-imported file that
+is not a test, and the function records leave test code out.
"""
from __future__ import annotations
@@ -13,10 +12,19 @@ from datetime import UTC, datetime
import pytest
from httpx import AsyncClient
-from repowise.core.persistence.crud import get_repository, upsert_git_commits_bulk
+from repowise.core.persistence.crud import upsert_git_commits_bulk
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphMetric, GraphNode
-from repowise.server.routers.stats import _commit_pass, _records
+from repowise.core.stats_highlights import (
+ build_commit_pass,
+ build_file_records,
+ build_function_records,
+ build_scale,
+ is_test_checker,
+ most_imported_file,
+ most_patched_function,
+)
+from repowise.server.routers.stats import stats_highlights
from tests.unit.server.conftest import create_test_repo
_DAY = 86400
@@ -41,81 +49,159 @@ def _commit(sha: str, ts: int, added: int, deleted: int = 0, files: int = 1) ->
}
-async def test_biggest_commit_skips_initial_and_streak_counts_days(
- client: AsyncClient, app
-) -> None:
- repo = await create_test_repo(client)
+def test_commit_awards_skip_the_root_commit_and_streak_counts_days() -> None:
rows = [
- # Initial commit is the largest by churn but must not win the award.
- _commit("a1", 1000, added=50_000, files=300),
- # Days 2-4 form a 3-day streak; day 2's commit is the rightful winner.
+ # The root commit is the largest by churn and by deletion, and wins neither.
+ _commit("a1", 1000, added=50_000, deleted=60_000, files=300),
_commit("b1", 1000 + _DAY, added=900, deleted=100, files=12),
- _commit("c1", 1000 + 2 * _DAY, added=10),
+ _commit("c1", 1000 + 2 * _DAY, added=10, deleted=400),
_commit("d1", 1000 + 3 * _DAY, added=10),
- # A gap, then a lone day — streak stays 4 (day 1 chains into days 2-4).
_commit("e1", 1000 + 10 * _DAY, added=10),
]
- async with get_session(app.state.session_factory) as session:
- await upsert_git_commits_bulk(session, repo["id"], rows)
+ out = build_commit_pass(rows)
+ assert out["biggest_commit"]["sha"] == "b1"
+ assert out["biggest_commit"]["lines_changed"] == 1000
+ assert out["biggest_purge"] == {
+ "sha": "c1",
+ "subject": "commit c1",
+ "lines_deleted": 400,
+ "lines_added": 10,
+ }
+ assert out["rhythm"]["longest_streak"]["days"] == 4
+ assert out["rhythm"]["longest_silence"]["hours"] == 7 * 24
- async with get_session(app.state.session_factory) as session:
- repo_row = await get_repository(session, repo["id"])
- activity = await _commit_pass(session, repo["id"], repo_row)
- biggest = activity["biggest_commit"]
- assert biggest is not None
- assert biggest["sha"] == "b1"
- assert biggest["lines_changed"] == 1000
- assert biggest["files_changed"] == 12
+def test_a_partial_sample_keeps_its_oldest_commit_eligible() -> None:
+ """Only the repo's root commit is barred; the oldest commit of a newer
+ sample is ordinary and may win."""
+ rows = [
+ _commit("old", 1000 + 50 * _DAY, added=9_000, files=40),
+ _commit("new", 1000 + 51 * _DAY, added=10, files=1),
+ ]
+ totals = {"first_commit_at": datetime.fromtimestamp(1000, tz=UTC), "total_commit_count": 90}
+ out = build_commit_pass(rows, totals)
+ assert out["rhythm"]["window"]["complete"] is False
+ assert out["biggest_commit"]["sha"] == "old"
+
- streak = activity["rhythm"]["longest_streak"]
- assert streak is not None
- assert streak["days"] == 4
+def test_merge_commits_do_not_make_a_full_sample_look_partial() -> None:
+ """The sample skips merges and the total counts them; the root decides."""
+ rows = [_commit("root", 1000, added=5), _commit("b", 1000 + _DAY, added=5)]
+ totals = {"first_commit_at": datetime.fromtimestamp(1000, tz=UTC), "total_commit_count": 3}
+ assert build_commit_pass(rows, totals)["rhythm"]["window"]["complete"] is True
-async def test_most_central_file_skips_tests_without_false_positives(
- client: AsyncClient, app
-) -> None:
- """The award goes to the top real source file (#1103).
-
- Two ways to get this wrong, one on each side. The unanchored regex this
- used to re-check with read ``src/latest/api.py`` as a test and handed the
- award to the runner-up. Trusting ``is_test`` alone would hand it to
- ``tests/conftest.py``, which tops fan-in in any repo sharing fixtures
- widely and whose stored flag is only as fresh as its last traversal.
- """
- repo = await create_test_repo(client)
+def test_most_imported_file_rechecks_stale_test_flags() -> None:
+ """Stale ``is_test`` lets conftest through the SQL filter; the path rules
+ catch it, without reading ``src/latest/api.py`` as a test (#1103)."""
+ candidates = [
+ {"path": "tests/conftest.py", "in_degree": 700, "pagerank": 0.1},
+ {"path": "src/latest/api.py", "in_degree": 90, "pagerank": 0.1},
+ ]
+ assert most_imported_file(candidates) == {
+ "path": "src/latest/api.py",
+ "pagerank": 0.1,
+ "import_count": 90,
+ }
+
+
+def test_scale_counts_code_languages_and_skips_external_nodes() -> None:
nodes = [
- # Stale flag: stamped before conftest counted as test material.
- ("tests/conftest.py", False, 700),
- ("src/latest/api.py", False, 90), # not a test, whatever the name reads like
- ("src/util.py", False, 40),
+ {"node_id": "a.py", "language": "python", "symbol_count": 3},
+ {"node_id": "b.ts", "language": "typescript", "symbol_count": 2},
+ {"node_id": "c.json", "language": "json", "symbol_count": 0},
+ {"node_id": "external:requests", "language": "external", "symbol_count": 0},
]
+ metrics = [
+ {"nloc": 100, "module": "a", "is_test": False},
+ {"nloc": 40, "module": "tests", "is_test": True},
+ ]
+ scale = build_scale(nodes, metrics)
+ assert scale["file_count"] == 3
+ assert scale["symbol_count"] == 5
+ assert scale["language_count"] == 2
+ assert {lang["language"] for lang in scale["languages"]} == {"python", "typescript"}
+ assert scale["total_nloc"] == 140
+ assert scale["test_nloc"] == 40
+
+
+def test_day_one_files_replace_an_arbitrary_oldest_file() -> None:
+ root = datetime(2024, 1, 1, 9, 0)
+ meta = [
+ {"file_path": "a.py", "first_commit_at": root, "commit_count_total": 3},
+ {"file_path": "b.py", "first_commit_at": root, "commit_count_total": 9},
+ {"file_path": "c.py", "first_commit_at": datetime(2024, 2, 1), "commit_count_total": 1},
+ ]
+ # A capped history can lose its root commit, so it counts on neither side.
+ meta.append(
+ {"file_path": "d.py", "first_commit_at": datetime(2024, 3, 1), "commit_count_total": 5,
+ "commit_count_capped": True}
+ )
+ out = build_file_records([], meta, "2024-01-01T09:00:00+00:00")
+ assert out["day_one_files"] == {"count": 2, "of": 3}
+ assert out["most_changed_file"] == {"path": "b.py", "commit_count": 9}
+ assert "oldest_file" not in out
+
+
+def test_function_records_leave_test_code_out() -> None:
+ def fn(name: str, path: str, end: int, kind: str = "function") -> dict:
+ return {"name": name, "kind": kind, "file_path": path, "start_line": 1, "end_line": end}
+
+ fns = [
+ fn("run", "src/app.py", 300),
+ fn("run", "src/other.py", 5, kind="method"),
+ fn("a_rather_descriptive_name", "src/app.py", 2),
+ fn("test_a_name_long_enough_to_win_everything_if_tests_counted", "tests/test_app.py", 900),
+ fn("Widget", "src/app.py", 2000, kind="class"),
+ ]
+ # The stored flag is NULL here, as on an index written before the column:
+ # the path rules have to catch the test file anyway.
+ is_test = is_test_checker([{"file_path": "tests/test_app.py", "is_test": None}])
+ out = build_function_records(fns, is_test)
+ assert out["longest_function"] == {"name": "run", "file_path": "src/app.py", "lines": 300}
+ assert out["longest_name"]["name"] == "a_rather_descriptive_name"
+ assert out["most_common_name"] == {"name": "run", "count": 2}
+
+ blame = [
+ {"function_name": "test_x", "file_path": "tests/test_app.py", "mod_count": 40},
+ {"function_name": "", "file_path": "src/app.py", "mod_count": 30},
+ {"function_name": "run", "file_path": "src/app.py", "mod_count": 12},
+ ]
+ assert most_patched_function(blame, is_test) == {
+ "name": "run",
+ "file_path": "src/app.py",
+ "mod_count": 12,
+ }
+
+
+async def test_route_serves_records_from_the_database(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
async with get_session(app.state.session_factory) as session:
- for path, is_test, in_degree in nodes:
+ for path, in_degree in (("tests/conftest.py", 700), ("src/latest/api.py", 90)):
session.add(
GraphNode(
repository_id=repo["id"],
node_id=path,
node_type="file",
- is_test=is_test,
+ language="python",
+ is_test=False,
pagerank=0.1,
)
)
session.add(
GraphMetric(
- repository_id=repo["id"],
- node_id=path,
- in_degree=in_degree,
- pagerank=0.1,
+ repository_id=repo["id"], node_id=path, in_degree=in_degree, pagerank=0.1
)
)
await session.commit()
+ await upsert_git_commits_bulk(
+ session, repo["id"], [_commit("a1", 1000, 5), _commit("b1", 1000 + _DAY, 7, files=3)]
+ )
async with get_session(app.state.session_factory) as session:
- out = await _records(session, repo["id"], metrics=[], all_meta=[])
-
- assert out["most_central_file"]["path"] == "src/latest/api.py"
- assert out["most_central_file"]["import_count"] == 90
+ body = await stats_highlights(repo["id"], session)
+ assert body["records"]["most_central_file"]["path"] == "src/latest/api.py"
+ assert body["records"]["biggest_commit"]["sha"] == "b1"
+ assert body["scale"]["file_count"] == 2
+ assert body["rhythm"]["window"]["commits"] == 2