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.

Scope the Stats page to what no other page shows (#1091)

Raghav Chamadiya65aa1c43f5ee
diff --git a/packages/api-client/src/__fixtures__/hosted/stats-highlights.json b/packages/api-client/src/__fixtures__/hosted/stats-highlights.json
index 3dbe15593..b86c54958 100644
--- a/packages/api-client/src/__fixtures__/hosted/stats-highlights.json
+++ b/packages/api-client/src/__fixtures__/hosted/stats-highlights.json
@@ -1,1157 +1,379 @@
{
"repo": {
- "id": "d8ea204a-6325-438c-a805-fbdb029ffd11",
- "name": "flask",
- "default_branch": "main",
- "head_commit": "36e4a824f340fdee7ed50937ba8e7f6bc7d17f81"
+ "id": "repo-1",
+ "name": "demo"
},
"scale": {
- "file_count": 108,
- "symbol_count": 1060,
- "entry_point_count": 5,
- "module_count": 24,
- "total_nloc": 14043,
- "language_count": 8,
+ "file_count": 3146,
+ "symbol_count": 24430,
+ "module_count": 11,
+ "total_nloc": 419590,
+ "language_count": 12,
"languages": [
{
"language": "python",
- "file_count": 83
+ "file_count": 1803
},
{
- "language": "yaml",
- "file_count": 8
+ "language": "typescript",
+ "file_count": 1001
},
{
"language": "markdown",
- "file_count": 6
- },
- {
- "language": "toml",
- "file_count": 5
+ "file_count": 144
},
{
"language": "json",
- "file_count": 2
- },
- {
- "language": "sql",
- "file_count": 2
- },
- {
- "language": "shell",
- "file_count": 1
- },
- {
- "language": "makefile",
- "file_count": 1
+ "file_count": 85
}
],
"size_class": {
- "name": "Village",
- "blurb": "A tidy village — a few neighborhoods, easy to walk.",
- "nloc": 14043
+ "name": "Metropolis",
+ "blurb": "A sprawling metropolis with serious infrastructure.",
+ "nloc": 419590
}
},
- "activity": {
- "total_commits": 2000,
- "agent_commits": 0,
- "agent_pct": 0,
- "fix_commits": 204,
- "fix_pct": 10.2,
- "contributor_count": 568,
- "first_commit_at": "2015-06-06T04:25:41+00:00",
- "first_commit_author": "Armin Ronacher",
- "last_commit_at": "2026-05-31T14:42:46+00:00",
- "age_days": 4012,
- "busiest_month": {
- "month": "2017-05",
- "total": 100,
- "agent": 0
- },
- "monthly": [
- {
- "month": "2015-06",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2015-07",
- "total": 12,
- "agent": 0
- },
- {
- "month": "2015-08",
- "total": 3,
- "agent": 0
- },
- {
- "month": "2015-09",
- "total": 2,
- "agent": 0
- },
- {
- "month": "2015-10",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2015-11",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2015-12",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2016-01",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2016-02",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2016-03",
- "total": 7,
- "agent": 0
- },
- {
- "month": "2016-04",
- "total": 18,
- "agent": 0
- },
- {
- "month": "2016-05",
- "total": 33,
- "agent": 0
- },
- {
- "month": "2016-06",
- "total": 71,
- "agent": 0
- },
- {
- "month": "2016-07",
- "total": 9,
- "agent": 0
- },
- {
- "month": "2016-08",
- "total": 33,
- "agent": 0
- },
- {
- "month": "2016-09",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2016-10",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2016-11",
- "total": 13,
- "agent": 0
- },
- {
- "month": "2016-12",
- "total": 21,
- "agent": 0
- },
- {
- "month": "2017-01",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2017-02",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2017-03",
- "total": 27,
- "agent": 0
- },
- {
- "month": "2017-04",
- "total": 29,
- "agent": 0
- },
- {
- "month": "2017-05",
- "total": 100,
- "agent": 0
- },
- {
- "month": "2017-06",
- "total": 54,
- "agent": 0
- },
- {
- "month": "2017-07",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2017-08",
- "total": 9,
- "agent": 0
- },
- {
- "month": "2017-09",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2017-10",
- "total": 9,
- "agent": 0
- },
- {
- "month": "2017-11",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2017-12",
- "total": 16,
- "agent": 0
- },
- {
- "month": "2018-01",
- "total": 25,
- "agent": 0
- },
- {
- "month": "2018-02",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2018-03",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2018-04",
- "total": 77,
- "agent": 0
- },
- {
- "month": "2018-05",
- "total": 27,
- "agent": 0
- },
- {
- "month": "2018-06",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2018-07",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2018-08",
- "total": 1,
- "agent": 0
- },
- {
- "month": "2018-09",
- "total": 12,
- "agent": 0
- },
- {
- "month": "2018-10",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2018-11",
- "total": 7,
- "agent": 0
- },
- {
- "month": "2018-12",
- "total": 2,
- "agent": 0
- },
- {
- "month": "2019-01",
- "total": 36,
- "agent": 0
- },
- {
- "month": "2019-02",
- "total": 2,
- "agent": 0
- },
- {
- "month": "2019-03",
- "total": 1,
- "agent": 0
- },
- {
- "month": "2019-04",
- "total": 2,
- "agent": 0
- },
- {
- "month": "2019-05",
- "total": 73,
- "agent": 0
- },
- {
- "month": "2019-06",
- "total": 26,
- "agent": 0
- },
- {
- "month": "2019-07",
- "total": 19,
- "agent": 0
- },
- {
- "month": "2019-08",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2019-09",
- "total": 5,
- "agent": 0
- },
- {
- "month": "2019-10",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2019-11",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2020-02",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2020-03",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2020-04",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2020-05",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2020-06",
- "total": 19,
- "agent": 0
- },
- {
- "month": "2020-07",
- "total": 33,
- "agent": 0
- },
- {
- "month": "2020-08",
- "total": 12,
- "agent": 0
- },
- {
- "month": "2020-09",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2020-10",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2020-11",
- "total": 21,
- "agent": 0
- },
- {
- "month": "2020-12",
- "total": 2,
- "agent": 0
- },
- {
- "month": "2021-01",
- "total": 16,
- "agent": 0
- },
- {
- "month": "2021-02",
- "total": 26,
- "agent": 0
- },
- {
- "month": "2021-03",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2021-04",
- "total": 34,
- "agent": 0
- },
- {
- "month": "2021-05",
- "total": 67,
- "agent": 0
- },
- {
- "month": "2021-06",
- "total": 15,
- "agent": 0
- },
- {
- "month": "2021-07",
- "total": 12,
- "agent": 0
- },
- {
- "month": "2021-08",
- "total": 21,
- "agent": 0
- },
- {
- "month": "2021-09",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2021-10",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2021-11",
- "total": 24,
- "agent": 0
- },
- {
- "month": "2021-12",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2022-01",
- "total": 7,
- "agent": 0
- },
- {
- "month": "2022-02",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2022-03",
- "total": 23,
- "agent": 0
- },
- {
- "month": "2022-04",
- "total": 16,
- "agent": 0
- },
- {
- "month": "2022-05",
- "total": 24,
- "agent": 0
- },
- {
- "month": "2022-06",
- "total": 32,
- "agent": 0
- },
- {
- "month": "2022-07",
- "total": 33,
- "agent": 0
- },
- {
- "month": "2022-08",
- "total": 32,
- "agent": 0
- },
- {
- "month": "2022-09",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2022-10",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2022-11",
- "total": 5,
- "agent": 0
- },
- {
- "month": "2022-12",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2023-01",
- "total": 13,
- "agent": 0
- },
- {
- "month": "2023-02",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2023-03",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2023-04",
- "total": 34,
- "agent": 0
- },
- {
- "month": "2023-05",
- "total": 24,
- "agent": 0
- },
- {
- "month": "2023-06",
- "total": 21,
- "agent": 0
- },
- {
- "month": "2023-07",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2023-08",
- "total": 24,
- "agent": 0
- },
- {
- "month": "2023-09",
- "total": 7,
- "agent": 0
- },
- {
- "month": "2023-10",
- "total": 5,
- "agent": 0
- },
- {
- "month": "2023-11",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2023-12",
- "total": 6,
- "agent": 0
- },
- {
- "month": "2024-01",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2024-02",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2024-04",
- "total": 14,
- "agent": 0
- },
- {
- "month": "2024-05",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2024-06",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2024-07",
- "total": 5,
- "agent": 0
- },
- {
- "month": "2024-08",
- "total": 10,
- "agent": 0
- },
- {
- "month": "2024-09",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2024-10",
- "total": 13,
- "agent": 0
- },
- {
- "month": "2024-11",
- "total": 22,
- "agent": 0
- },
- {
- "month": "2025-01",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2025-03",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2025-05",
- "total": 8,
- "agent": 0
- },
- {
- "month": "2025-06",
- "total": 7,
- "agent": 0
- },
- {
- "month": "2025-08",
- "total": 13,
- "agent": 0
- },
- {
- "month": "2025-09",
- "total": 3,
- "agent": 0
- },
- {
- "month": "2025-10",
- "total": 1,
- "agent": 0
- },
- {
- "month": "2025-11",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2026-01",
- "total": 12,
- "agent": 0
- },
- {
- "month": "2026-02",
- "total": 11,
- "agent": 0
- },
- {
- "month": "2026-03",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2026-04",
- "total": 4,
- "agent": 0
- },
- {
- "month": "2026-05",
- "total": 6,
- "agent": 0
- }
- ],
- "agent_names": [],
+ "origin": {
+ "first_commit_at": "2026-03-23T16:14:58+00:00",
+ "first_commit_author": "RaghavChamadiya",
+ "first_commit_subject": "Initial commit: CodeWiki project",
+ "last_commit_at": "2026-07-25T18:00:21+00:00",
+ "age_days": 124,
+ "total_commits": 854,
+ "contributor_count": 51
+ },
+ "churn": {
+ "lines_added": 740846,
+ "lines_deleted": 160171,
+ "net": 580675,
+ "deleted_per_hundred": 21.6
+ },
+ "rhythm": {
"punch_card": {
"matrix": [
[
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 6,
+ 2,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 9,
+ 5,
6,
+ 5,
+ 8,
12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 6,
- 6,
- 6,
- 1,
- 1
+ 10,
+ 4,
+ 4,
+ 11,
+ 5,
+ 0,
+ 3,
+ 4
],
[
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 6,
- 6,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 6,
+ 3,
+ 8,
+ 13,
+ 16,
+ 4,
+ 5,
+ 5,
6,
+ 5,
+ 3,
6,
- 1,
- 1
+ 2
],
[
1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
1,
1,
- 1,
- 1,
- 1,
- 1,
- 6,
- 6,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 6,
- 6,
- 6,
- 1,
- 1
+ 4,
+ 8,
+ 7,
+ 17,
+ 12,
+ 13,
+ 11,
+ 11,
+ 7,
+ 2,
+ 16,
+ 8,
+ 4,
+ 4
],
[
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 6,
- 6,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 9,
+ 4,
+ 0,
+ 9,
+ 16,
+ 19,
+ 15,
+ 4,
+ 9,
12,
6,
- 6,
- 6,
1,
- 1
+ 7
],
[
1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
+ 2,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
6,
+ 16,
+ 10,
+ 11,
+ 25,
+ 13,
+ 13,
+ 13,
+ 7,
6,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 12,
- 6,
- 6,
- 6,
- 1,
- 1
+ 8,
+ 10,
+ 4,
+ 7
],
[
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 4,
4,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 2,
+ 3,
+ 1,
+ 9,
+ 15,
+ 7,
+ 10,
+ 18,
+ 18,
+ 16,
+ 18,
+ 15,
+ 17,
+ 7,
4,
4,
- 4,
- 4,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1
+ 4
],
[
1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 4,
- 4,
- 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 9,
+ 9,
+ 8,
+ 5,
+ 21,
+ 22,
+ 10,
+ 13,
+ 2,
4,
- 4,
- 4,
- 1,
+ 0,
1,
- 1,
- 1,
- 1,
- 1,
- 1
+ 2
]
],
"peak": {
- "weekday": 2,
+ "weekday": 4,
"hour": 14,
- "count": 12
+ "count": 25
},
- "busiest_weekday": 2,
- "peak_hour": 14,
- "total": 879
+ "busiest_weekday": 5,
+ "peak_hour": 15,
+ "total": 853,
+ "timezone_mode": "author_local"
},
"velocity": {
- "recent_90d": 412,
- "prior_90d": 318,
- "pct_change": 29.6
+ "recent_90d": 742,
+ "prior_90d": 111,
+ "pct_change": 568.5
},
- "change_risk_mix": {
- "low": 1240,
- "moderate": 560,
- "high": 200
- }
+ "busiest_month": {
+ "month": "2026-07",
+ "total": 351
+ },
+ "busiest_day": {
+ "date": "2026-07-24",
+ "commits": 37
+ },
+ "longest_streak": {
+ "days": 25,
+ "start": "2026-05-23",
+ "end": "2026-06-16"
+ },
+ "active_days": 95,
+ "code_half_life_days": 28
},
"people": {
- "owner_count": 12,
- "top_owners": [
- {
- "name": "David Lord",
- "file_count": 58,
- "pct": 0.6904761904761905
- },
- {
- "name": "Markus Unterwaditzer",
- "file_count": 5,
- "pct": 0.05952380952380952
- },
- {
- "name": "pgjones",
- "file_count": 4,
- "pct": 0.047619047619047616
- },
+ "owner_count": 28,
+ "single_owner_files": 2820,
+ "silo_count": 9,
+ "truck_factor": 1,
+ "contributor_count": 51,
+ "chronotypes": [
+ {
+ "name": "Raghav Chamadiya",
+ "commits": 626,
+ "peak_hour": 15,
+ "label": "daylight",
+ "night_pct": 9.6,
+ "early_pct": 0.8
+ },
+ {
+ "name": "Swati Ahuja",
+ "commits": 90,
+ "peak_hour": 15,
+ "label": "daylight",
+ "night_pct": 10.0,
+ "early_pct": 0.0
+ },
+ {
+ "name": "joptimus",
+ "commits": 25,
+ "peak_hour": 13,
+ "label": "daylight",
+ "night_pct": 0.0,
+ "early_pct": 0.0
+ }
+ ],
+ "arrivals": [
{
- "name": "David Baumgold",
- "file_count": 4,
- "pct": 0.047619047619047616
+ "name": "Raghav Chamadiya",
+ "first_commit_at": "2026-03-23T09:14:58+00:00"
},
{
- "name": "Armin Ronacher",
- "file_count": 4,
- "pct": 0.047619047619047616
+ "name": "Swati Ahuja",
+ "first_commit_at": "2026-03-29T07:34:55+00:00"
},
{
- "name": "Jannis Leidel",
- "file_count": 3,
- "pct": 0.03571428571428571
+ "name": "Adam Franke",
+ "first_commit_at": "2026-04-03T07:20:45+00:00"
},
{
- "name": "emisargent",
- "file_count": 1,
- "pct": 0.011904761904761904
+ "name": "Lakshay Sachdeva",
+ "first_commit_at": "2026-04-03T12:53:35+00:00"
},
{
- "name": "Hendrik Makait",
- "file_count": 1,
- "pct": 0.011904761904761904
+ "name": "Gabriel Mitelman Tkacz",
+ "first_commit_at": "2026-04-04T09:56:16+00:00"
}
- ],
- "single_owner_files": 28,
- "silo_count": 4,
- "truck_factor": 3
+ ]
},
- "quality": {
- "average_health": 6.94,
- "maintainability_average": 7.71,
- "performance_average": 9.96,
- "worst_performer_path": "src/flask/app.py",
- "worst_performer_score": 1.07,
- "open_findings": 209,
- "severity_breakdown": {
- "critical": 8,
- "high": 32,
- "medium": 84,
- "low": 85
- },
- "defect_accuracy": {
- "k": 20,
- "hits": 5,
- "precision": 0.25,
- "base_rate": 0.0556,
- "lift": 4.5,
- "window_days": 180,
- "scored_files": 108,
- "defect_files": 6,
- "concentration_file_fraction": 0.2,
- "concentration_defect_share": 0.8333,
- "precision_table": [
- {
- "k": 10,
- "hits": 3
- },
- {
- "k": 20,
- "hits": 5
- },
- {
- "k": 30,
- "hits": 5
- }
- ],
- "flagged_files": [
- {
- "file_path": "src/flask/app.py",
- "score": 1.07,
- "recent_fixes": 1
- },
- {
- "file_path": "src/flask/sansio/app.py",
- "score": 1.35,
- "recent_fixes": 1
- },
- {
- "file_path": "src/flask/cli.py",
- "score": 2.05,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/sansio/blueprints.py",
- "score": 3.53,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/config.py",
- "score": 5.15,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/testing.py",
- "score": 5.5,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/ctx.py",
- "score": 6.51,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/templating.py",
- "score": 7.15,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/sansio/scaffold.py",
- "score": 7.16,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_basic.py",
- "score": 7.49,
- "recent_fixes": 1
- },
- {
- "file_path": "src/flask/debughelpers.py",
- "score": 7.53,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/helpers.py",
- "score": 8.09,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_blueprints.py",
- "score": 8.14,
- "recent_fixes": 1
- },
- {
- "file_path": "tests/test_cli.py",
- "score": 8.19,
- "recent_fixes": 1
- },
- {
- "file_path": "src/flask/wrappers.py",
- "score": 8.59,
- "recent_fixes": 0
- },
- {
- "file_path": "src/flask/blueprints.py",
- "score": 8.64,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_templating.py",
- "score": 8.74,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_appctx.py",
- "score": 8.94,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_reqctx.py",
- "score": 8.94,
- "recent_fixes": 0
- },
- {
- "file_path": "tests/test_testing.py",
- "score": 8.94,
- "recent_fixes": 0
- }
- ]
- },
- "distribution": {
- "total_files": 108,
- "total_nloc": 14046,
- "bands": {
- "healthy": {
- "files": 97,
- "nloc": 7562,
- "pct": 53.8
- },
- "warning": {
- "files": 7,
- "nloc": 3192,
- "pct": 22.7
- },
- "alert": {
- "files": 4,
- "nloc": 3292,
- "pct": 23.4
- }
- }
- },
- "doc_coverage_pct": 0,
- "page_count": 0,
- "test_coverage_pct": 62,
- "dead_code": {
- "total_findings": 28,
- "deletable_lines": 169
- }
- },
- "knowledge": {
- "decision_count": 32,
- "active_decision_count": 0
- },
- "superlatives": {
+ "records": {
"largest_file": {
- "path": "tests/test_basic.py",
- "nloc": 1440
+ "path": "packages/api-client/src/__fixtures__/hosted/health-overview.json",
+ "nloc": 1707
+ },
+ "gnarliest_file": {
+ "path": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py",
+ "max_ccn": 166
},
"most_complex_symbol": {
- "name": "register",
- "file_path": "src/flask/sansio/blueprints.py",
- "complexity": 22
+ "name": "get_answer",
+ "file_path": "packages/server/src/repowise/server/mcp_server/tool_answer/answer.py",
+ "complexity": 166
},
"most_changed_file": {
- "path": "src/flask/app.py",
- "commit_count": 134
+ "path": "uv.lock",
+ "commit_count": 65
},
"oldest_file": {
- "path": "tests/test_apps/blueprintapp/apps/__init__.py",
- "first_commit_at": "2014-09-11T20:09:50+00:00"
+ "path": "package-lock.json",
+ "first_commit_at": "2026-03-23T09:14:58+00:00"
+ },
+ "most_central_file": {
+ "path": "packages/core/src/repowise/core/persistence/models.py",
+ "pagerank": 0.0098,
+ "import_count": 188
},
"strongest_coupling": {
- "a": "CHANGES.rst",
- "b": "src/flask/sansio/app.py",
- "count": 3
+ "a": "packages/cli/src/repowise/cli/__init__.py",
+ "b": "pyproject.toml",
+ "count": 42.51
+ },
+ "largest_cycle": {
+ "files": 151,
+ "cycle_count": 18
+ },
+ "symbol_shape": {
+ "total": 24412,
+ "async_count": 2882,
+ "async_pct": 11.8,
+ "documented_count": 6461,
+ "documented_pct": 26.5
+ },
+ "biggest_commit": {
+ "sha": "a901cc985cbd47634a45dc50ddab2d80f2c36cc4",
+ "subject": "feat: v0.3.0 \u2014 workspaces, auto-sync hooks, graph intelligence (#76)",
+ "lines_changed": 27519,
+ "files_changed": 187
+ },
+ "widest_commit": {
+ "sha": "aadd8f5e022208cc0901bd34d03bd6287aee43a6",
+ "subject": "release: v0.5.0 \u2014 frontend monorepo restructure, build hardening, jobs reliability (#132)",
+ "files_changed": 278,
+ "lines_changed": 20715
}
- },
- "graph": {
- "cycle_clusters": 7,
- "files_in_cycles": 63,
- "largest_cycle": 21,
- "community_count": 48
- },
- "build": {
- "page_count": 486,
- "total_tokens": 5231044,
- "cost_usd": 0.92,
- "llm_operations": 640
}
}
diff --git a/packages/api-client/src/hosted.fixtures.test.ts b/packages/api-client/src/hosted.fixtures.test.ts
index 4a5feb1c0..e11885bfd 100644
--- a/packages/api-client/src/hosted.fixtures.test.ts
+++ b/packages/api-client/src/hosted.fixtures.test.ts
@@ -123,9 +123,22 @@ describe("hosted fixtures satisfy the OSS contracts", () => {
expect(summary.health).toBeDefined();
expect(summary.sync).toBeDefined();
+ // Assert every top-level section, not just two. `getStatsHighlights` is a
+ // bare passthrough with no field mapping, so this fixture is the only thing
+ // standing between a hosted payload drifting from the contract and the
+ // Stats page rendering `undefined` sections at runtime.
const stats: StatsHighlights = await p.getStatsHighlights("repo-1");
- expect(stats.scale).toBeDefined();
- expect(stats.people).toBeDefined();
+ expect(stats.scale.size_class.name).toBeTruthy();
+ expect(stats.origin).toBeDefined();
+ expect(stats.rhythm.punch_card.matrix).toHaveLength(7);
+ expect(stats.rhythm.punch_card.matrix[0]).toHaveLength(24);
+ expect(["author_local", "utc"]).toContain(stats.rhythm.punch_card.timezone_mode);
+ expect(stats.people.arrivals).toBeInstanceOf(Array);
+ expect(stats.people.chronotypes).toBeInstanceOf(Array);
+ expect(stats.records).toBeDefined();
+ // `churn` is legitimately null when the history was too deep to walk, so
+ // the key must exist while the value may not.
+ expect(stats).toHaveProperty("churn");
});
it("files index and file detail", async () => {
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 7f9535770..8f5620c5c 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -51,6 +51,7 @@ from .mode import _resolve_index_only_mode
from .persistence import (
_persist_index_only_update,
_run_full_health_rescore,
+ heal_commit_offsets,
stamp_head_commit,
)
from .reporting import (
@@ -748,6 +749,9 @@ def run_update(
# current here while the DB head_commit is still the last full index.
if not dry_run:
stamp_head_commit(repo_path, head)
+ # A capture added after this repo was indexed would otherwise wait
+ # for the next commit to land, which on a quiet repo is never.
+ heal_commit_offsets(repo_path)
_refresh_editor_stamp(repo_path, agents_md)
# The index is current, so any pending marker a bailed update left
# is by definition caught-up (or older); drop it here too rather
@@ -903,6 +907,9 @@ def run_update(
# Keep the DB freshness stamp in lockstep with state.json: the server's
# /repos endpoint reads head_commit from the row, not the state file.
stamp_head_commit(repo_path, head)
+ # This path skips the git phase, so its offset backfill never runs.
+ if not dry_run:
+ heal_commit_offsets(repo_path)
_refresh_editor_stamp(repo_path, agents_md)
# We hold the lock and have advanced to head; drop any stale pending
# marker a bailed update left behind.
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 8b66387bc..9c79ef46d 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -129,6 +129,53 @@ def stamp_head_commit(repo_path: Any, head: str | None) -> None:
run_async(reconcile_repo_head_commit(Path(repo_path), head))
+def heal_commit_offsets(repo_path: Any) -> None:
+ """Fill ``git_commits.committed_offset_minutes`` on a quiet repo.
+
+ The commit walk captures this offset, so any update that ingests commits
+ backfills it on the way past. A repo whose HEAD hasn't moved never gets
+ there — it takes the "already up to date" fast path — which would strand an
+ index written before the column existed with a UTC-only punch card until
+ someone re-indexed. Nobody should have to re-index for a new column, so the
+ fast path calls this too.
+
+ Cheap enough to run unconditionally: one indexed SELECT that returns nothing
+ once the column is filled, and no git at all in that case. Best-effort — a
+ failure here must never turn a clean no-op into an error.
+ """
+ root = Path(repo_path)
+ if not (root / ".repowise" / "wiki.db").is_file():
+ return
+
+ async def _run() -> None:
+ from repowise.core.ingestion.git_indexer import GitIndexer
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ )
+ from repowise.core.persistence.crud import get_repository_by_path
+ from repowise.core.persistence.database import resolve_db_url
+ from repowise.core.pipeline.incremental import reconcile_commit_offsets
+
+ engine = create_engine(resolve_db_url(root))
+ try:
+ # Migrates first: on the fast path this may be the run that adds the
+ # column the backfill is about to fill.
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(root))
+ if repo is None:
+ return
+ await reconcile_commit_offsets(session, repo.id, GitIndexer(root))
+ finally:
+ await engine.dispose()
+
+ with contextlib.suppress(Exception):
+ run_async(_run())
+
+
def _persist_index_only_update(
repo_path: Any,
graph_builder: Any,
diff --git a/packages/core/alembic/versions/0043_stats_birthday_and_churn.py b/packages/core/alembic/versions/0043_stats_birthday_and_churn.py
new file mode 100644
index 000000000..36f2ce29f
--- /dev/null
+++ b/packages/core/alembic/versions/0043_stats_birthday_and_churn.py
@@ -0,0 +1,65 @@
+"""Stats page: first-commit subject, lifetime churn, and per-commit UTC offset.
+
+Three captures the Stats page needs that the existing tables cannot answer.
+
+``repositories.first_commit_subject`` — the root commit's headline, so the page
+can render the repo's opening line rather than just its date. Rides along free
+with the root commit already loaded for ``first_commit_at`` (0037).
+
+``repositories.total_lines_added`` / ``total_lines_deleted`` — lifetime churn.
+Summing ``git_commits`` cannot answer this: that table is bounded to the newest
+N commits, so a repo with more history than the window would silently report a
+windowed figure as a lifetime one. NULL when the history was too deep to walk.
+
+``git_commits.committed_offset_minutes`` — minutes east of UTC at commit time.
+``committed_at`` is stored as a UTC instant, which discards the author's local
+wall-clock, so time-of-day analysis (the punch card, per-author peak hour) read
+a 10pm commit in Mumbai as a mid-afternoon one. Backfilled on the next update
+(``pipeline.incremental.reconcile_commit_offsets``) rather than requiring a
+re-index; rows stay NULL and fall back to UTC until then.
+
+All nullable so existing indexes keep working untouched.
+
+Revision ID: 0043
+Revises: 0042
+Create Date: 2026-07-26
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0043"
+down_revision: str | None = "0042"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "repositories",
+ sa.Column("first_commit_subject", sa.Text(), nullable=True),
+ )
+ op.add_column(
+ "repositories",
+ sa.Column("total_lines_added", sa.Integer(), nullable=True),
+ )
+ op.add_column(
+ "repositories",
+ sa.Column("total_lines_deleted", sa.Integer(), nullable=True),
+ )
+ op.add_column(
+ "git_commits",
+ sa.Column("committed_offset_minutes", sa.Integer(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("git_commits", "committed_offset_minutes")
+ op.drop_column("repositories", "total_lines_deleted")
+ op.drop_column("repositories", "total_lines_added")
+ op.drop_column("repositories", "first_commit_subject")
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index 4563d6ded..68ee2a0f7 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -260,6 +260,7 @@ def load_commit_index(
"author_name": header["author_name"],
"author_email": header["author_email"],
"ts": header["ts"],
+ "tz_offset_minutes": header.get("tz_offset_minutes"),
"subject": header["subject"],
"changes": commit_changes,
"agent_name": prov.agent,
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
index 2fca8a110..ee8952792 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py
@@ -66,6 +66,7 @@ import json
import re
from collections import Counter
from dataclasses import dataclass
+from functools import lru_cache
from pathlib import Path
import structlog
@@ -77,6 +78,7 @@ __all__ = [
"AgentProvenanceClassifier",
"AgentTraceIndex",
"_agent_from_git_ai_note",
+ "agent_from_identity",
"classifier_from_repo_config",
]
@@ -660,6 +662,38 @@ class AgentProvenanceClassifier:
return _HUMAN
+@lru_cache(maxsize=1)
+def _default_classifier() -> AgentProvenanceClassifier:
+ """Shared registry-only classifier for identity lookups (no repo config)."""
+ return AgentProvenanceClassifier()
+
+
+def agent_from_identity(name: str | None, email: str | None) -> str | None:
+ """The agent behind an author identity, or ``None`` for a human.
+
+ Identity only — deliberately ignores commit-message trailers, which mark a
+ commit a *human* authored with agent assistance. Callers asking "is this
+ contributor a person?" (the stats page's people sections) need the identity
+ answer: a human using Claude Code is still a human, while a commit authored
+ by ``[email protected]`` is not.
+
+ Also matches an agent's plain display name, since a locally-configured
+ ``user.name`` of "Claude" carries no vendor e-mail to recognise.
+ """
+ hit = _default_classifier()._identity_match(email or "")
+ if hit:
+ return hit[0]
+ slug = (name or "").strip().lower()
+ if not slug:
+ return None
+ for token, agent in _AGENT_ALIASES:
+ # Whole-token match only: "Aiden" must not read as "aider", and a
+ # surname like "Coplin" must not read as "copilot".
+ if re.fullmatch(rf"{re.escape(token)}([-_ ]?(code|cli|agent|ai|bot))?", slug):
+ return agent
+ return None
+
+
def classifier_from_repo_config(repo_path: object) -> AgentProvenanceClassifier:
"""Build a classifier with any repo-local pattern extensions.
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
index d1522c046..cdbca277d 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
@@ -109,6 +109,10 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
"author_name": c.get("author_name", "") or "",
"author_email": c.get("author_email", "") or "",
"committed_at": _committed_at(c.get("ts", 0) or 0),
+ # Minutes east of UTC at the moment of the commit. ``committed_at``
+ # is a UTC instant, so this is the only way back to the author's
+ # local wall-clock for time-of-day analysis. None on older rows.
+ "committed_offset_minutes": c.get("tz_offset_minutes"),
"subject": subject,
"lines_added": feats.la,
"lines_deleted": feats.ld,
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 2d1dd1011..79e1119e3 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -14,7 +14,7 @@ import json
import os
import threading
import time
-from collections.abc import Callable
+from collections.abc import Callable, Sequence
from pathlib import Path
from typing import Any
@@ -32,13 +32,24 @@ from .co_change import compute_co_changes, compute_co_changes_and_entropy
from .enrich import compute_percentiles
from .file_history import DECAY_REFRESH_KEYS, index_file
from .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defects
-from .records import GitIndexSummary, _CommitRec, _should_skip_index, capture_repo_totals
+from .records import (
+ GitIndexSummary,
+ _CommitRec,
+ _should_skip_index,
+ _tz_offset_minutes,
+ capture_repo_totals,
+)
from .tiers import GitIndexTier
logger = structlog.get_logger(__name__)
__all__ = ["GitIndexer"]
+# Shas per ``git log --no-walk`` call when backfilling commit offsets. Each sha
+# is a 40-char argv entry, and Windows caps a command line near 32k characters —
+# 200 leaves generous headroom while keeping the subprocess count low.
+_OFFSET_LOOKUP_CHUNK = 200
+
class GitIndexer:
"""Mines git history into the git_metadata table.
@@ -654,6 +665,49 @@ class GitIndexer:
# broken call than a genuinely empty history.
return shas or None
+ def capture_commit_offsets(self, shas: Sequence[str]) -> dict[str, int]:
+ """Map each requested sha to its commit's UTC offset in minutes.
+
+ Backfill support for :attr:`GitCommit.committed_offset_minutes`, which
+ older indexes predate.
+
+ Looks the shas up directly (``--no-walk``) rather than walking HEAD and
+ filtering: the persisted commit table can hold more rows than the
+ indexer's current ``commit_limit`` (the window has moved, and co-change
+ walks deeper), so a bounded walk silently leaves the oldest rows unfilled
+ — which is exactly the half-filled state this backfill exists to avoid.
+ Requests are chunked because every sha is an argv entry and Windows caps
+ a command line at ~32k characters.
+
+ Returns ``{}`` on total git failure; a failed chunk drops only its own
+ shas. An unfilled offset degrades that row to UTC, which is what it
+ already was.
+ """
+ if not shas:
+ return {}
+ repo = self._get_repo()
+ if repo is None:
+ return {}
+
+ offsets: dict[str, int] = {}
+ try:
+ for start in range(0, len(shas), _OFFSET_LOOKUP_CHUNK):
+ chunk = list(shas[start : start + _OFFSET_LOOKUP_CHUNK])
+ try:
+ out = repo.git.log("--no-walk", "--format=%H %cI", *chunk)
+ except Exception as exc:
+ logger.debug("commit_offsets_chunk_failed", error=str(exc))
+ continue
+ for line in out.split("\n"):
+ sha, _, iso = line.strip().partition(" ")
+ minutes = _tz_offset_minutes(iso)
+ if sha and minutes is not None:
+ offsets[sha] = minutes
+ finally:
+ with contextlib.suppress(Exception):
+ repo.close()
+ return offsets
+
def capture_new_fix_events(
self, *, known_shas: set[str] | None = None
) -> tuple[list[dict], int, set[str]]:
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
index 592531734..e3206bb21 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
-from datetime import datetime
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -30,6 +30,10 @@ __all__ = [
_RECORD_SEP = "\x00"
_FIELD_SEP = "\x1f"
+# Same cap the per-commit row builder applies to ``subject`` (commit_rows), kept
+# local so this module stays import-free of its sibling.
+_MAX_SUBJECT_LEN = 500
+
# Shared log format for both the batched repo-wide index and the per-file
# ``--follow`` fallback. NOTE: the format ARG uses git's literal ``%x00`` /
# ``%x1f`` escape text — NOT the real bytes — because a real NUL in a subprocess
@@ -45,7 +49,11 @@ _FIELD_SEP = "\x1f"
# across several contributor buckets. Committer name/email (``%cN``/``%cE``)
# ride the same record for agent-provenance classification: a service identity
# as committer over a human author means an agent pushed/amended the change.
-_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%cN%x1f%cE%x1f%ct%x1f%P%x1f%s%x1f%b"
+# ``%cI`` follows ``%ct`` purely for its UTC offset: ``%ct`` is a bare epoch, so
+# the author's local wall-clock is unrecoverable from it. Time-of-day features
+# (the stats punch card, per-author peak hour) are meaningless across timezones
+# without it — a 10pm commit in Mumbai reads as mid-afternoon in UTC.
+_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%cN%x1f%cE%x1f%ct%x1f%cI%x1f%P%x1f%s%x1f%b"
# A git ``--numstat`` line: ``<added>\t<deleted>\t<path>`` where added/deleted
# are decimal counts or ``-`` for binary files. Used to split the trailing
@@ -72,12 +80,33 @@ class _CommitRec:
agent_tier: int | None = None
+def _tz_offset_minutes(iso: str) -> int | None:
+ """Minutes east of UTC for a git ``%cI`` timestamp, or ``None``.
+
+ Only the offset is kept — the instant itself already rides on ``%ct``. Git
+ always emits a numeric offset (never a name), so the tail is ``±HH:MM``.
+ Parsed by hand rather than via ``fromisoformat`` because this runs once per
+ commit on every index and the string shape is fixed.
+ """
+ iso = iso.strip()
+ if len(iso) < 6:
+ return None
+ sign, hh, mm = iso[-6], iso[-5:-3], iso[-2:]
+ if sign not in "+-" or iso[-3] != ":":
+ return None
+ try:
+ minutes = int(hh) * 60 + int(mm)
+ except ValueError:
+ return None
+ return -minutes if sign == "-" else minutes
+
+
def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
"""Parse one ``\\x00``-delimited git-log record into header + numstat lines.
A record (after the leading record separator is stripped) looks like::
- <sha>\\x1f<an>\\x1f<ae>\\x1f<cn>\\x1f<ce>\\x1f<ct>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>
+ <sha>\\x1f<an>\\x1f<ae>\\x1f<cn>\\x1f<ce>\\x1f<ct>\\x1f<cI>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>
The body is multi-line, so the trailing ``--numstat`` block is identified
by the first line matching :data:`_NUMSTAT_RE`; everything before it is
@@ -87,12 +116,12 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
``parents`` (the commit's parent shas).
"""
parts = record.split(_FIELD_SEP)
- if len(parts) < 9:
+ if len(parts) < 10:
return None
- sha, an, ae, cn, ce, ct, parents, subject = parts[:8]
+ sha, an, ae, cn, ce, ct, ciso, parents, subject = parts[:9]
# %b cannot contain the field separator, so the body + numstat tail is the
- # 9th field exactly (join is defensive against an unexpected stray sep).
- body_and_numstat = _FIELD_SEP.join(parts[8:])
+ # 10th field exactly (join is defensive against an unexpected stray sep).
+ body_and_numstat = _FIELD_SEP.join(parts[9:])
body_lines: list[str] = []
numstat_lines: list[str] = []
@@ -118,6 +147,7 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
"committer_name": cn or "",
"committer_email": ce or "",
"ts": ts,
+ "tz_offset_minutes": _tz_offset_minutes(ciso),
"is_merge": len(parent_shas) > 1,
# Parent shas ride along for the agent-trace channel, whose records
# capture the pre-commit HEAD (i.e. a parent of the commit that
@@ -200,23 +230,66 @@ class RepoTotals:
first_commit_at: datetime | None = None
total_contributor_count: int | None = None
first_commit_author: str | None = None
+ first_commit_subject: str | None = None
+ total_lines_added: int | None = None
+ total_lines_deleted: int | None = None
+
+
+# Lifetime churn walks every commit's shortstat, so unlike the other totals it
+# is O(history). Above this many commits the walk is skipped and the fields stay
+# None (the stats page hides the ledger rather than showing a windowed number
+# as if it were lifetime). Raise it if a big repo ever wants the figure enough
+# to pay for the walk.
+_CHURN_COMMIT_CEILING = 50_000
+
+# ``git log --shortstat`` summary line, e.g.
+# " 3 files changed, 41 insertions(+), 9 deletions(-)". Either half can be absent.
+_SHORTSTAT_RE = re.compile(r"(\d+) insertions?\(\+\)|(\d+) deletions?\(-\)")
+
+
+def _lifetime_churn(repo: Any, commit_count: int | None) -> tuple[int | None, int | None]:
+ """Total lines ever added / deleted across the whole history.
+
+ One ``git log --shortstat`` pass, summed here. The per-commit ``git_commits``
+ table cannot answer this: it is bounded to the newest N commits, so summing
+ it silently understates a repo with more history than the window.
+
+ Skipped above :data:`_CHURN_COMMIT_CEILING` commits — returns ``(None, None)``
+ so the caller stores nothing and the UI omits the figure.
+ """
+ if commit_count is None or commit_count > _CHURN_COMMIT_CEILING:
+ return None, None
+ try:
+ out = repo.git.log("--shortstat", "--pretty=tformat:", "HEAD")
+ except Exception:
+ return None, None
+ added = deleted = 0
+ for ins, dels in _SHORTSTAT_RE.findall(out):
+ if ins:
+ added += int(ins)
+ if dels:
+ deleted += int(dels)
+ return added, deleted
def capture_repo_totals(repo: Any) -> RepoTotals:
"""Whole-history stats for *repo* via a handful of cheap git calls.
- All three git calls are O(1) in subprocess count and independent of the
- indexer's ``commit_limit``, so they stay cheap no matter how deep the
+ The first three git calls are O(1) in subprocess count and independent of
+ the indexer's ``commit_limit``, so they stay cheap no matter how deep the
history is:
- ``git rev-list --count HEAD`` — the true total commit count.
- - the root commit(s) — earliest committed date (project age) and the
- founding author's name. Multiple roots (merged histories) use the
- earliest root.
+ - the root commit(s) — earliest committed date (project age), the founding
+ author's name, and that commit's subject. Multiple roots (merged
+ histories) use the earliest root.
- ``git shortlog -sn HEAD`` — one line per mailmap-folded author, so its
line count is the true all-time contributor count. Passing ``HEAD``
keeps shortlog from blocking on stdin.
+ Lifetime churn is the one exception: it walks the history, so it is capped
+ (see :func:`_lifetime_churn`).
+
Each field is captured under its own ``try`` so one failure (empty/unborn
HEAD, detached state, git unavailable) never voids the others.
"""
@@ -232,8 +305,17 @@ def capture_repo_totals(repo: Any) -> RepoTotals:
root_commits = [repo.commit(sha) for sha in roots if sha]
if root_commits:
oldest = min(root_commits, key=lambda c: c.committed_datetime)
- totals.first_commit_at = oldest.committed_datetime
+ # Normalise to UTC before storing. GitPython hands back the author's
+ # local offset, and SQLite drops tzinfo on write — so the raw value
+ # came back looking like a UTC instant while actually being local
+ # wall-clock, shifting the founding date by the author's offset (and
+ # across midnight for anyone far enough east or west).
+ totals.first_commit_at = oldest.committed_datetime.astimezone(UTC)
totals.first_commit_author = (oldest.author.name or None) if oldest.author else None
+ # ``summary`` is the subject line; cap it like every other stored
+ # subject so one pathological commit can't bloat the repo row.
+ subject = (oldest.summary or "").strip() if oldest.summary else ""
+ totals.first_commit_subject = subject[:_MAX_SUBJECT_LEN] or None
except Exception:
pass
@@ -243,6 +325,10 @@ def capture_repo_totals(repo: Any) -> RepoTotals:
except Exception:
pass
+ totals.total_lines_added, totals.total_lines_deleted = _lifetime_churn(
+ repo, totals.total_commit_count
+ )
+
return totals
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 2bed2a4f7..47ada9c1f 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -347,9 +347,18 @@ async def get_perf_coverage(session: AsyncSession, repository_id: str) -> PerfCo
return coverage_for_metrics(metrics, lang_by_path)
-async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
- """Aggregate KPIs over the per-file metrics table."""
- metrics = await get_health_metrics(session, repository_id)
+async def get_health_summary(
+ session: AsyncSession, repository_id: str, *, metrics: list | None = None
+) -> dict:
+ """Aggregate KPIs over the per-file metrics table.
+
+ *metrics* lets a caller that has already loaded the per-file rows hand them
+ over instead of paying for a second full read. Callers doing more than one
+ thing with them — the overview payload computes both these KPIs and the
+ defect-accuracy stat — would otherwise pull the whole table twice.
+ """
+ if metrics is None:
+ metrics = await get_health_metrics(session, repository_id)
if not metrics:
return {
"file_count": 0,
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 701a73877..2a976cdfa 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -265,6 +265,28 @@ async def upsert_git_commits_bulk(
)
+async def get_commits_missing_offset(
+ session: AsyncSession, repository_id: str, *, limit: int = 20_000
+) -> list[str]:
+ """Shas whose ``committed_offset_minutes`` was never captured.
+
+ Indexes written before the offset existed have it NULL on every row, which
+ would leave the punch card mixing author-local and UTC hours. The update
+ path backfills them (see ``pipeline.incremental.reconcile_commit_offsets``);
+ this is the "what still needs filling" half. Bounded so one update can't
+ balloon on a very deep window — the next update picks up the remainder.
+ """
+ rows = await session.execute(
+ select(GitCommit.sha)
+ .where(
+ GitCommit.repository_id == repository_id,
+ GitCommit.committed_offset_minutes.is_(None),
+ )
+ .limit(limit)
+ )
+ return [sha for (sha,) in rows]
+
+
async def delete_git_commits(session: AsyncSession, repository_id: str) -> None:
"""Remove all per-commit rows for a repository (used before a clean reindex)."""
await session.execute(delete(GitCommit).where(GitCommit.repository_id == repository_id))
diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.py
index 67fb52411..361024ff3 100644
--- a/packages/core/src/repowise/core/persistence/crud/repository.py
+++ b/packages/core/src/repowise/core/persistence/crud/repository.py
@@ -136,6 +136,9 @@ async def update_repo_git_totals(
first_commit_at: datetime | None = None,
total_contributor_count: int | None = None,
first_commit_author: str | None = None,
+ first_commit_subject: str | None = None,
+ total_lines_added: int | None = None,
+ total_lines_deleted: int | None = None,
) -> None:
"""Store a repo's whole-history git totals, captured at index time (#730).
@@ -150,6 +153,9 @@ async def update_repo_git_totals(
"first_commit_at": first_commit_at,
"total_contributor_count": total_contributor_count,
"first_commit_author": first_commit_author,
+ "first_commit_subject": first_commit_subject,
+ "total_lines_added": total_lines_added,
+ "total_lines_deleted": total_lines_deleted,
}
if all(v is None for v in updates.values()):
return
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 320f8c592..40a5d8e58 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -63,6 +63,13 @@ class Repository(Base):
# first-commit date). Both NULL until the first index writes them.
total_contributor_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
first_commit_author: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ # The root commit's subject line, and lifetime churn across the whole
+ # history. Both share the #730 reasoning: the bounded ``git_commits`` sample
+ # cannot answer either without understating a long-lived repo. Churn is NULL
+ # when the history was too deep to walk (see ``_lifetime_churn``).
+ first_commit_subject: Mapped[str | None] = mapped_column(Text, nullable=True)
+ total_lines_added: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ total_lines_deleted: Mapped[int | None] = mapped_column(Integer, nullable=True)
settings_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
@@ -555,6 +562,12 @@ class GitCommit(Base):
author_name: Mapped[str] = mapped_column(String(255), nullable=False, default="")
author_email: Mapped[str] = mapped_column(String(255), nullable=False, default="")
committed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ # Minutes east of UTC when the commit was made. ``committed_at`` is stored as
+ # a UTC instant, which loses the author's local wall-clock — so time-of-day
+ # analysis (stats punch card, per-author peak hour) needs this to avoid
+ # reporting a 10pm commit in Mumbai as a mid-afternoon one. NULL on rows
+ # written before the offset was captured.
+ committed_offset_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
subject: Mapped[str] = mapped_column(Text, nullable=False, default="")
# Kamei change features (diff size + diffusion of THIS change)
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 93936a830..7f1da02f6 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -583,6 +583,9 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
await upsert_git_commits_bulk(session, repo_id, rows)
await reconcile_commit_experience(session, repo_id, indexer)
+ # Fills the commit-offset column on indexes written before it existed, so a
+ # new capture never needs a re-index to become useful.
+ await reconcile_commit_offsets(session, repo_id, indexer)
# Refresh the repo-level whole-history totals so age / commit / contributor
# counts keep growing between full re-indexes (#730). Cheap git calls, and
@@ -595,6 +598,9 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any
first_commit_at=totals.first_commit_at,
total_contributor_count=totals.total_contributor_count,
first_commit_author=totals.first_commit_author,
+ first_commit_subject=totals.first_commit_subject,
+ total_lines_added=totals.total_lines_added,
+ total_lines_deleted=totals.total_lines_deleted,
)
await persist_incremental_fix_events(session, repo_id, indexer)
@@ -654,6 +660,45 @@ async def reconcile_commit_experience(session: Any, repo_id: str, indexer: Any)
logger.debug("commit_experience_reconcile_failed", error=str(exc))
+async def reconcile_commit_offsets(session: Any, repo_id: str, indexer: Any) -> None:
+ """Backfill ``committed_offset_minutes`` on commits indexed before it existed.
+
+ The offset is captured on the commit walk, so a full re-index gets it for
+ free — but an update only writes rows for *new* commits, which would leave a
+ repo indexed earlier with author-local hours on recent commits and UTC on
+ everything older. A punch card mixing the two is worse than one that is
+ honestly all-UTC, so the gap is closed here rather than waiting for a
+ re-index nobody should have to run for a new column.
+
+ One ``git log`` and one bulk update, both skipped entirely once the column
+ is filled — the common case is a single cheap SELECT that returns nothing.
+ Failure-isolated like the other update-time reconciles; an unfilled offset
+ just means those rows keep falling back to UTC.
+ """
+ from repowise.core.persistence.crud import (
+ get_commits_missing_offset,
+ upsert_git_commits_bulk,
+ )
+
+ try:
+ pending = await get_commits_missing_offset(session, repo_id)
+ if not pending:
+ return
+
+ offsets = await asyncio.to_thread(indexer.capture_commit_offsets, pending)
+ if not offsets:
+ return
+
+ await upsert_git_commits_bulk(
+ session,
+ repo_id,
+ [{"sha": sha, "committed_offset_minutes": minutes} for sha, minutes in offsets.items()],
+ )
+ logger.info("commit_offsets_backfilled", repo_id=repo_id, count=len(offsets))
+ except Exception as exc:
+ logger.debug("commit_offset_reconcile_failed", error=str(exc))
+
+
def _committed_ts(committed_at: Any) -> float:
"""``committed_at`` as a sortable epoch, or 0 when the row has no date.
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index af79c25f3..21f028754 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -865,6 +865,9 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:
first_commit_at=totals.first_commit_at,
total_contributor_count=totals.total_contributor_count,
first_commit_author=totals.first_commit_author,
+ first_commit_subject=totals.first_commit_subject,
+ total_lines_added=totals.total_lines_added,
+ total_lines_deleted=totals.total_lines_deleted,
)
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 1b92592b7..10aede542 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -278,7 +278,11 @@ async def overview_summary(
)
# --- Health KPIs + deltas vs previous snapshot ------------------------
- health_summary = await crud.get_health_summary(session, repo_id)
+ # Loaded once and handed to both consumers below: the KPI rollup and the
+ # defect-accuracy stat both want every per-file row, and letting each fetch
+ # its own pulled the whole table twice per page load.
+ health_metrics = await crud.get_health_metrics(session, repo_id)
+ health_summary = await crud.get_health_summary(session, repo_id, metrics=health_metrics)
snapshots = await crud.list_health_snapshots(session, repo_id)
hotspot_health: float | None = None
last_indexed_at: str | None = None
@@ -310,6 +314,38 @@ async def overview_summary(
if s in severity_breakdown:
severity_breakdown[s] += 1
+ # "Can you trust this score?" — the backtested precision of the defect
+ # ranking, shown on the health card. Sourced here rather than from the stats
+ # payload: this is a health number, and having the overview reach across
+ # into another page's payload for it is what broke when that payload changed.
+ defect_accuracy = None
+ try:
+ from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
+
+ defect_accuracy = compute_defect_accuracy(
+ [
+ {
+ "file_path": m.file_path,
+ "score": m.score,
+ "nloc": m.nloc,
+ "has_test_file": m.has_test_file,
+ "module": m.module,
+ }
+ for m in health_metrics
+ ],
+ [
+ {
+ "file_path": f.file_path,
+ "biomarker_type": f.biomarker_type,
+ "severity": f.severity,
+ }
+ for f in findings
+ ],
+ )
+ except Exception:
+ # Best-effort: the card omits the panel rather than failing the page.
+ defect_accuracy = None
+
# --- Attention items + onboarding targets -----------------------------
decision_health = await crud.get_decision_health_summary(session, repo_id)
knowledge = await compute_knowledge_map(session, repo_id)
@@ -437,6 +473,7 @@ async def overview_summary(
"worst_performance_path": health_summary.get("worst_performance_path"),
"worst_performance_score": health_summary.get("worst_performance_score"),
"severity_breakdown": severity_breakdown,
+ "defect_accuracy": defect_accuracy,
"last_indexed_at": last_indexed_at,
"snapshot_count": len(snapshots),
"history": [
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index 833581a1c..048b768ff 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -1,40 +1,42 @@
"""/api/repos/{repo_id}/stats/highlights — the "By the Numbers" payload.
-A single read-only aggregate that powers the repo Stats page: a showcase of
-signals the engine already computes across every layer (graph, git, health,
-docs, decisions, dead code) plus a handful of fun superlatives and a derived
-"size class" label. Nothing here is new analysis — it stitches together rows
-the indexer already wrote, so the page is cheap and never blocks.
-
-Every section is built defensively: a missing table or column degrades that
-section to ``None`` / empty rather than 500-ing the whole page, mirroring the
-overview-summary contract.
+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.
"""
from __future__ import annotations
import json
import re
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from itertools import pairwise
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
-from sqlalchemy import func, select
+from sqlalchemy import Integer, func, select
from sqlalchemy.ext.asyncio import AsyncSession
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.persistence import crud
from repowise.core.persistence.models import (
- DecisionRecord,
- ExternalSystem,
GitCommit,
GitMetadata,
GraphMetric,
GraphNode,
GraphNodeMembership,
- LlmCost,
- Page,
+ HealthFileMetric,
WikiSymbol,
)
from repowise.server.deps import get_db_session, verify_api_key
@@ -62,6 +64,63 @@ _SIZE_CLASSES: tuple[tuple[int, str, str], ...] = (
)
_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))
+
def _size_class(total_nloc: int) -> dict[str, Any]:
for ceiling, name, blurb in _SIZE_CLASSES:
@@ -75,6 +134,21 @@ 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)
+
+
# Test-path convention shared with analysis (communities / execution_flows):
# catches conftest, fixtures, and spec files the `is_test` flag misses.
_TEST_PATH_RE = re.compile(
@@ -82,6 +156,11 @@ _TEST_PATH_RE = re.compile(
)
+# ---------------------------------------------------------------------------
+# 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 = (
@@ -98,15 +177,6 @@ async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dic
)
or 0
)
- entry_point_count = (
- await session.scalar(
- select(func.count(GraphNode.id)).where(
- GraphNode.repository_id == repo_id,
- GraphNode.is_entry_point.is_(True),
- )
- )
- or 0
- )
total_nloc = sum(int(m.nloc or 0) for m in metrics)
lang_rows = await session.execute(
@@ -123,7 +193,6 @@ async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dic
return {
"file_count": file_count,
"symbol_count": symbol_count,
- "entry_point_count": entry_point_count,
"module_count": module_count,
"total_nloc": total_nloc,
"language_count": len(languages),
@@ -132,14 +201,22 @@ async def _scale(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dic
}
-def _punch_card_summary(punch: list[list[int]], dated_total: int) -> dict[str, Any]:
+# ---------------------------------------------------------------------------
+# 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 the stored UTC. Also names the
- single hottest cell and the busiest weekday / peak hour (by marginal
- totals) — the human-readable hooks the hero renders. 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."""
+ ``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):
@@ -157,6 +234,7 @@ def _punch_card_summary(punch: list[list[int]], dated_total: int) -> dict[str, A
"busiest_weekday": busiest_weekday,
"peak_hour": peak_hour,
"total": dated_total,
+ "timezone_mode": timezone_mode,
}
@@ -167,7 +245,8 @@ def _commit_velocity(commit_times: list[Any], last_at: Any) -> dict[str, Any]:
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."""
+ 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)
@@ -178,175 +257,311 @@ def _commit_velocity(commit_times: list[Any], last_at: Any) -> dict[str, Any]:
return {"recent_90d": recent, "prior_90d": prior, "pct_change": pct_change}
-async def _activity(session: AsyncSession, repo_id: str, repo: Any) -> dict[str, Any]:
- """Commit volume, project age, agent-vs-human split, and a monthly series.
+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 _chronotypes(
+ per_author_hours: dict[str, list[int]], names: dict[str, str]
+) -> list[dict[str, Any]]:
+ """Each frequent contributor's peak commit hour, with a habit label.
+
+ 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.
+ """
+ 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),
+ }
+ )
+ return sorted(out, key=lambda a: -a["commits"])[:8]
- Buckets the bounded ``git_commits`` table in Python so it is portable
- across SQLite/Postgres date functions (same approach as the agent-trend
- endpoint).
+
+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 captured on the ``Repository`` row at index
- time — the ``git_commits`` table is bounded to the newest N commits, so
- deriving them from it undercounts a long-lived repo badly (issue #730). The
- bounded scan still drives the *sample* signals (agent/fix ratios, monthly
- series, awards) that are meaningful on the recent window.
-
- Also derives the ``biggest_commit`` and ``longest_streak`` awards on the
- same pass — they need per-commit rows anyway, and riding along here keeps
- the endpoint at a single scan of the commits table. The caller moves them
- into the superlatives payload."""
+ 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.agent_name,
- GitCommit.is_fix,
GitCommit.sha,
GitCommit.subject,
GitCommit.lines_added,
GitCommit.lines_deleted,
GitCommit.files_changed,
- GitCommit.change_risk_level,
).where(GitCommit.repository_id == repo_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])
+ resolve = build_identity_resolver([(name, email) for _, _, name, email, *_ in rows])
total = 0
- agent_total = 0
- fix_total = 0
- months: dict[str, dict[str, int]] = {}
- agent_names: dict[str, int] = {}
+ dated = 0
+ with_offset = 0
contributors: set[str] = set()
- first_at: Any = None
+ 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: Any = None
- commit_days: set[Any] = set()
- # Coding-rhythm punch card: commits bucketed by weekday (0=Mon) x hour (UTC,
- # the stored tz). Plus the raw timestamps for the recent-vs-prior velocity
- # window and a low/moderate/high change-risk tally — all off this one scan.
- punch = [[0] * 24 for _ in range(7)]
- commit_times: list[Any] = []
- risk_mix = {"low": 0, "moderate": 0, "high": 0}
- # Top-2 commits by churn: the repo's very first commit is excluded from
- # the "biggest commit" award (every import/initial commit would win), so
- # two candidates are enough to survive dropping it.
- top_commits: list[dict[str, Any]] = []
-
- for row in rows:
- committed_at, author_name, author_email, agent_name, is_fix = row[:5]
- sha, subject, lines_added, lines_deleted, files_changed, change_risk_level = row[5:]
+ 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)
- if is_fix:
- fix_total += 1
- if change_risk_level in risk_mix:
- risk_mix[change_risk_level] += 1
- if agent_name:
- agent_total += 1
- agent_names[agent_name] = agent_names.get(agent_name, 0) + 1
- churn = int(lines_added or 0) + int(lines_deleted or 0)
+ 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_commits.append(
+ top_churn.append(
{
"sha": sha,
"subject": subject or "",
"lines_changed": churn,
- "files_changed": int(files_changed or 0),
+ "files_changed": int(files or 0),
}
)
- top_commits.sort(key=lambda c: -c["lines_changed"])
- del top_commits[2:]
- if committed_at is not None:
- if first_at is None or committed_at < first_at:
- first_at = committed_at
- first_sha = sha
- if last_at is None or committed_at > last_at:
- last_at = committed_at
- commit_days.add(committed_at.date())
- commit_times.append(committed_at)
- punch[committed_at.weekday()][committed_at.hour] += 1
- key = committed_at.strftime("%Y-%m")
- b = months.setdefault(key, {"total": 0, "agent": 0})
- b["total"] += 1
- if agent_name:
- b["agent"] += 1
-
- biggest_commit = next((c for c in top_commits if c["sha"] != first_sha), None)
-
- longest_streak: dict[str, Any] | None = None
- if commit_days:
- 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:
- longest_streak = {
- "days": best_len,
- "start": (best_end - timedelta(days=best_len - 1)).isoformat(),
- "end": best_end.isoformat(),
- }
+ 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:]
- monthly = [
- {"month": m, "total": b["total"], "agent": b["agent"]} for m, b in sorted(months.items())
- ]
- busiest = max(monthly, key=lambda r: r["total"], default=None)
+ 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_card = _punch_card_summary(punch, len(commit_times))
- velocity = _commit_velocity(commit_times, last_at)
+ punch = [[0] * 24 for _ in range(7)]
+ commit_days: set[Any] = set()
+ day_counts: dict[Any, int] = {}
+ per_author_hours: 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
+
+ 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_total = getattr(repo, "total_commit_count", None)
- true_first = getattr(repo, "first_commit_at", None)
- true_contributors = getattr(repo, "total_contributor_count", None)
- effective_total = true_total if true_total is not None else total
+ true_first = _as_utc(getattr(repo, "first_commit_at", None))
effective_first = true_first if true_first is not None else first_at
- effective_contributors = (
- true_contributors if true_contributors is not None else len(contributors)
+ 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 "",
)
- age_days = (last_at - effective_first).days if (effective_first and last_at) else None
return {
- "total_commits": effective_total,
- "agent_commits": agent_total,
- "agent_pct": round(agent_total / total * 100.0, 1) if total else 0.0,
- "fix_commits": fix_total,
- "fix_pct": round(fix_total / total * 100.0, 1) if total else 0.0,
- "contributor_count": effective_contributors,
- "first_commit_at": _iso(effective_first),
- "first_commit_author": getattr(repo, "first_commit_author", None),
- "last_commit_at": _iso(last_at),
- "age_days": age_days,
- "busiest_month": busiest,
- "monthly": monthly,
- "agent_names": sorted(
- ({"name": k, "count": v} for k, v in agent_names.items()),
- key=lambda x: -x["count"],
- ),
+ "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, display_name) if local_mode else [],
+ "arrivals": arrivals,
"biggest_commit": biggest_commit,
- "longest_streak": longest_streak,
- "punch_card": punch_card,
- "velocity": velocity,
- "change_risk_mix": risk_mix,
+ "widest_commit": widest_commit,
}
-async def _people(session: AsyncSession, repo_id: str, all_meta: list[Any]) -> dict[str, Any]:
- """Ownership concentration: top owners, single-owner files, module silos."""
+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
+ )
+ 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]] = {}
@@ -364,12 +579,6 @@ async def _people(session: AsyncSession, repo_id: str, all_meta: list[Any]) -> d
bucket = module_owner_files.setdefault(module, {})
bucket[m.primary_owner_name] = bucket.get(m.primary_owner_name, 0) + 1
- total_files = len(all_meta) or 1
- top_owners = sorted(
- ({"name": k, "file_count": v, "pct": v / total_files} for k, v in owners.items()),
- key=lambda x: -x["file_count"],
- )[:8]
-
silo_count = 0
for module, mowners in module_owner_files.items():
top = max(mowners.values(), default=0)
@@ -392,101 +601,35 @@ async def _people(session: AsyncSession, repo_id: str, all_meta: list[Any]) -> d
return {
"owner_count": len(owners),
- "top_owners": top_owners,
"single_owner_files": single_owner_files,
"silo_count": silo_count,
"truck_factor": truck_factor,
}
-async def _quality(session: AsyncSession, repo_id: str, metrics: list[Any]) -> dict[str, Any]:
- """Health KPIs + the defect-validation stat + dead code + doc coverage."""
- from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
- from repowise.core.analysis.health.grading import distribution as health_distribution
-
- summary = await crud.get_health_summary(session, repo_id)
- findings = await crud.get_health_findings(session, repo_id)
-
- severity = {"critical": 0, "high": 0, "medium": 0, "low": 0}
- for f in findings:
- s = (f.severity or "").lower()
- if s in severity:
- severity[s] += 1
-
- metric_dicts = [
- {
- "file_path": m.file_path,
- "score": m.score,
- "nloc": m.nloc,
- "has_test_file": m.has_test_file,
- "module": m.module,
- }
- for m in metrics
- ]
- finding_dicts = [
- {
- "file_path": f.file_path,
- "biomarker_type": f.biomarker_type,
- "severity": f.severity,
- }
- for f in findings
- ]
- try:
- defect_accuracy = compute_defect_accuracy(metric_dicts, finding_dicts)
- except Exception:
- defect_accuracy = None
- try:
- dist = health_distribution(metric_dicts)
- except Exception:
- dist = None
-
- # Dead code rollup
- dead = await crud.get_dead_code_findings(session, repo_id, status="open")
- deletable_lines = sum(int(f.lines or 0) for f in dead if f.safe_to_delete)
- dead_total = len(dead)
-
- # Doc coverage (avg page confidence) + page count
- avg_conf = float(
- await session.scalar(select(func.avg(Page.confidence)).where(Page.repository_id == repo_id))
- or 0.0
- )
- page_count = (
- await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0
- )
-
- # Test coverage: share of health-metric files that have a test file.
- tested = sum(1 for m in metrics if m.has_test_file)
- test_coverage_pct = round(tested / len(metrics) * 100.0, 1) if metrics else None
-
- return {
- "average_health": summary.get("average_health"),
- "maintainability_average": summary.get("maintainability_average"),
- "performance_average": summary.get("performance_average"),
- "worst_performer_path": summary.get("worst_performer_path"),
- "worst_performer_score": summary.get("worst_performer_score"),
- "open_findings": summary.get("open_findings", len(findings)),
- "severity_breakdown": severity,
- "defect_accuracy": defect_accuracy,
- "distribution": dist,
- "doc_coverage_pct": avg_conf * 100.0,
- "page_count": page_count,
- "test_coverage_pct": test_coverage_pct,
- "dead_code": {"total_findings": dead_total, "deletable_lines": deletable_lines},
- }
+# ---------------------------------------------------------------------------
+# 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 _superlatives(
+async def _records(
session: AsyncSession, repo_id: str, metrics: list[Any], all_meta: list[Any]
) -> dict[str, Any]:
- """The fun "biggest / oldest / most" awards, one row each."""
+ """The "biggest / oldest / gnarliest / most" awards, one row each."""
out: dict[str, Any] = {}
- # Largest file by NLOC
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)}
- # Most complex symbol
+ # 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 = (
await session.execute(
select(WikiSymbol.name, WikiSymbol.file_path, WikiSymbol.complexity_estimate)
@@ -502,7 +645,6 @@ async def _superlatives(
"complexity": int(sym[2]),
}
- # Most-changed file + oldest file (from git metadata)
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"] = {
@@ -511,10 +653,10 @@ async def _superlatives(
}
dated = [m for m in all_meta if m.first_commit_at is not None]
if dated:
- oldest = min(dated, key=lambda m: m.first_commit_at)
+ oldest = min(dated, key=lambda m: _as_utc(m.first_commit_at))
out["oldest_file"] = {
"path": oldest.file_path,
- "first_commit_at": _iso(oldest.first_commit_at),
+ "first_commit_at": _iso(_as_utc(oldest.first_commit_at)),
}
# Most imported file — highest fan-in among non-test file nodes, the
@@ -579,53 +721,12 @@ async def _superlatives(
if best_pair and best_pair["count"] > 0:
out["strongest_coupling"] = best_pair
- return out
-
-
-async def _dependencies(session: AsyncSession, repo_id: str) -> dict[str, Any] | None:
- """Third-party dependency rollup from the manifest-derived rows."""
- rows = (
- await session.execute(
- select(ExternalSystem.ecosystem, ExternalSystem.is_dev_dep, func.count())
- .where(ExternalSystem.repository_id == repo_id)
- .group_by(ExternalSystem.ecosystem, ExternalSystem.is_dev_dep)
- )
- ).all()
- if not rows:
- return None
-
- total = runtime = dev = 0
- ecosystems: dict[str, int] = {}
- for eco, is_dev, n in rows:
- total += n
- if is_dev:
- dev += n
- else:
- runtime += n
- key = eco or "other"
- ecosystems[key] = ecosystems.get(key, 0) + n
-
- return {
- "total": total,
- "runtime": runtime,
- "dev": dev,
- "ecosystems": sorted(
- ({"name": k, "count": v} for k, v in ecosystems.items()),
- key=lambda x: -x["count"],
- ),
- }
-
-
-async def _graph(session: AsyncSession, repo_id: str) -> dict[str, Any]:
- """Dependency-cycle and community structure from the graph snapshot.
-
- Reads the materialized ``graph_node_membership`` rows (no graph rebuild):
- strongly-connected components with ``scc_size > 1`` are import cycles, and
- ``symbol_community_id`` groups the natural neighborhoods. Pure aggregate
- SQL — a couple of GROUP BY scans, never a row pull."""
+ # 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(GraphNodeMembership.scc_id, func.count())
+ select(func.count())
.where(
GraphNodeMembership.repository_id == repo_id,
GraphNodeMembership.scc_size > 1,
@@ -633,54 +734,41 @@ async def _graph(session: AsyncSession, repo_id: str) -> dict[str, Any]:
.group_by(GraphNodeMembership.scc_id)
)
).all()
- cycle_clusters = len(scc_rows)
- files_in_cycles = sum(int(n) for _, n in scc_rows)
- largest_cycle = max((int(n) for _, n in scc_rows), default=0)
-
- community_count = (
- await session.scalar(
- select(func.count(func.distinct(GraphNodeMembership.symbol_community_id))).where(
- GraphNodeMembership.repository_id == repo_id,
- GraphNodeMembership.symbol_community_id.is_not(None),
- )
- )
- or 0
- )
-
- return {
- "cycle_clusters": cycle_clusters,
- "files_in_cycles": files_in_cycles,
- "largest_cycle": largest_cycle,
- "community_count": int(community_count),
- }
-
-
-async def _build(session: AsyncSession, repo_id: str) -> dict[str, Any]:
- """The knowledge base's own build stats — the wiki bragging about itself.
+ if scc_rows:
+ out["largest_cycle"] = {
+ "files": max(int(n) for (n,) in scc_rows),
+ "cycle_count": len(scc_rows),
+ }
- Pages come from the ``wiki_pages`` count; tokens and cost from the
- ``llm_costs`` ledger written during generation. Single aggregate scan;
- every field degrades to 0 when generation was index-only (no LLM spend)."""
- page_count = (
- await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0
- )
- cost_row = (
+ # Symbol-shape shares: what fraction of this codebase is async, and what
+ # fraction carries a docstring. One aggregate row, three counters.
+ shape = (
await session.execute(
select(
- func.coalesce(func.sum(LlmCost.input_tokens + LlmCost.output_tokens), 0),
- func.coalesce(func.sum(LlmCost.cost_usd), 0.0),
- func.count(LlmCost.id),
- ).where(LlmCost.repository_id == repo_id)
+ func.count(WikiSymbol.id),
+ func.sum(func.cast(WikiSymbol.is_async, Integer)),
+ func.count(WikiSymbol.docstring),
+ ).where(WikiSymbol.repository_id == repo_id)
)
- ).one()
- total_tokens, cost_usd, op_count = cost_row
+ ).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),
+ }
- return {
- "page_count": int(page_count),
- "total_tokens": int(total_tokens or 0),
- "cost_usd": round(float(cost_usd or 0.0), 2),
- "llm_operations": int(op_count or 0),
- }
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Endpoint
+# ---------------------------------------------------------------------------
@router.get("/{repo_id}/stats/highlights")
@@ -688,60 +776,68 @@ async def stats_highlights(
repo_id: str,
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> dict:
- """Everything the Stats ("By the Numbers") page needs, in one call."""
+ """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.
+ """
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
- metrics = await crud.get_health_metrics(session, repo_id)
- all_meta = list(
- (await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id)))
- .scalars()
- .all()
- )
-
- decision_count = (
- await session.scalar(
- select(func.count(DecisionRecord.id)).where(DecisionRecord.repository_id == repo_id)
+ # 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)
)
- or 0
- )
- active_decisions = (
- await session.scalar(
- select(func.count(DecisionRecord.id)).where(
- DecisionRecord.repository_id == repo_id,
- DecisionRecord.status == "active",
- )
+ ).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)
)
- or 0
- )
+ ).all()
- activity = await _activity(session, repo_id, repo)
- superlatives = await _superlatives(session, repo_id, metrics, all_meta)
- # Computed on _activity's commit scan for performance, but they are awards
- # so they belong under superlatives in the payload.
- for key in ("biggest_commit", "longest_streak"):
- value = activity.pop(key, None)
+ 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:
- superlatives[key] = 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", [])
return {
- "repo": {
- "id": repo.id,
- "name": repo.name,
- "default_branch": repo.default_branch,
- "head_commit": repo.head_commit,
- },
+ "repo": {"id": repo.id, "name": repo.name},
"scale": await _scale(session, repo_id, metrics),
- "activity": activity,
- "people": await _people(session, repo_id, all_meta),
- "quality": await _quality(session, repo_id, metrics),
- "knowledge": {
- "decision_count": decision_count,
- "active_decision_count": active_decisions,
- },
- "dependencies": await _dependencies(session, repo_id),
- "graph": await _graph(session, repo_id),
- "build": await _build(session, repo_id),
- "superlatives": superlatives,
+ "origin": commits["origin"],
+ "churn": _churn_ledger(repo),
+ "rhythm": rhythm,
+ "people": people,
+ "records": records,
}
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
index 1c7c37e97..9f32d8b6f 100644
--- a/packages/types/src/overview.ts
+++ b/packages/types/src/overview.ts
@@ -5,6 +5,7 @@
*/
import type { Hotspot } from "./git.js";
+import type { DefectAccuracy } from "./health.js";
export interface OverviewRepoMeta {
id: string;
@@ -56,6 +57,10 @@ export interface OverviewHealthHistoryPoint {
export interface OverviewHealth {
average_health: number | null;
+ /** Backtested precision of the defect ranking — the "can you trust this
+ * score?" panel on the health card. Optional so an older server payload
+ * simply omits the panel. */
+ defect_accuracy?: DefectAccuracy | null;
hotspot_health: number | null;
worst_performer_path: string | null;
worst_performer_score: number | null;
diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.ts
index b9e3992a5..eb8e25f0f 100644
--- a/packages/types/src/stats.ts
+++ b/packages/types/src/stats.ts
@@ -2,9 +2,14 @@
* Data contract for the repo Stats ("By the Numbers") page.
*
* Mirrors the payload from `GET /api/repos/{repo_id}/stats/highlights`
- * (packages/server/.../routers/stats.py). Every section is independently
- * built server-side and degrades to null/empty rather than failing the page,
- * so most leaf fields are nullable.
+ * (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.
+ *
+ * Every section is independently built server-side and degrades to null/empty
+ * rather than failing the page, so most leaf fields are nullable.
*/
export interface StatsSizeClass {
@@ -21,7 +26,6 @@ export interface StatsLanguage {
export interface StatsScale {
file_count: number;
symbol_count: number;
- entry_point_count: number;
module_count: number;
total_nloc: number;
language_count: number;
@@ -29,19 +33,43 @@ export interface StatsScale {
size_class: StatsSizeClass;
}
-export interface StatsMonthlyBucket {
- month: string;
- total: number;
- agent: number;
+/** The repo's founding moment — its opening line, not just a date. */
+export interface StatsOrigin {
+ first_commit_at: string | null;
+ /** Founding author (root commit). Null for older indexes / non-git repos. */
+ first_commit_author: string | null;
+ /** The root commit's subject. Null until an index captures it. */
+ first_commit_subject: string | null;
+ last_commit_at: string | null;
+ age_days: number | null;
+ total_commits: number;
+ contributor_count: number;
}
-export interface StatsAgentName {
- name: string;
- count: number;
+/**
+ * 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
+ * would present a windowed figure as a lifetime one. Null when the history was
+ * too deep to walk or the index predates the capture.
+ */
+export interface StatsChurn {
+ lines_added: number;
+ lines_deleted: number;
+ net: number;
+ /** Lines deleted per hundred written. The shareable ratio. */
+ deleted_per_hundred: number;
}
-/** Coding-rhythm heatmap: commit counts by weekday (0=Monday) x hour (0-23,
- * in the stored UTC), with the human-readable hooks the hero renders. */
+/**
+ * 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
+ * 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`.
+ */
export interface StatsPunchCard {
/** 7 rows (Mon..Sun) x 24 columns (hours). */
matrix: number[][];
@@ -51,6 +79,7 @@ export interface StatsPunchCard {
busiest_weekday: number | null;
peak_hour: number | null;
total: number;
+ timezone_mode: "author_local" | "utc";
}
/** Commit momentum: the 90 days ending at the newest commit vs the 90 before. */
@@ -61,111 +90,63 @@ export interface StatsVelocity {
pct_change: number | null;
}
-/** Calibrated just-in-time change-risk tally across the sampled commits. */
-export interface StatsChangeRiskMix {
- low: number;
- moderate: number;
- high: number;
-}
-
-export interface StatsActivity {
- total_commits: number;
- agent_commits: number;
- agent_pct: number;
- fix_commits: number;
- fix_pct: number;
- contributor_count: number;
- first_commit_at: string | null;
- /** Founding author (root commit). Null for older indexes / non-git repos. */
- first_commit_author: string | null;
- last_commit_at: string | null;
- age_days: number | null;
- busiest_month: StatsMonthlyBucket | null;
- monthly: StatsMonthlyBucket[];
- agent_names: StatsAgentName[];
+/** The time-shape of the work. Nothing else in the app has a clock. */
+export interface StatsRhythm {
punch_card: StatsPunchCard;
velocity: StatsVelocity;
- change_risk_mix: StatsChangeRiskMix;
+ 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;
+ /** Distinct calendar days carrying at least one commit. */
+ active_days: number;
+ /** Median days since each file was last touched, anchored to the newest
+ * commit rather than now, so a stale index doesn't inflate it. */
+ code_half_life_days: number | null;
+}
+
+/** 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;
+ commits: number;
+ peak_hour: number;
+ label: "night_owl" | "early_bird" | "daylight";
+ night_pct: number;
+ early_pct: number;
}
-export interface StatsOwner {
+export interface StatsArrival {
name: string;
- file_count: number;
- pct: number;
+ first_commit_at: string | null;
}
+/**
+ * Repo-level concentration only. Per-person detail (ownership share, hotspots
+ * owned, dead-code burden) is the Contributors page's job.
+ */
export interface StatsPeople {
owner_count: number;
- top_owners: StatsOwner[];
+ contributor_count: 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. */
+ arrivals: StatsArrival[];
}
-export interface StatsSeverityBreakdown {
- critical: number;
- high: number;
- medium: number;
- low: number;
-}
-
-export interface StatsDefectAccuracy {
- k: number;
- hits: number;
- precision: number;
- base_rate: number;
- lift: number | null;
- window_days: number;
- scored_files: number;
- defect_files: number;
-}
-
-export interface StatsDistributionBand {
- files: number;
- nloc: number;
- pct: number;
-}
-
-export interface StatsDistribution {
- total_files: number;
- total_nloc: number;
- bands: {
- healthy: StatsDistributionBand;
- warning: StatsDistributionBand;
- alert: StatsDistributionBand;
- };
-}
-
-export interface StatsDeadCode {
- total_findings: number;
- deletable_lines: number;
-}
-
-export interface StatsQuality {
- average_health: number | null;
- maintainability_average: number | null;
- performance_average: number | null;
- worst_performer_path: string | null;
- worst_performer_score: number | null;
- open_findings: number;
- severity_breakdown: StatsSeverityBreakdown;
- defect_accuracy: StatsDefectAccuracy | null;
- distribution: StatsDistribution | null;
- doc_coverage_pct: number;
- page_count: number;
- test_coverage_pct: number | null;
- dead_code: StatsDeadCode;
-}
-
-export interface StatsKnowledge {
- decision_count: number;
- active_decision_count: number;
-}
-
-export interface StatsSuperlatives {
+/**
+ * The superlatives. Several are the only headline treatment their underlying
+ * signal gets anywhere: max CCN is otherwise a sortable column, and import
+ * cycles have no other UI at all.
+ */
+export interface StatsRecords {
largest_file?: { path: string; nloc: number };
+ /** Highest cyclomatic complexity in any single file. */
+ 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 };
@@ -173,6 +154,16 @@ export interface StatsSuperlatives {
* 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. */
+ symbol_shape?: {
+ total: number;
+ async_count: number;
+ async_pct: number;
+ documented_count: number;
+ documented_pct: number;
+ };
/** Largest non-initial commit by churn (added + deleted lines). */
biggest_commit?: {
sha: string;
@@ -180,59 +171,27 @@ export interface StatsSuperlatives {
lines_changed: number;
files_changed: number;
};
- /** Longest run of consecutive days with at least one commit (UTC dates). */
- longest_streak?: { days: number; start: string; end: string };
-}
-
-export interface StatsEcosystem {
- name: string;
- count: number;
-}
-
-export interface StatsDependencies {
- total: number;
- runtime: number;
- dev: number;
- ecosystems: StatsEcosystem[];
-}
-
-/** Import-graph structure: dependency cycles and natural communities, read
- * from the materialized graph snapshot (no rebuild). */
-export interface StatsGraph {
- /** Strongly-connected components with >1 member — circular import clusters. */
- cycle_clusters: number;
- files_in_cycles: number;
- largest_cycle: number;
- community_count: number;
-}
-
-/** The knowledge base's own build cost — the wiki bragging about itself. */
-export interface StatsBuild {
- page_count: number;
- total_tokens: number;
- cost_usd: number;
- llm_operations: number;
+ /** Non-initial commit touching the most files. */
+ widest_commit?: {
+ sha: string;
+ subject: string;
+ files_changed: number;
+ lines_changed: number;
+ };
}
export interface StatsRepo {
id: string;
name: string;
- default_branch: string;
- head_commit: string | null;
}
export interface StatsHighlights {
repo: StatsRepo;
scale: StatsScale;
- activity: StatsActivity;
+ origin: StatsOrigin;
+ /** Null when lifetime churn could not be captured. */
+ churn: StatsChurn | null;
+ rhythm: StatsRhythm;
people: StatsPeople;
- quality: StatsQuality;
- knowledge: StatsKnowledge;
- /** Optional so older payloads (hosted exporters) degrade gracefully. */
- dependencies?: StatsDependencies | null;
- /** Optional so older payloads (hosted exporters) degrade gracefully. */
- graph?: StatsGraph | null;
- /** Optional so older payloads (hosted exporters) degrade gracefully. */
- build?: StatsBuild | null;
- superlatives: StatsSuperlatives;
+ records: StatsRecords;
}
diff --git a/packages/ui/__tests__/stats/punch-card.test.tsx b/packages/ui/__tests__/stats/punch-card.test.tsx
index 344bc24e3..cb38d9f7b 100644
--- a/packages/ui/__tests__/stats/punch-card.test.tsx
+++ b/packages/ui/__tests__/stats/punch-card.test.tsx
@@ -16,7 +16,8 @@ function makePunchCard(): StatsPunchCard {
peak: { weekday: 2, hour: 14, count: 6 },
busiest_weekday: 2,
peak_hour: 14,
- total: 10,
+ timezone_mode: "author_local" as const,
+ total: 10,
};
}
diff --git a/packages/ui/__tests__/stats/size-class-hero.test.tsx b/packages/ui/__tests__/stats/size-class-hero.test.tsx
index 167beab6d..6a52761b9 100644
--- a/packages/ui/__tests__/stats/size-class-hero.test.tsx
+++ b/packages/ui/__tests__/stats/size-class-hero.test.tsx
@@ -7,7 +7,6 @@ function makeScale(overrides: Partial<StatsScale> = {}): StatsScale {
return {
file_count: 1_234_567,
symbol_count: 98_432,
- entry_point_count: 12,
module_count: 80,
total_nloc: 4_200_000,
language_count: 3,
@@ -22,30 +21,29 @@ function makeScale(overrides: Partial<StatsScale> = {}): StatsScale {
}
describe("SizeClassHero", () => {
- it("renders large file and symbol counts compactly", () => {
- render(<SizeClassHero scale={makeScale()} />);
+ it("names the size class and its blurb", () => {
+ render(<SizeClassHero scale={makeScale()} repoName="acme" />);
- expect(screen.getByText("1.2M")).toBeInTheDocument();
- expect(screen.getByText("98.4K")).toBeInTheDocument();
- expect(screen.queryByText("1,234,567")).not.toBeInTheDocument();
- expect(screen.queryByText("98,432")).not.toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Metropolis" })).toBeInTheDocument();
+ expect(screen.getByText("A large codebase.")).toBeInTheDocument();
+ expect(screen.getByText("acme")).toBeInTheDocument();
});
- it("renders small counts verbatim", () => {
- render(<SizeClassHero scale={makeScale({ file_count: 999, symbol_count: 42 })} />);
+ 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.getByText("999")).toBeInTheDocument();
- expect(screen.getByText("42")).toBeInTheDocument();
- expect(screen.getByText("3")).toBeInTheDocument();
+ 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("never clips a figure to an ellipsis", () => {
- render(<SizeClassHero scale={makeScale({ total_nloc: 485_300 })} />);
-
- const value = screen.getByText("485.3K");
- expect(value).toHaveClass("whitespace-nowrap");
- expect(value).not.toHaveClass("truncate");
- // The tile must not be allowed to shrink below its figure.
- expect(value.parentElement).not.toHaveClass("min-w-0");
+ 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
new file mode 100644
index 000000000..3cf20e09e
--- /dev/null
+++ b/packages/ui/__tests__/stats/stat-ribbon.test.tsx
@@ -0,0 +1,45 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { StatRibbon } from "../../src/stats/stat-ribbon.js";
+
+describe("StatRibbon", () => {
+ it("renders each stat as a labelled definition pair", () => {
+ render(
+ <StatRibbon
+ stats={[
+ { label: "Lines of code", value: "419.6K" },
+ { label: "Files", value: "3,146" },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText("Lines of code")).toBeInTheDocument();
+ expect(screen.getByText("419.6K")).toBeInTheDocument();
+ expect(screen.getByText("Files")).toBeInTheDocument();
+ expect(screen.getByText("3,146")).toBeInTheDocument();
+ });
+
+ it("lines figures up as tabular numerals", () => {
+ render(<StatRibbon stats={[{ label: "Files", value: "3,146" }]} />);
+ expect(screen.getByText("3,146")).toHaveClass("tabular-nums");
+ });
+
+ it("drops stats with no value rather than rendering an empty cell", () => {
+ render(
+ <StatRibbon
+ stats={[
+ { label: "Files", value: "3,146" },
+ { label: "Modules", value: "" },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText("Files")).toBeInTheDocument();
+ expect(screen.queryByText("Modules")).not.toBeInTheDocument();
+ });
+
+ it("renders nothing at all when every stat is empty", () => {
+ const { container } = render(<StatRibbon stats={[{ label: "Files", value: "" }]} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/ui/src/stats/activity-trend-chart.tsx b/packages/ui/src/stats/activity-trend-chart.tsx
deleted file mode 100644
index c077e4269..000000000
--- a/packages/ui/src/stats/activity-trend-chart.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-"use client";
-
-import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";
-import type { StatsMonthlyBucket } from "@repowise-dev/types/stats";
-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
-
-interface ActivityTrendChartProps {
- monthly: StatsMonthlyBucket[];
- title?: string;
-}
-
-/** Stacked monthly commit volume, split into agent-authored vs human. The
- * "when did AI start writing this code" view. */
-export function ActivityTrendChart({ monthly, title = "Commits per month" }: ActivityTrendChartProps) {
- if (monthly.length === 0) return null;
-
- const data = monthly.map((b) => ({
- month: b.month,
- human: Math.max(b.total - b.agent, 0),
- agent: b.agent,
- }));
-
- return (
- <Card className="h-full">
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">{title}</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <div className="h-[220px] w-full">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>
- <XAxis
- dataKey="month"
- tick={{ fontSize: 10, fill: "var(--color-text-tertiary)" }}
- tickLine={false}
- axisLine={false}
- interval="preserveStartEnd"
- minTickGap={24}
- />
- <YAxis
- tick={{ fontSize: 10, fill: "var(--color-text-tertiary)" }}
- tickLine={false}
- axisLine={false}
- allowDecimals={false}
- width={40}
- />
- <Tooltip
- cursor={{ fill: "var(--color-bg-muted)", opacity: 0.4 }}
- contentStyle={{
- background: "var(--color-bg-overlay)",
- border: "1px solid var(--color-border-default)",
- borderRadius: 8,
- fontSize: 11,
- color: "var(--color-text-primary)",
- }}
- />
- <Bar dataKey="human" stackId="c" fill="var(--color-accent-primary)" radius={[0, 0, 0, 0]} />
- <Bar dataKey="agent" stackId="c" fill="var(--color-info)" radius={[2, 2, 0, 0]} />
- </BarChart>
- </ResponsiveContainer>
- </div>
- <div className="mt-2 flex items-center gap-4 text-[11px] text-[var(--color-text-secondary)]">
- <span className="flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full" style={{ background: "var(--color-accent-primary)" }} />
- Human
- </span>
- <span className="flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full" style={{ background: "var(--color-info)" }} />
- Agent
- </span>
- </div>
- </CardContent>
- </Card>
- );
-}
diff --git a/packages/ui/src/stats/arrivals-timeline.tsx b/packages/ui/src/stats/arrivals-timeline.tsx
new file mode 100644
index 000000000..a41ee8617
--- /dev/null
+++ b/packages/ui/src/stats/arrivals-timeline.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import * as React from "react";
+import type { StatsArrival } from "@repowise-dev/types/stats";
+import { formatDate, formatNumber } from "../lib/format";
+
+const INITIAL_SHOWN = 12;
+
+/**
+ * Contributors in the order they first showed up.
+ *
+ * The Contributors page shows one person's join date on their own profile, so
+ * the sequence — who was here first, when the team grew — exists nowhere else.
+ * Reads as a roll rather than a chart: the dates are the interesting part, and a
+ * timeline axis would compress the early years into nothing on a repo whose
+ * hiring accelerated.
+ */
+export function ArrivalsTimeline({ arrivals }: { arrivals: StatsArrival[] }) {
+ const [expanded, setExpanded] = React.useState(false);
+ const dated = (arrivals ?? []).filter((a) => a.first_commit_at);
+ if (dated.length === 0) return null;
+
+ const shown = expanded ? dated : dated.slice(0, INITIAL_SHOWN);
+ const hidden = dated.length - shown.length;
+
+ 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
+ </span>
+ </div>
+
+ <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)]">
+ {i + 1}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-sm text-[var(--color-text-primary)]">
+ {a.name}
+ </span>
+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-[var(--color-text-secondary)]">
+ {formatDate(a.first_commit_at as string)}
+ </span>
+ </li>
+ ))}
+ </ol>
+
+ {hidden > 0 && (
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ className="self-start rounded-md px-1 text-xs font-medium text-[var(--color-accent-primary)] underline-offset-4 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-accent-primary)]"
+ >
+ Show {formatNumber(hidden)} more
+ </button>
+ )}
+ </section>
+ );
+}
diff --git a/packages/ui/src/stats/chronotype-list.tsx b/packages/ui/src/stats/chronotype-list.tsx
new file mode 100644
index 000000000..07c6bd334
--- /dev/null
+++ b/packages/ui/src/stats/chronotype-list.tsx
@@ -0,0 +1,74 @@
+import { Moon, Sun, Sunrise } from "lucide-react";
+import type { StatsChronotype } from "@repowise-dev/types/stats";
+import { formatNumber } from "../lib/format";
+
+const LABELS: Record<
+ StatsChronotype["label"],
+ { text: string; icon: typeof Moon; color: string }
+> = {
+ night_owl: { text: "Night owl", icon: Moon, color: "var(--color-info)" },
+ early_bird: { text: "Early bird", icon: Sunrise, color: "var(--color-warning)" },
+ daylight: { text: "Daylight", icon: Sun, color: "var(--color-text-tertiary)" },
+};
+
+function hourLabel(h: number): string {
+ const period = h < 12 ? "am" : "pm";
+ const twelve = h % 12 === 0 ? 12 : h % 12;
+ return `${twelve}${period}`;
+}
+
+/**
+ * When each frequent contributor actually commits.
+ *
+ * Only rendered when the index carries per-commit UTC offsets — in UTC mode the
+ * "night owl" award would just go to whoever lives furthest east, so the server
+ * withholds the data entirely rather than let the UI publish a timezone
+ * artifact as a personality trait.
+ *
+ * The bar is the person's own 24-hour histogram, normalised to their own peak,
+ * so someone with 600 commits and someone with 20 are compared on shape rather
+ * than volume.
+ */
+export function ChronotypeList({ people }: { people: StatsChronotype[] }) {
+ if (!people || people.length === 0) return null;
+
+ 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)]">
+ Night owls &amp; early birds
+ </h3>
+ <span className="font-mono text-[11px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">
+ Each person&apos;s local time
+ </span>
+ </div>
+
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {people.map((p) => {
+ const meta = LABELS[p.label] ?? LABELS.daylight;
+ const Icon = meta.icon;
+ 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.name}
+ </p>
+ <p className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ {formatNumber(p.commits)} commits · peaks around {hourLabel(p.peak_hour)}
+ </p>
+ </div>
+ <span
+ className="flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium"
+ style={{ color: meta.color, borderColor: meta.color }}
+ title={`${p.night_pct}% of commits between 10pm and 5am`}
+ >
+ <Icon className="h-3.5 w-3.5" />
+ {meta.text}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
diff --git a/packages/ui/src/stats/churn-ledger.tsx b/packages/ui/src/stats/churn-ledger.tsx
new file mode 100644
index 000000000..277a8bb36
--- /dev/null
+++ b/packages/ui/src/stats/churn-ledger.tsx
@@ -0,0 +1,90 @@
+import type { StatsChurn } from "@repowise-dev/types/stats";
+import { formatNumber } from "../lib/format";
+
+/**
+ * Lifetime lines written, and how many were later taken back.
+ *
+ * One bar, three readings. The full width is everything ever written; the
+ * hatched tail is what was deleted; what remains is what survived. Deletion
+ * reads as erosion of the whole rather than as a second competing bar, which is
+ * what a diverging two-sided chart would imply — and "taken back" is a share of
+ * the work, not its opposite.
+ *
+ * The ratio line underneath is the point of the whole component.
+ */
+export function ChurnLedger({ data }: { data: StatsChurn }) {
+ if (!data || data.lines_added <= 0) return null;
+
+ // Guard the pathological case where a rewrite deletes more than the running
+ // total ever added: clamp so the bar can't invert or overflow its track.
+ const deleted = Math.max(0, Math.min(data.lines_deleted, data.lines_added));
+ const standing = data.lines_added - deleted;
+ const standingPct = (standing / data.lines_added) * 100;
+
+ const figures = [
+ { label: "Written", value: data.lines_added, tone: "var(--color-text-primary)" },
+ { label: "Taken back", value: data.lines_deleted, tone: "var(--color-error)" },
+ // `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)" },
+ ];
+
+ return (
+ <section aria-label="Lifetime line churn" className="flex flex-col gap-3.5">
+ <div
+ className="flex h-11 overflow-hidden rounded-md border border-[var(--color-border-default)]"
+ role="img"
+ aria-label={`${formatNumber(data.lines_added)} lines written, of which ${formatNumber(
+ data.lines_deleted,
+ )} were later deleted`}
+ >
+ <div
+ className="relative shrink-0 bg-[var(--color-success-muted,rgba(47,125,82,0.12))]"
+ 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)]">
+ {formatNumber(standing)} standing
+ </span>
+ </div>
+ <div
+ className="relative flex-1 border-l border-[var(--color-border-default)]"
+ style={{
+ // 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, rgba(163,58,50,0.14)) 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)]">
+ {formatNumber(deleted)} cut
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap gap-x-10 gap-y-3">
+ {figures.map((f) => (
+ <div key={f.label}>
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {f.label}
+ </p>
+ <p
+ className="text-2xl font-semibold tabular-nums leading-tight"
+ style={{ color: f.tone }}
+ >
+ {formatNumber(f.value)}
+ </p>
+ </div>
+ ))}
+ </div>
+
+ <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)]">
+ {Math.round(data.deleted_per_hundred)} were taken back
+ </strong>
+ .
+ </p>
+ </section>
+ );
+}
diff --git a/packages/ui/src/stats/index.ts b/packages/ui/src/stats/index.ts
index b006d4400..6d4616768 100644
--- a/packages/ui/src/stats/index.ts
+++ b/packages/ui/src/stats/index.ts
@@ -6,8 +6,12 @@ export {
type StatCalloutProps,
type CalloutTone,
} from "./stat-callout";
-export { SuperlativesGrid } from "./superlatives-grid";
-export { ActivityTrendChart } from "./activity-trend-chart";
+export { OriginBlock } from "./origin-block";
+export { ChurnLedger } from "./churn-ledger";
+export { StatRibbon, type RibbonStat } from "./stat-ribbon";
+export { RecordsGrid } from "./records-grid";
+export { ChronotypeList } from "./chronotype-list";
+export { ArrivalsTimeline } from "./arrivals-timeline";
export { PunchCard } from "./punch-card";
export {
WEEKEND_PRESETS,
diff --git a/packages/ui/src/stats/origin-block.tsx b/packages/ui/src/stats/origin-block.tsx
new file mode 100644
index 000000000..b27f51bba
--- /dev/null
+++ b/packages/ui/src/stats/origin-block.tsx
@@ -0,0 +1,77 @@
+import type { StatsOrigin } from "@repowise-dev/types/stats";
+import { formatAgeDays, formatNumber } from "../lib/format";
+
+/** Absolute date in UTC.
+ *
+ * Deliberately not the browser's locale timezone: this is the repo's founding
+ * moment, a fact about the project rather than about the reader, and rendering
+ * 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 new Date(iso).toLocaleDateString(undefined, {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ timeZone: "UTC",
+ });
+}
+
+/**
+ * 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,
+ * the subject in mono at display size, and the prose underneath doing the work
+ * that a "Project age: 1,232 days" tile never could.
+ *
+ * Degrades a rung at a time: without a subject it is still a dated founding,
+ * without a date it renders nothing.
+ */
+export function OriginBlock({ data }: { data: StatsOrigin }) {
+ if (!data.first_commit_at) return null;
+
+ const author = data.first_commit_author;
+ const age = data.age_days != null ? formatAgeDays(data.age_days) : null;
+ const others = Math.max(0, data.contributor_count - 1);
+
+ return (
+ <section
+ aria-label="Project origin"
+ className="border-l-2 border-[var(--color-accent-primary)] pl-5"
+ >
+ <p className="font-mono text-[11px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Root commit · {foundingDate(data.first_commit_at)}
+ </p>
+
+ {data.first_commit_subject && (
+ <p className="mt-2 break-words font-mono text-[15px] font-medium leading-snug text-[var(--color-text-primary)] sm:text-lg">
+ {data.first_commit_subject}
+ </p>
+ )}
+
+ <p className="mt-2.5 text-sm text-[var(--color-text-secondary)]">
+ {age ? (
+ <>
+ It started{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">{age} ago</strong>
+ </>
+ ) : (
+ <>It started here</>
+ )}
+ {author && (
+ <>
+ , written by{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">{author}</strong>
+ </>
+ )}
+ {". "}
+ {others > 0 && (
+ <span className="text-[var(--color-text-tertiary)]">
+ Since then, {formatNumber(others)} more {others === 1 ? "person has" : "people have"}{" "}
+ shown up.
+ </span>
+ )}
+ </p>
+ </section>
+ );
+}
diff --git a/packages/ui/src/stats/punch-card.tsx b/packages/ui/src/stats/punch-card.tsx
index 9a484a203..f8f89987a 100644
--- a/packages/ui/src/stats/punch-card.tsx
+++ b/packages/ui/src/stats/punch-card.tsx
@@ -2,7 +2,6 @@
import * as React from "react";
import type { StatsPunchCard } from "@repowise-dev/types/stats";
-import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { DEFAULT_WEEKEND_PRESET, weekendShare } from "./weekend";
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
@@ -27,10 +26,21 @@ function weekdayLong(i: number): string {
}
/**
- * Coding-rhythm heatmap: a GitHub-punch-card of commit volume by weekday x hour.
- * The signature "when does this team actually code" view — nothing else on the
- * stats page shows temporal shape. Cells ramp the accent color by a sqrt-scaled
- * intensity, and hovering a cell reads out its weekday/hour/count live.
+ * Coding-rhythm heatmap: commit volume by weekday x hour.
+ *
+ * The page's signature view and its focal point — nothing else in the app shows
+ * temporal shape at all. Presented as an open figure rather than inside a card:
+ * the heading, the live readout and the lattice are one object, and a border
+ * around them only competes with the grid's own structure.
+ *
+ * Cells ramp the accent by a sqrt-scaled intensity so low-but-nonzero hours stay
+ * legible against the peak; hovering reads out the exact cell and dims the rest.
+ *
+ * The clock is whatever the server resolved: `author_local` means each commit
+ * was shifted by its own author's UTC offset, which is the only version of this
+ * chart that means anything across timezones. The footer always names which,
+ * because a heatmap that silently changes clocks is worse than one that admits
+ * it hasn't got the data yet.
*/
export function PunchCard({
data,
@@ -46,6 +56,8 @@ export function PunchCard({
const max = data.peak.count || 1;
const weekendPct = weekendShare(data.matrix, weekendDays);
+ const isLocal = data.timezone_mode === "author_local";
+
const readout = hover
? `${weekdayLong(hover.wd)} · ${hourLabel(hover.hr)} · ${hover.count} commit${
hover.count === 1 ? "" : "s"
@@ -55,112 +67,118 @@ export function PunchCard({
: "Commit activity by weekday and hour";
return (
- <Card className="h-full">
- <CardHeader className="flex-row items-center justify-between gap-3 pb-3">
- <CardTitle className="text-sm">Coding rhythm</CardTitle>
- <span className="shrink-0 rounded-full bg-[var(--color-bg-muted)] px-2.5 py-1 text-[11px] font-medium tabular-nums text-[var(--color-text-secondary)]">
+ <section aria-label="Coding rhythm" 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)]">Coding rhythm</h3>
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
{weekendPct}% on weekends
</span>
- </CardHeader>
- <CardContent className="pt-0">
- <p
- className={`mb-3 text-xs transition-colors ${
- hover
- ? "font-medium text-[var(--color-text-primary)]"
- : "text-[var(--color-text-secondary)]"
- }`}
- >
- {readout}
- </p>
+ </div>
- <div className="overflow-x-auto">
- <div className="min-w-[420px]" onMouseLeave={() => setHover(null)}>
- <div className="flex flex-col" style={{ gap: CELL_GAP }}>
- {WEEKDAYS.map((day, wd) => (
- <div key={day} className="flex items-center gap-1.5">
- <span
- className={`w-8 shrink-0 py-px text-right text-[10px] font-medium uppercase tracking-wide transition-colors ${
- hover?.wd === wd
- ? "text-[var(--color-accent-primary)]"
- : "text-[var(--color-text-tertiary)]"
- }`}
- >
- {day}
- </span>
- <div
- className="grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))]"
- style={{ gap: CELL_GAP }}
- >
- {Array.from({ length: 24 }, (_, hr) => {
- const count = data.matrix[wd]?.[hr] ?? 0;
- // sqrt keeps low-but-nonzero hours legible against the peak.
- const intensity = count > 0 ? Math.sqrt(count / max) : 0;
- const isHover = hover?.wd === wd && hover?.hr === hr;
- const dimmed = hover && !isHover && hover.wd !== wd && hover.hr !== hr;
- return (
- <div
- key={hr}
- onMouseEnter={() => setHover({ wd, hr, count })}
- className={`aspect-square rounded-[2px] transition-all duration-100 ${
- isHover
- ? "scale-[1.35] ring-1 ring-[var(--color-accent-primary)]"
- : ""
- }`}
- style={{
- background:
- count > 0 ? "var(--color-accent-primary)" : "var(--color-bg-muted)",
- opacity: isHover
- ? 1
- : count > 0
- ? (dimmed ? 0.5 : 1) * (0.16 + 0.84 * intensity)
- : dimmed
- ? 0.4
- : 1,
- }}
- />
- );
- })}
- </div>
- </div>
- ))}
- </div>
+ {/* 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 ${
+ hover
+ ? "font-medium text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)]"
+ }`}
+ aria-live="polite"
+ >
+ {readout}
+ </p>
- {/* Hour axis — ticks aligned to the 24-column grid. */}
- <div className="mt-1.5 flex items-center gap-1.5">
- <span className="w-8 shrink-0" />
- <div className="relative grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))]">
- {HOUR_TICKS.map(([h, label]) => (
- <span
- key={h}
- className="col-span-1 whitespace-nowrap text-[10px] tabular-nums text-[var(--color-text-tertiary)]"
- style={{ gridColumnStart: h + 1 }}
- >
- {label}
- </span>
- ))}
+ <div className="overflow-x-auto">
+ <div className="min-w-[420px]" onMouseLeave={() => setHover(null)}>
+ <div className="flex flex-col" style={{ gap: CELL_GAP }}>
+ {WEEKDAYS.map((day, wd) => (
+ <div key={day} className="flex items-center gap-2">
+ <span
+ className={`w-8 shrink-0 py-px text-right font-mono text-[10px] uppercase tracking-wide transition-colors ${
+ hover?.wd === wd
+ ? "text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-tertiary)]"
+ }`}
+ >
+ {day}
+ </span>
+ <div
+ className="grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))]"
+ style={{ gap: CELL_GAP }}
+ >
+ {Array.from({ length: 24 }, (_, hr) => {
+ const count = data.matrix[wd]?.[hr] ?? 0;
+ // sqrt keeps low-but-nonzero hours legible against the peak.
+ const intensity = count > 0 ? Math.sqrt(count / max) : 0;
+ const isHover = hover?.wd === wd && hover?.hr === hr;
+ const dimmed = hover && !isHover && hover.wd !== wd && hover.hr !== hr;
+ return (
+ <div
+ key={hr}
+ onMouseEnter={() => setHover({ wd, hr, count })}
+ className={`aspect-square rounded-[2px] transition-all duration-100 ${
+ isHover ? "scale-[1.35] ring-1 ring-[var(--color-accent-primary)]" : ""
+ }`}
+ style={{
+ background:
+ count > 0 ? "var(--color-accent-primary)" : "var(--color-bg-muted)",
+ opacity: isHover
+ ? 1
+ : count > 0
+ ? (dimmed ? 0.5 : 1) * (0.16 + 0.84 * intensity)
+ : dimmed
+ ? 0.4
+ : 1,
+ }}
+ />
+ );
+ })}
+ </div>
</div>
+ ))}
+ </div>
+
+ {/* Hour axis — ticks aligned to the 24-column grid. */}
+ <div className="mt-2 flex items-center gap-2">
+ <span className="w-8 shrink-0" />
+ <div className="relative grid flex-1 grid-cols-[repeat(24,minmax(0,1fr))]">
+ {HOUR_TICKS.map(([h, label]) => (
+ <span
+ key={h}
+ className="col-span-1 whitespace-nowrap font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]"
+ style={{ gridColumnStart: h + 1 }}
+ >
+ {label}
+ </span>
+ ))}
</div>
</div>
</div>
+ </div>
- {/* Legend — hours are bucketed in UTC (git records the commit instant,
- not the author's local offset), so we say so rather than imply local
- time. */}
- <div className="mt-3 flex items-center justify-between gap-2 text-[10px] text-[var(--color-text-tertiary)]">
- <span>Hours in UTC</span>
- <div className="flex items-center gap-1.5">
- <span>Less</span>
- {[0.16, 0.44, 0.72, 1].map((o) => (
- <span
- key={o}
- className="h-2.5 w-2.5 rounded-[2px]"
- style={{ background: "var(--color-accent-primary)", opacity: o }}
- />
- ))}
- <span>More</span>
- </div>
+ <div className="flex items-center justify-between gap-2 border-t border-[var(--color-border-default)] pt-3 text-[10px] text-[var(--color-text-tertiary)]">
+ <span
+ title={
+ isLocal
+ ? "Each commit is placed at its author's own local time, using the UTC offset git recorded with it."
+ : "This index predates the commit-offset capture, so hours fall back to UTC. Run `repowise update` to switch to author-local time."
+ }
+ className="cursor-help font-mono uppercase tracking-[0.1em]"
+ >
+ {isLocal ? "Author-local time" : "Hours in UTC"}
+ </span>
+ <div className="flex items-center gap-1.5">
+ <span>Less</span>
+ {[0.16, 0.44, 0.72, 1].map((o) => (
+ <span
+ key={o}
+ className="h-2.5 w-2.5 rounded-[2px]"
+ style={{ background: "var(--color-accent-primary)", opacity: o }}
+ />
+ ))}
+ <span>More</span>
</div>
- </CardContent>
- </Card>
+ </div>
+ </section>
);
}
diff --git a/packages/ui/src/stats/superlatives-grid.tsx b/packages/ui/src/stats/records-grid.tsx
similarity index 59%
rename from packages/ui/src/stats/superlatives-grid.tsx
rename to packages/ui/src/stats/records-grid.tsx
index 9c7cd455f..42287fad6 100644
--- a/packages/ui/src/stats/superlatives-grid.tsx
+++ b/packages/ui/src/stats/records-grid.tsx
@@ -1,16 +1,19 @@
import * as React from "react";
import {
+ Boxes,
FileText,
- Flame,
GitCommitHorizontal,
Hourglass,
Network,
+ Repeat,
+ Ruler,
+ ScrollText,
+ Spline,
Workflow,
- Boxes,
Zap,
} from "lucide-react";
-import type { StatsSuperlatives } from "@repowise-dev/types/stats";
-import { formatDate, formatNumber, formatRelativeTimeOrNull, truncatePath } from "../lib/format";
+import type { StatsRecords } from "@repowise-dev/types/stats";
+import { formatNumber, formatRelativeTimeOrNull, truncatePath } from "../lib/format";
interface AwardRow {
key: string;
@@ -20,7 +23,7 @@ interface AwardRow {
detail: string;
}
-function buildAwards(s: StatsSuperlatives): AwardRow[] {
+function buildAwards(s: StatsRecords): AwardRow[] {
const rows: AwardRow[] = [];
if (s.largest_file) {
rows.push({
@@ -31,6 +34,15 @@ function buildAwards(s: StatsSuperlatives): AwardRow[] {
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",
@@ -85,15 +97,13 @@ function buildAwards(s: StatsSuperlatives): AwardRow[] {
)} files — in one commit`,
});
}
- if (s.longest_streak) {
+ if (s.widest_commit) {
rows.push({
- key: "streak",
- icon: Flame,
- title: "Longest streak",
- primary: `${formatNumber(s.longest_streak.days)} consecutive days`,
- detail: `commits every day, ${formatDate(s.longest_streak.start)} – ${formatDate(
- s.longest_streak.end,
- )}`,
+ 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) {
@@ -105,20 +115,47 @@ function buildAwards(s: StatsSuperlatives): AwardRow[] {
s.strongest_coupling.b,
26,
)}`,
- detail: `changed together ${formatNumber(s.strongest_coupling.count)}×`,
+ 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;
}
-interface SuperlativesGridProps {
- superlatives: StatsSuperlatives;
-}
-
-/** A grid of "award" cards — the biggest / oldest / most-tangled records in
- * the repo. Renders only the awards that have data. */
-export function SuperlativesGrid({ superlatives }: SuperlativesGridProps) {
- const awards = buildAwards(superlatives);
+/**
+ * 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 (
@@ -140,7 +177,10 @@ export function SuperlativesGrid({ superlatives }: SuperlativesGridProps) {
>
{a.primary}
</p>
- <p className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]" title={a.detail}>
+ <p
+ className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]"
+ title={a.detail}
+ >
{a.detail}
</p>
</div>
diff --git a/packages/ui/src/stats/size-class-hero.tsx b/packages/ui/src/stats/size-class-hero.tsx
index c1fbc9db5..ff5e34942 100644
--- a/packages/ui/src/stats/size-class-hero.tsx
+++ b/packages/ui/src/stats/size-class-hero.tsx
@@ -8,8 +8,6 @@ import {
Globe2,
} from "lucide-react";
import type { StatsScale } from "@repowise-dev/types/stats";
-import { formatCompact, formatNumber, formatLOC } from "../lib/format";
-import { NLOC_HINT } from "./stat-callout";
const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {
Seedling: Sprout,
@@ -21,13 +19,6 @@ const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {
Megalopolis: Globe2,
};
-interface HeroFigure {
- label: string;
- value: string;
- /** Longer clarification shown as a native hover tooltip. */
- hint?: string;
-}
-
interface SizeClassHeroProps {
scale: StatsScale;
/** Repo name, rendered as the eyebrow above the size-class label. */
@@ -35,74 +26,44 @@ interface SizeClassHeroProps {
}
/**
- * The Stats page centerpiece: a warm-washed banner that names the codebase's
- * "size class" (derived from NLOC) and leads with the headline figures. Reads
- * as the centerpiece through spacing, the wash, and one accent — not through
- * outsized type, which would put it out of step with every other page.
+ * 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;
- const figures: HeroFigure[] = [
- { label: "Lines of code", value: formatLOC(scale.total_nloc), hint: NLOC_HINT },
- { label: "Files", value: formatCompact(scale.file_count) },
- { label: "Symbols", value: formatCompact(scale.symbol_count) },
- { label: "Languages", value: formatNumber(scale.language_count) },
- ];
-
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))" }}
>
- {/* Side by side once there is room, but wrapping rather than letting the
- figures crowd the size-class name — the figure tiles refuse to shrink,
- so the row needs somewhere to break. */}
- <div className="flex flex-col gap-6 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between">
- <div className="min-w-0 lg:basis-80 lg:grow">
- {repoName && (
- <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--color-text-tertiary)]">
- {repoName}
+ <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>
- )}
- <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>
+ <h2 className="text-2xl font-bold leading-tight text-[var(--color-text-primary)] sm:text-3xl">
+ {scale.size_class.name}
+ </h2>
</div>
- <p className="mt-3 max-w-md text-sm text-[var(--color-text-secondary)]">
- {scale.size_class.blurb}
- </p>
- </div>
-
- {/* Columns floor at their content width so a six-character figure
- ("485.3K") is never clipped to an ellipsis; they still share the
- leftover width equally, and the group refuses to be squeezed by the
- blurb beside it. */}
- <div className="grid grid-cols-[repeat(2,minmax(max-content,1fr))] gap-3 sm:grid-cols-[repeat(4,minmax(max-content,1fr))] lg:shrink-0">
- {figures.map((f) => (
- <div
- key={f.label}
- title={f.hint}
- className={`rounded-xl border border-[var(--color-border-subtle,var(--color-border-default))] bg-[var(--color-bg-surface)]/70 px-4 py-3 backdrop-blur-sm${f.hint ? " cursor-help" : ""}`}
- >
- <p className="whitespace-nowrap text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
- {f.value}
- </p>
- <p className="mt-0.5 text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {f.label}
- </p>
- </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-ribbon.tsx b/packages/ui/src/stats/stat-ribbon.tsx
new file mode 100644
index 000000000..0ca6b37a9
--- /dev/null
+++ b/packages/ui/src/stats/stat-ribbon.tsx
@@ -0,0 +1,57 @@
+import * as React from "react";
+
+export interface RibbonStat {
+ label: string;
+ value: string;
+ hint?: string;
+}
+
+/**
+ * A row of figures separated by hairlines rather than boxed into cards.
+ *
+ * The stats page used to be ~25 near-identical bordered tiles, which reads as
+ * box soup: every figure claims the same visual weight, so none of them lands.
+ * Rules carry the same grouping at a fraction of the ink, which is why the
+ * public repo pages use them for exactly this job.
+ *
+ * Rendered as a `<dl>` because that is what it is — labelled values, not a
+ * layout grid.
+ */
+export function StatRibbon({ stats }: { stats: RibbonStat[] }) {
+ const shown = stats.filter((s) => s.value);
+ if (shown.length === 0) return null;
+
+ return (
+ <dl className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3 lg:grid-cols-5">
+ {shown.map((s, i) => (
+ <div
+ key={s.label}
+ title={s.hint}
+ className={[
+ "px-4 py-3.5",
+ s.hint ? "cursor-help" : "",
+ // 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(" ")}
+ >
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {s.label}
+ </dt>
+ <dd className="mt-1 text-xl font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {s.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index c535f8625..298905799 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -154,7 +154,7 @@ export default async function OverviewPage({ params }: Props) {
repoId={id}
averageDelta={stats.deltas.average_health}
hotspotDelta={stats.deltas.hotspot_health}
- defectAccuracy={statsHighlights?.quality.defect_accuracy ?? null}
+ defectAccuracy={health.defect_accuracy ?? null}
/>
<ContributorsStripCard repoId={id} />
{/* The two short tiles sit two-up here rather than stacked in
diff --git a/packages/web/src/app/repos/[id]/stats/page.tsx b/packages/web/src/app/repos/[id]/stats/page.tsx
index b88bb5df6..e90985cbb 100644
--- a/packages/web/src/app/repos/[id]/stats/page.tsx
+++ b/packages/web/src/app/repos/[id]/stats/page.tsx
@@ -25,10 +25,10 @@ export default async function StatsPage({ params }: Props) {
<PageShell
title="By the Numbers"
icon={<BarChart3 className="h-5 w-5" />}
- description="A tour of everything the index knows about this codebase — scale, growth, people, and the signals only repowise computes."
+ 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."
maxWidth="wide"
>
- <StatsTabs data={data} />
+ <StatsTabs data={data} repoId={id} />
</PageShell>
);
}
diff --git a/packages/web/src/components/overview/stats-teaser-card.tsx b/packages/web/src/components/overview/stats-teaser-card.tsx
index eb77557ce..e858f9216 100644
--- a/packages/web/src/components/overview/stats-teaser-card.tsx
+++ b/packages/web/src/components/overview/stats-teaser-card.tsx
@@ -1,9 +1,9 @@
import Link from "next/link";
-import { BarChart3, ArrowRight, Bot } from "lucide-react";
+import { BarChart3, ArrowRight, Clock } from "lucide-react";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import { Card } from "@repowise-dev/ui/ui/card";
import { formatLOC, formatNumber, formatAgeDays } from "@repowise-dev/ui/lib/format";
-import { NLOC_HINT, AGENT_PCT_HINT } from "@repowise-dev/ui/stats";
+import { NLOC_HINT } from "@repowise-dev/ui/stats";
interface StatsTeaserCardProps {
repoId: string;
@@ -13,14 +13,14 @@ interface StatsTeaserCardProps {
/** Compact overview teaser that headlines the "size class" + a couple of
* marquee figures and links into the full Stats page. */
export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {
- const { scale, activity } = data;
+ const { scale, origin, rhythm } = data;
const figures: { label: string; value: string; hint?: string }[] = [
{ label: "Lines of code", value: formatLOC(scale.total_nloc), hint: NLOC_HINT },
- { label: "Commits", value: formatNumber(activity.total_commits) },
+ { label: "Commits", value: formatNumber(origin.total_commits) },
{
label: "Age",
- value: activity.age_days != null ? formatAgeDays(activity.age_days) : "—",
+ value: origin.age_days != null ? formatAgeDays(origin.age_days) : "—",
},
];
@@ -60,13 +60,10 @@ export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {
))}
</div>
- {activity.total_commits > 0 && (
- <p
- title={AGENT_PCT_HINT}
- className="mt-3 flex cursor-help items-center gap-1.5 text-xs text-[var(--color-text-secondary)]"
- >
- <Bot className="h-3.5 w-3.5 text-[var(--color-info)]" />
- {activity.agent_pct}% of commits carry a verifiable agent signature
+ {rhythm.longest_streak && (
+ <p className="mt-3 flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ <Clock className="h-3.5 w-3.5 text-[var(--color-accent-primary)]" />
+ Longest streak: {formatNumber(rhythm.longest_streak.days)} consecutive days
</p>
)}
</Link>
diff --git a/packages/web/src/components/stats/architecture-tab.tsx b/packages/web/src/components/stats/architecture-tab.tsx
deleted file mode 100644
index 89b650301..000000000
--- a/packages/web/src/components/stats/architecture-tab.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { Boxes, Lightbulb, Waypoints, FileCode, Repeat, Network } from "lucide-react";
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { StatCallout, SuperlativesGrid } from "@repowise-dev/ui/stats";
-import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-
-export function ArchitectureTab({ data }: { data: StatsHighlights }) {
- const { scale, knowledge, quality, superlatives } = data;
- const graph = data.graph;
-
- const langDistribution: Record<string, number> = {};
- for (const l of scale.languages) langDistribution[l.language] = l.file_count;
-
- return (
- <div className="space-y-5">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
- <StatCallout
- label="Modules"
- value={formatNumber(scale.module_count)}
- icon={<Boxes className="h-4 w-4" />}
- sub={`${formatNumber(scale.file_count)} files`}
- />
- <StatCallout
- label="Entry points"
- value={formatNumber(scale.entry_point_count)}
- icon={<Waypoints className="h-4 w-4" />}
- sub="reachable roots in the graph"
- />
- <StatCallout
- label="Symbols"
- value={formatNumber(scale.symbol_count)}
- icon={<FileCode className="h-4 w-4" />}
- sub={`${formatNumber(scale.language_count)} languages · ${Math.round(
- quality.doc_coverage_pct,
- )}% documented`}
- />
- <StatCallout
- label="Decisions"
- value={formatNumber(knowledge.decision_count)}
- icon={<Lightbulb className="h-4 w-4" />}
- sub={`${formatNumber(knowledge.active_decision_count)} active`}
- />
- {graph && (
- <StatCallout
- label="Dependency cycles"
- value={formatNumber(graph.cycle_clusters)}
- tone={graph.cycle_clusters > 0 ? "warning" : "success"}
- icon={<Repeat className="h-4 w-4" />}
- sub={
- graph.cycle_clusters > 0
- ? `largest spans ${formatNumber(graph.largest_cycle)} files · ${formatNumber(
- graph.files_in_cycles,
- )} caught in a loop`
- : "no circular imports — clean layering"
- }
- />
- )}
- {graph && (
- <StatCallout
- label="Neighborhoods"
- value={formatNumber(graph.community_count)}
- icon={<Network className="h-4 w-4" />}
- sub="natural clusters in the import graph"
- />
- )}
- </div>
-
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <LanguageDonut distribution={langDistribution} />
- <div className="lg:col-span-2">
- <h3 className="mb-2 text-sm font-semibold text-[var(--color-text-primary)]">
- Structural records
- </h3>
- <SuperlativesGrid superlatives={superlatives} />
- </div>
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/by-the-numbers-tab.tsx b/packages/web/src/components/stats/by-the-numbers-tab.tsx
index a807246fa..b933f2ea7 100644
--- a/packages/web/src/components/stats/by-the-numbers-tab.tsx
+++ b/packages/web/src/components/stats/by-the-numbers-tab.tsx
@@ -1,261 +1,57 @@
-import Link from "next/link";
-import {
- Bot,
- CalendarClock,
- Users,
- ShieldCheck,
- Trash2,
- HeartPulse,
- Package,
- TrendingUp,
- TrendingDown,
- Sparkles,
-} from "lucide-react";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import {
+ ChurnLedger,
+ NLOC_HINT,
+ OriginBlock,
+ RecordsGrid,
SizeClassHero,
- StatCallout,
- SuperlativesGrid,
- PunchCard,
- AGENT_PCT_HINT,
+ StatRibbon,
+ type RibbonStat,
} from "@repowise-dev/ui/stats";
-import {
- formatNumber,
- formatAgeDays,
- formatDate,
- formatTokens,
- formatCost,
-} from "@repowise-dev/ui/lib/format";
-import { useWeekendDays } from "@/lib/hooks/use-weekend";
-
-const ECOSYSTEM_NAMES: Record<string, string> = {
- npm: "npm",
- pypi: "PyPI",
- go: "Go",
- cargo: "crates.io",
- nuget: "NuGet",
-};
-
+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, activity, quality, people, superlatives } = data;
- const da = quality.defect_accuracy;
- const deps = data.dependencies;
- const build = data.build;
- const vel = activity.velocity;
- const weekendDays = useWeekendDays();
+ const { scale, origin, churn, records, rhythm } = data;
- // Momentum: recent-vs-prior commit change, or a plain recent count when there
- // is no prior window to compare against (young repo).
- 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);
+ 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="space-y-5">
+ <div className="flex flex-col gap-8">
<SizeClassHero scale={scale} repoName={data.repo.name} />
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="AI authorship"
- value={`${activity.agent_pct}%`}
- tone="info"
- icon={<Bot className="h-4 w-4" />}
- sub={`${formatNumber(activity.agent_commits)} of ${formatNumber(
- activity.total_commits,
- )} commits carry a verifiable agent signature`}
- hint={AGENT_PCT_HINT}
- />
- <StatCallout
- label="Project age"
- value={activity.age_days != null ? formatAgeDays(activity.age_days) : "—"}
- icon={<CalendarClock className="h-4 w-4" />}
- sub={
- activity.first_commit_at
- ? `since ${formatDate(activity.first_commit_at)}${
- activity.first_commit_author ? ` · started by ${activity.first_commit_author}` : ""
- }`
- : "first commit date unknown"
- }
- />
- <StatCallout
- label="Contributors"
- value={formatNumber(activity.contributor_count)}
- icon={<Users className="h-4 w-4" />}
- sub={`${formatNumber(people.owner_count)} hold primary ownership of a file`}
- />
- {da ? (
- <StatCallout
- label="Score finds bugs"
- value={da.lift != null ? `${da.lift}×` : `${Math.round(da.precision * 100)}%`}
- tone="success"
- icon={<ShieldCheck className="h-4 w-4" />}
- sub={`${da.hits}/${da.k} least-healthy files later got a bug fix — ${
- da.lift != null ? `${da.lift}× the base rate` : "above base rate"
- }`}
- />
- ) : (
- <StatCallout
- label="Defect risk"
- value={quality.average_health != null ? `${quality.average_health.toFixed(1)}/10` : "—"}
- tone="accent"
- icon={<HeartPulse className="h-4 w-4" />}
- sub="average health across all files"
- />
- )}
- </div>
+ <OriginBlock data={origin} />
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <div className="lg:col-span-2">
- <PunchCard data={activity.punch_card} weekendDays={weekendDays} />
- </div>
- <div className="flex flex-col gap-4">
- {/* Momentum — recent vs prior 90-day commit volume, with a mini
- comparison bar so the card carries its own weight. */}
- <div className="flex flex-1 flex-col justify-between rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <div className="flex items-center justify-between gap-2">
- <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Momentum
- </p>
- <span
- className={
- vel?.pct_change == null
- ? "text-[var(--color-text-tertiary)]"
- : rising
- ? "text-[var(--color-success)]"
- : "text-[var(--color-warning)]"
- }
- >
- {vel?.pct_change == null ? null : rising ? (
- <TrendingUp className="h-4 w-4" />
- ) : (
- <TrendingDown className="h-4 w-4" />
- )}
- </span>
- </div>
- <p
- className={`mt-1.5 text-2xl font-bold leading-none tabular-nums ${
- vel?.pct_change == null
- ? "text-[var(--color-text-primary)]"
- : rising
- ? "text-[var(--color-success)]"
- : "text-[var(--color-warning)]"
- }`}
- >
- {momentum}
- </p>
- {vel && vel.pct_change != null ? (
- <div className="mt-4 space-y-2">
- {(
- [
- { label: "Prev 90d", value: vel.prior_90d, accent: false },
- { label: "Last 90d", value: vel.recent_90d, accent: true },
- ] as const
- ).map((r) => {
- const barMax = Math.max(vel.recent_90d, vel.prior_90d, 1);
- return (
- <div key={r.label} className="flex items-center gap-2 text-[11px]">
- <span className="w-14 shrink-0 text-[var(--color-text-tertiary)]">
- {r.label}
- </span>
- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
- <div
- className="h-full rounded-full"
- style={{
- width: `${(r.value / barMax) * 100}%`,
- background: r.accent
- ? "var(--color-accent-primary)"
- : "var(--color-text-tertiary)",
- }}
- />
- </div>
- <span className="w-8 shrink-0 text-right tabular-nums text-[var(--color-text-secondary)]">
- {formatNumber(r.value)}
- </span>
- </div>
- );
- })}
- </div>
- ) : (
- <p className="mt-2 text-xs text-[var(--color-text-secondary)]">
- commits in the last 90 days
- </p>
- )}
- </div>
+ <StatRibbon stats={ribbon} />
+
+ {churn && <ChurnLedger data={churn} />}
- {/* This wiki, by the numbers — the knowledge base bragging about
- itself. Spread top-to-bottom so it fills the column. */}
- {build && build.page_count > 0 && (
- <div
- className="flex flex-1 flex-col justify-between overflow-hidden rounded-xl border border-[var(--color-border-default)] p-4"
- style={{ background: "var(--gradient-warm-wash, var(--color-bg-surface))" }}
- >
- <div className="flex items-center gap-2">
- <Sparkles className="h-4 w-4 text-[var(--color-accent-primary)]" />
- <p className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- This wiki, by the numbers
- </p>
- </div>
- <div className="my-3 grid grid-cols-3 gap-2">
- {[
- { v: formatNumber(build.page_count), l: "pages" },
- { v: formatTokens(build.total_tokens), l: "tokens" },
- { v: formatCost(build.cost_usd), l: "to build" },
- ].map((s) => (
- <div key={s.l}>
- <p className="text-lg font-semibold tabular-nums text-[var(--color-text-primary)]">
- {s.v}
- </p>
- <p className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)]">{s.l}</p>
- </div>
- ))}
- </div>
- <p className="text-[11px] text-[var(--color-text-secondary)]">
- distilled from your codebase in {formatNumber(build.llm_operations)} model calls
- </p>
- </div>
+ <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>
- </div>
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
- <StatCallout
- label="Knowledge captured"
- value={formatNumber(data.knowledge.decision_count)}
- sub={`architectural decisions · ${formatNumber(quality.page_count)} wiki pages`}
- />
- <StatCallout
- label="Recoverable lines"
- value={formatNumber(quality.dead_code.deletable_lines)}
- tone="warning"
- icon={<Trash2 className="h-4 w-4" />}
- sub={`safe to delete across ${formatNumber(
- quality.dead_code.total_findings,
- )} dead-code findings`}
- />
- {deps && deps.total > 0 && (
- <StatCallout
- label="Dependencies"
- value={formatNumber(deps.total)}
- icon={<Package className="h-4 w-4" />}
- href={`/repos/${data.repo.id}/architecture?view=deps`}
- LinkComponent={Link}
- sub={`standing on ${formatNumber(deps.runtime)} runtime + ${formatNumber(
- deps.dev,
- )} dev shoulders across ${deps.ecosystems
- .map((e) => ECOSYSTEM_NAMES[e.name] ?? e.name)
- .join(", ")}`}
- />
- )}
- </div>
-
- <div>
- <h3 className="mb-2 text-sm font-semibold text-[var(--color-text-primary)]">
- Records & superlatives
- </h3>
- <SuperlativesGrid superlatives={superlatives} />
- </div>
+ <RecordsGrid records={records} />
+ </section>
</div>
);
}
diff --git a/packages/web/src/components/stats/growth-tab.tsx b/packages/web/src/components/stats/growth-tab.tsx
deleted file mode 100644
index 8bfd63769..000000000
--- a/packages/web/src/components/stats/growth-tab.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { ActivityTrendChart, StatCallout, AGENT_PCT_HINT } from "@repowise-dev/ui/stats";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { formatNumber, formatDate } from "@repowise-dev/ui/lib/format";
-
-function monthLabel(month: string): string {
- // "2026-06" → "Jun 2026"
- const [y, m] = month.split("-");
- const d = new Date(Number(y), Number(m) - 1, 1);
- return new Intl.DateTimeFormat("en-US", { month: "short", year: "numeric" }).format(d);
-}
-
-const RISK_BANDS = [
- { key: "low", label: "Low", color: "var(--color-success)" },
- { key: "moderate", label: "Moderate", color: "var(--color-warning)" },
- { key: "high", label: "High", color: "var(--color-error)" },
-] as const;
-
-export function GrowthTab({ data }: { data: StatsHighlights }) {
- const { activity } = data;
- const risk = activity.change_risk_mix;
- const riskTotal = risk.low + risk.moderate + risk.high;
-
- return (
- <div className="space-y-5">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="Total commits"
- value={formatNumber(activity.total_commits)}
- sub={
- activity.first_commit_at && activity.last_commit_at
- ? `${formatDate(activity.first_commit_at)} → ${formatDate(activity.last_commit_at)}`
- : "across the indexed window"
- }
- />
- <StatCallout
- label="Busiest month"
- value={activity.busiest_month ? monthLabel(activity.busiest_month.month) : "—"}
- sub={
- activity.busiest_month
- ? `${formatNumber(activity.busiest_month.total)} commits`
- : "no monthly data"
- }
- />
- <StatCallout
- label="Fix commits"
- value={`${activity.fix_pct}%`}
- tone="warning"
- sub={`${formatNumber(activity.fix_commits)} commits classified as fixes`}
- />
- <StatCallout
- label="Agent commits"
- value={`${activity.agent_pct}%`}
- tone="info"
- sub={`${formatNumber(activity.agent_commits)} commits with verifiable agent signatures`}
- hint={AGENT_PCT_HINT}
- />
- </div>
-
- {riskTotal > 0 && (
- <Card>
- <CardHeader className="flex-row items-center justify-between gap-3 pb-3">
- <CardTitle className="text-sm">Change-risk mix</CardTitle>
- <span className="text-[11px] text-[var(--color-text-tertiary)]">
- calibrated per-commit risk across {formatNumber(riskTotal)} commits
- </span>
- </CardHeader>
- <CardContent className="pt-0">
- <div className="flex h-3 w-full overflow-hidden rounded-full">
- {RISK_BANDS.map((b) => {
- const pct = (risk[b.key] / riskTotal) * 100;
- return pct > 0 ? (
- <div
- key={b.key}
- style={{ width: `${pct}%`, background: b.color }}
- title={`${b.label}: ${risk[b.key]} (${Math.round(pct)}%)`}
- />
- ) : null;
- })}
- </div>
- <div className="mt-3 grid grid-cols-3 gap-2 text-xs">
- {RISK_BANDS.map((b) => (
- <div key={b.key} className="flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full" style={{ background: b.color }} />
- <span className="text-[var(--color-text-secondary)]">{b.label}</span>
- <span className="tabular-nums text-[var(--color-text-tertiary)]">
- {formatNumber(risk[b.key])}
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
-
- <ActivityTrendChart monthly={activity.monthly} />
-
- {activity.agent_names.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Agents at work</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ul className="divide-y divide-[var(--color-border-subtle,var(--color-border-default))]">
- {activity.agent_names.map((a) => (
- <li key={a.name} className="flex items-center justify-between py-2 text-sm">
- <span className="truncate text-[var(--color-text-primary)]">{a.name}</span>
- <span className="tabular-nums text-[var(--color-text-secondary)]">
- {formatNumber(a.count)} commits
- </span>
- </li>
- ))}
- </ul>
- </CardContent>
- </Card>
- )}
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/people-tab.tsx b/packages/web/src/components/stats/people-tab.tsx
index 2275ecdc0..9ba0b6082 100644
--- a/packages/web/src/components/stats/people-tab.tsx
+++ b/packages/web/src/components/stats/people-tab.tsx
@@ -1,84 +1,73 @@
-import { Users, UserCheck, AlertTriangle, Truck } from "lucide-react";
+import Link from "next/link";
+import { AlertTriangle, Users } from "lucide-react";
import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { StatCallout } from "@repowise-dev/ui/stats";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
+import { ArrivalsTimeline, ChronotypeList, StatCallout } from "@repowise-dev/ui/stats";
import { formatNumber } from "@repowise-dev/ui/lib/format";
-export function PeopleTab({ data }: { data: StatsHighlights }) {
- const { people, activity } = data;
- const maxFiles = people.top_owners[0]?.file_count ?? 0;
- const truck = people.truck_factor;
+/**
+ * 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";
return (
- <div className="space-y-5">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
- {truck != null && (
- <StatCallout
- label="Truck factor"
- value={truck}
- tone={truck <= 2 ? "warning" : "default"}
- icon={<Truck className="h-4 w-4" />}
- sub={
- truck === 1
- ? "one person owns most of the code"
- : `lose ${truck} people and >50% of files lose their owner`
- }
- />
- )}
+ <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(activity.contributor_count)}
+ value={formatNumber(people.contributor_count)}
icon={<Users className="h-4 w-4" />}
- sub="distinct commit authors"
- />
- <StatCallout
- label="File owners"
- value={formatNumber(people.owner_count)}
- icon={<UserCheck className="h-4 w-4" />}
- sub="hold primary ownership of ≥1 file"
+ 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"
- icon={<AlertTriangle className="h-4 w-4" />}
- sub="bus factor of 1 — knowledge risk"
+ sub="only one person has ever really touched them"
/>
<StatCallout
label="Knowledge silos"
value={formatNumber(people.silo_count)}
- tone="warning"
- sub="modules >80% owned by one person"
+ tone={people.silo_count > 0 ? "warning" : "default"}
+ sub="modules where one person owns over 80%"
/>
</div>
- {people.top_owners.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Top contributors by files owned</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ul className="space-y-2.5">
- {people.top_owners.map((o) => (
- <li key={o.name} className="space-y-1">
- <div className="flex items-center justify-between text-sm">
- <span className="truncate text-[var(--color-text-primary)]">{o.name}</span>
- <span className="tabular-nums text-[var(--color-text-secondary)]">
- {formatNumber(o.file_count)} files · {Math.round(o.pct * 100)}%
- </span>
- </div>
- <div className="h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
- <div
- className="h-full rounded-full bg-[var(--color-accent-primary)]"
- style={{ width: `${maxFiles ? (o.file_count / maxFiles) * 100 : 0}%` }}
- />
- </div>
- </li>
- ))}
- </ul>
- </CardContent>
- </Card>
+ {people.chronotypes.length > 0 ? (
+ <ChronotypeList people={people.chronotypes} />
+ ) : (
+ 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-muted)] 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/quality-tab.tsx b/packages/web/src/components/stats/quality-tab.tsx
deleted file mode 100644
index b200fa12c..000000000
--- a/packages/web/src/components/stats/quality-tab.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import type { StatsHighlights } from "@repowise-dev/types/stats";
-import { StatCallout } from "@repowise-dev/ui/stats";
-import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { formatNumber, truncatePath } from "@repowise-dev/ui/lib/format";
-
-const BAND_COLOR: Record<string, string> = {
- healthy: "var(--color-success)",
- warning: "var(--color-warning)",
- alert: "var(--color-error)",
-};
-
-function score(v: number | null): string {
- return v != null ? `${v.toFixed(1)}/10` : "—";
-}
-
-export function QualityTab({ data }: { data: StatsHighlights }) {
- const { quality, scale } = data;
- const dist = quality.distribution;
-
- const langDistribution: Record<string, number> = {};
- for (const l of scale.languages) langDistribution[l.language] = l.file_count;
-
- return (
- <div className="space-y-5">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="Defect risk"
- value={score(quality.average_health)}
- tone="accent"
- sub="bug-predictive headline score"
- />
- <StatCallout
- label="Maintainability"
- value={score(quality.maintainability_average)}
- sub="cohesion, brain methods, DRY"
- />
- <StatCallout
- label="Performance"
- value={score(quality.performance_average)}
- sub="I/O-in-loop / N+1 risk"
- />
- <StatCallout
- label="Test coverage"
- value={quality.test_coverage_pct != null ? `${quality.test_coverage_pct}%` : "—"}
- sub="files with a matching test"
- />
- </div>
-
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- {dist && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Health distribution</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <div className="flex h-3 w-full overflow-hidden rounded-full">
- {(["healthy", "warning", "alert"] as const).map((b) =>
- dist.bands[b].pct > 0 ? (
- <div
- key={b}
- style={{ width: `${dist.bands[b].pct}%`, background: BAND_COLOR[b] }}
- title={`${b}: ${dist.bands[b].pct}%`}
- />
- ) : null,
- )}
- </div>
- <div className="mt-3 grid grid-cols-3 gap-2 text-xs">
- {(["healthy", "warning", "alert"] as const).map((b) => (
- <div key={b} className="flex items-center gap-1.5">
- <span
- className="h-2 w-2 rounded-full"
- style={{ background: BAND_COLOR[b] }}
- />
- <span className="capitalize text-[var(--color-text-secondary)]">{b}</span>
- <span className="tabular-nums text-[var(--color-text-tertiary)]">
- {dist.bands[b].files}
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
-
- <LanguageDonut distribution={langDistribution} />
- </div>
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <StatCallout
- label="Open findings"
- value={formatNumber(quality.open_findings)}
- sub={`${quality.severity_breakdown.critical} critical · ${quality.severity_breakdown.high} high`}
- />
- <StatCallout
- label="Dead code"
- value={formatNumber(quality.dead_code.deletable_lines)}
- tone="warning"
- sub={`recoverable lines · ${formatNumber(quality.dead_code.total_findings)} findings`}
- />
- <StatCallout
- label="Doc coverage"
- value={`${Math.round(quality.doc_coverage_pct)}%`}
- sub={`${formatNumber(quality.page_count)} wiki pages`}
- />
- <StatCallout
- label="Lowest-scoring file"
- value={quality.worst_performer_score != null ? score(quality.worst_performer_score) : "—"}
- tone="warning"
- sub={
- quality.worst_performer_path
- ? truncatePath(quality.worst_performer_path, 30)
- : "no data"
- }
- />
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/stats/rhythm-tab.tsx b/packages/web/src/components/stats/rhythm-tab.tsx
new file mode 100644
index 000000000..a99f44bb0
--- /dev/null
+++ b/packages/web/src/components/stats/rhythm-tab.tsx
@@ -0,0 +1,106 @@
+"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} />
+
+ <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
index f1a7b424a..452f77ead 100644
--- a/packages/web/src/components/stats/stats-tabs.tsx
+++ b/packages/web/src/components/stats/stats-tabs.tsx
@@ -5,51 +5,54 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/ta
import { ErrorBoundary } from "@repowise-dev/ui/shared";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import { ByTheNumbersTab } from "./by-the-numbers-tab";
-import { GrowthTab } from "./growth-tab";
+import { RhythmTab } from "./rhythm-tab";
import { PeopleTab } from "./people-tab";
-import { QualityTab } from "./quality-tab";
-import { ArchitectureTab } from "./architecture-tab";
-const TAB_VALUES = ["numbers", "growth", "people", "quality", "architecture"] as const;
+/**
+ * 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];
-export function StatsTabs({ data }: { data: StatsHighlights }) {
- const [tab, setTab] = useQueryState(
+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).withDefault("numbers"),
+ 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 (typeof TAB_VALUES)[number])}>
+ <Tabs value={tab} onValueChange={(v) => setTab(v as TabValue)}>
<TabsList>
<TabsTrigger value="numbers">By the Numbers</TabsTrigger>
- <TabsTrigger value="growth">Growth &amp; Activity</TabsTrigger>
+ <TabsTrigger value="rhythm">Rhythm</TabsTrigger>
<TabsTrigger value="people">People</TabsTrigger>
- <TabsTrigger value="quality">Code &amp; Quality</TabsTrigger>
- <TabsTrigger value="architecture">Architecture</TabsTrigger>
</TabsList>
<TabsContent value="numbers" className="mt-4">
<ErrorBoundary title="Couldn't load stats">
<ByTheNumbersTab data={data} />
</ErrorBoundary>
</TabsContent>
- <TabsContent value="growth" className="mt-4">
- <ErrorBoundary title="Couldn't load activity">
- <GrowthTab data={data} />
+ <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} />
- </ErrorBoundary>
- </TabsContent>
- <TabsContent value="quality" className="mt-4">
- <ErrorBoundary title="Couldn't load quality">
- <QualityTab data={data} />
- </ErrorBoundary>
- </TabsContent>
- <TabsContent value="architecture" className="mt-4">
- <ErrorBoundary title="Couldn't load architecture">
- <ArchitectureTab data={data} />
+ <PeopleTab data={data} repoId={repoId} />
</ErrorBoundary>
</TabsContent>
</Tabs>
diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.py
index 82e2729cb..22f073b35 100644
--- a/tests/unit/ingestion/test_agent_provenance.py
+++ b/tests/unit/ingestion/test_agent_provenance.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import time
+from datetime import UTC, datetime
from unittest.mock import MagicMock
from repowise.core.ingestion.git_commit_index import (
@@ -354,7 +355,11 @@ def _log_record(
sha, an, ae, subj, body="", files=((1, 0, "src/a.py"),), ts=None, parents=""
) -> str:
ts = ts or int(time.time())
- lines = [f"\x00{sha}\x1f{an}\x1f{ae}\x1f{an}\x1f{ae}\x1f{ts}\x1f{parents}\x1f{subj}\x1f{body}"]
+ iso = datetime.fromtimestamp(int(ts), UTC).isoformat()
+ lines = [
+ f"\x00{sha}\x1f{an}\x1f{ae}\x1f{an}\x1f{ae}\x1f{ts}\x1f{iso}"
+ f"\x1f{parents}\x1f{subj}\x1f{body}"
+ ]
for a, d, p in files:
lines.append(f"{a}\t{d}\t{p}")
return "\n".join(lines)
diff --git a/tests/unit/server/test_stats_bot_filter.py b/tests/unit/server/test_stats_bot_filter.py
new file mode 100644
index 000000000..ef92e0925
--- /dev/null
+++ b/tests/unit/server/test_stats_bot_filter.py
@@ -0,0 +1,63 @@
+"""Automation is excluded from the Stats page's people sections.
+
+A bot's "peak hour" is a cron schedule and its "arrival" is the day someone
+enabled it — neither is a fact about how anyone works, and leaving dependabot in
+a night-owl leaderboard makes the whole list read as noise.
+
+The precision direction matters more than recall here: a missed bot is one odd
+row, but a human misread as automation disappears from the page entirely. Hence
+the human cases below, all of which contain an agent's name as a substring.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.routers.stats import _is_bot
+
+AGENTS = [
+ # Coding agents, recognised via the ingestion layer's provenance registry.
+ ("Claude", "[email protected]"),
+ ("claude[bot]", "claude[bot]@users.noreply.github.com"),
+ ("claude-code", "[email protected]"),
+ ("Cursor Agent", "[email protected]"),
+ ("cursor", "[email protected]"),
+ ("codex", "[email protected]"),
+ ("Codex", "[email protected]"),
+ ("copilot-swe-agent[bot]", "copilot-swe-agent[bot]@users.noreply.github.com"),
+ ("devin-ai-integration[bot]", "devin-ai-integration[bot]@users.noreply.github.com"),
+ ("gemini", "[email protected]"),
+ # CI automation, which provenance has no reason to model.
+ ("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com"),
+ ("github-actions[bot]", "[email protected]"),
+ ("renovate", "[email protected]"),
+]
+
+HUMANS = [
+ ("Raghav Chamadiya", "[email protected]"),
+ # Each of these contains an agent token as a substring.
+ ("Claudia Silva", "[email protected]"),
+ ("Jean-Claude Dupont", "[email protected]"),
+ ("Aiden Cursorly", "[email protected]"),
+ ("Devin Townsend", "[email protected]"),
+ ("Abbot Smith", "[email protected]"),
+ ("Gemma Wright", "[email protected]"),
+ # A real employee at a vendor domain is not that vendor's agent identity.
+ ("Jane Doe", "[email protected]"),
+]
+
+
[email protected](("name", "email"), AGENTS)
+def test_automation_is_filtered(name: str, email: str) -> None:
+ assert _is_bot(name, email) is True
+
+
[email protected](("name", "email"), HUMANS)
+def test_humans_survive(name: str, email: str) -> None:
+ assert _is_bot(name, email) is False
+
+
+def test_blank_identity_is_not_automation() -> None:
+ """An unattributed commit is a miss, not a bot — never drop it silently."""
+ assert _is_bot(None, None) is False
+ assert _is_bot("", "") is False
diff --git a/tests/unit/server/test_stats_contributors.py b/tests/unit/server/test_stats_contributors.py
index 618e51011..16e1dc7f5 100644
--- a/tests/unit/server/test_stats_contributors.py
+++ b/tests/unit/server/test_stats_contributors.py
@@ -14,7 +14,7 @@ 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 _activity
+from repowise.server.routers.stats import _commit_pass
from tests.unit.server.conftest import create_test_repo
@@ -53,7 +53,7 @@ async def test_contributor_count_folds_noreply_and_same_name(client: AsyncClient
async with get_session(app.state.session_factory) as session:
repo_row = await get_repository(session, repo["id"])
- activity = await _activity(session, repo["id"], repo_row)
+ activity = (await _commit_pass(session, repo["id"], repo_row))["origin"]
# No whole-history totals stored on the repo, so the count folds the
# bounded sample's author identities (Jane + Bob, not 4).
@@ -85,7 +85,7 @@ async def test_activity_prefers_whole_history_totals(client: AsyncClient, app) -
async with get_session(app.state.session_factory) as session:
repo_row = await get_repository(session, repo["id"])
- activity = await _activity(session, repo["id"], repo_row)
+ activity = (await _commit_pass(session, repo["id"], repo_row))["origin"]
assert activity["total_commits"] == 5000
assert activity["contributor_count"] == 42
diff --git a/tests/unit/server/test_stats_signals.py b/tests/unit/server/test_stats_signals.py
index 61ed70e5a..f2ad5d8a8 100644
--- a/tests/unit/server/test_stats_signals.py
+++ b/tests/unit/server/test_stats_signals.py
@@ -1,9 +1,8 @@
-"""New "By the Numbers" signals: punch card, commit velocity, change-risk mix,
-truck factor, dependency cycles, and the wiki build meta.
+"""Unit tests for the Stats page's derived signals.
-The pure summarizers are unit-tested directly; the commit-scan signals go
-through ``_activity`` on a seeded ``git_commits`` table so the wiring (SELECT
-columns, bucketing) is covered end to end.
+Covers the punch-card fold, commit velocity, the truck-factor rollup, and the
+single ``_commit_pass`` scan that produces the origin / rhythm / people sections
+from one read of the commits table.
"""
from __future__ import annotations
@@ -17,7 +16,7 @@ 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 (
- _activity,
+ _commit_pass,
_commit_velocity,
_people,
_punch_card_summary,
@@ -57,7 +56,7 @@ def test_punch_card_summary_peak() -> None:
punch[6][12] = 2 # Sunday (weekend)
dated = 10 + 4 + 3 + 2
- out = _punch_card_summary(punch, dated_total=dated)
+ out = _punch_card_summary(punch, dated_total=dated, timezone_mode="utc")
assert out["peak"] == {"weekday": 2, "hour": 14, "count": 10}
assert out["busiest_weekday"] == 2
@@ -66,7 +65,7 @@ def test_punch_card_summary_peak() -> None:
def test_punch_card_summary_empty() -> None:
- out = _punch_card_summary([[0] * 24 for _ in range(7)], dated_total=0)
+ out = _punch_card_summary([[0] * 24 for _ in range(7)], dated_total=0, timezone_mode="utc")
assert out["peak"] is None
assert out["busiest_weekday"] is None
assert out["total"] == 0
@@ -102,19 +101,17 @@ def _meta(owner: str, path: str) -> SimpleNamespace:
return SimpleNamespace(primary_owner_name=owner, bus_factor=1, file_path=path)
-async def test_truck_factor_single_dominant_owner() -> None:
+def test_truck_factor_single_dominant_owner() -> None:
# One owner holds 8/10 files → truck factor 1.
metas = [_meta("Ada", f"a{i}.py") for i in range(8)] + [
_meta("Bob", "b.py"),
_meta("Cara", "c.py"),
]
- out = await _people(None, "repo", metas)
+ out = _people(metas)
assert out["truck_factor"] == 1
-async def test_truck_factor_spread_ownership() -> None:
+def test_truck_factor_spread_ownership() -> None:
# Four owners with 3/3/2/2 → need 2 to cross 50% of 10.
metas = (
[_meta("Ada", f"a{i}.py") for i in range(3)]
@@ -122,23 +119,22 @@ async 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 = await _people(None, "repo", metas)
+ out = _people(metas)
assert out["truck_factor"] == 2
-async def test_truck_factor_none_without_owners() -> None:
- out = await _people(None, "repo", [SimpleNamespace(primary_owner_name=None, bus_factor=0, file_path="x.py")])
+def test_truck_factor_none_without_owners() -> None:
+ out = _people([SimpleNamespace(primary_owner_name=None, bus_factor=0, file_path="x.py")])
assert out["truck_factor"] is None
# ---------------------------------------------------------------------------
-# End-to-end through _activity on a seeded commits table
+# End-to-end through _commit_pass on a seeded commits table
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
-async def test_activity_punch_card_and_risk_mix(client: AsyncClient, app) -> None:
+async def test_punch_card_buckets_commits(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
rows = [
# Wednesday 2024-01-03 at 14:00 UTC — weekday 2, hour 14.
@@ -154,38 +150,65 @@ async def test_activity_punch_card_and_risk_mix(client: AsyncClient, app) -> Non
async with get_session(app.state.session_factory) as session:
repo_row = await get_repository(session, repo["id"])
- activity = await _activity(session, repo["id"], repo_row)
+ out = await _commit_pass(session, repo["id"], repo_row)
- pc = activity["punch_card"]
+ pc = out["rhythm"]["punch_card"]
assert pc["matrix"][2][14] == 2 # both Wednesday-2pm commits landed in one cell
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
-
- assert activity["change_risk_mix"] == {"low": 1, "moderate": 1, "high": 2}
+ # No commit carries an offset, so the card stays honestly in UTC rather
+ # than mixing clocks.
+ assert pc["timezone_mode"] == "utc"
@pytest.mark.asyncio
-async def test_graph_and_build_degrade_to_zero(client: AsyncClient, app) -> None:
- """The graph + build sections return a fully-shaped zero payload on a repo
- with no graph-membership or LLM-cost rows (index-only / brand-new repo)."""
- from repowise.server.routers.stats import _build, _graph
+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)
+
+ 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"]["busiest_day"] is None
+ assert out["rhythm"]["velocity"] == {"recent_90d": 0, "prior_90d": 0, "pct_change": 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)
+ 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,
+ },
+ ]
async with get_session(app.state.session_factory) as session:
- graph = await _graph(session, repo["id"])
- build = await _build(session, repo["id"])
-
- assert graph == {
- "cycle_clusters": 0,
- "files_in_cycles": 0,
- "largest_cycle": 0,
- "community_count": 0,
- }
- assert build == {
- "page_count": 0,
- "total_tokens": 0,
- "cost_usd": 0.0,
- "llm_operations": 0,
- }
+ 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["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
diff --git a/tests/unit/server/test_stats_superlatives.py b/tests/unit/server/test_stats_superlatives.py
index 4ce3afaeb..99ba17512 100644
--- a/tests/unit/server/test_stats_superlatives.py
+++ b/tests/unit/server/test_stats_superlatives.py
@@ -14,7 +14,7 @@ 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 _activity
+from repowise.server.routers.stats import _commit_pass
from tests.unit.server.conftest import create_test_repo
_DAY = 86400
@@ -59,7 +59,7 @@ async def test_biggest_commit_skips_initial_and_streak_counts_days(
async with get_session(app.state.session_factory) as session:
repo_row = await get_repository(session, repo["id"])
- activity = await _activity(session, repo["id"], repo_row)
+ activity = await _commit_pass(session, repo["id"], repo_row)
biggest = activity["biggest_commit"]
assert biggest is not None
@@ -67,6 +67,6 @@ async def test_biggest_commit_skips_initial_and_streak_counts_days(
assert biggest["lines_changed"] == 1000
assert biggest["files_changed"] == 12
- streak = activity["longest_streak"]
+ streak = activity["rhythm"]["longest_streak"]
assert streak is not None
assert streak["days"] == 4
diff --git a/tests/unit/test_git_commit_index.py b/tests/unit/test_git_commit_index.py
index c5bc6f592..68c1f6afc 100644
--- a/tests/unit/test_git_commit_index.py
+++ b/tests/unit/test_git_commit_index.py
@@ -3,11 +3,17 @@
from __future__ import annotations
import time
+from datetime import UTC, datetime
from unittest.mock import MagicMock
from repowise.core.ingestion.git_commit_index import load_commit_index
+def _iso_from_ts(ts: int) -> str:
+ """Render a git ``%cI`` value (strict ISO-8601 with a numeric offset)."""
+ return datetime.fromtimestamp(int(ts), UTC).isoformat()
+
+
def _build_log(commits: list[dict]) -> str:
"""Render an in-memory list of commit dicts into the raw `git log` format.
@@ -29,6 +35,8 @@ def _build_log(commits: list[dict]) -> str:
+ "\x1f"
+ str(c["ct"])
+ "\x1f"
+ + _iso_from_ts(c["ct"])
+ + "\x1f"
+ c.get("parents", "")
+ "\x1f"
+ c["subj"]
diff --git a/tests/unit/test_git_commit_rows.py b/tests/unit/test_git_commit_rows.py
index 9f1f0a535..6754b31ce 100644
--- a/tests/unit/test_git_commit_rows.py
+++ b/tests/unit/test_git_commit_rows.py
@@ -8,12 +8,18 @@ just-in-time change-risk, ordering, truncation).
from __future__ import annotations
import time
+from datetime import UTC, datetime
from unittest.mock import MagicMock
from repowise.core.ingestion.git_commit_index import load_commit_index
from repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows
+def _iso_from_ts(ts: int) -> str:
+ """Render a git ``%cI`` value (strict ISO-8601 with a numeric offset)."""
+ return datetime.fromtimestamp(int(ts), UTC).isoformat()
+
+
def _build_log(commits: list[dict]) -> str:
lines: list[str] = []
for c in commits:
@@ -31,6 +37,8 @@ def _build_log(commits: list[dict]) -> str:
+ "\x1f"
+ str(c["ct"])
+ "\x1f"
+ + _iso_from_ts(c["ct"])
+ + "\x1f"
+ c.get("parents", "")
+ "\x1f"
+ c["subj"]
@@ -87,12 +95,30 @@ def test_commit_sink_since_ts_drops_old_commits() -> None:
the incremental capture path's freshness guarantee."""
raw = _build_log(
[
- {"sha": "new", "an": "A", "ae": "a@x", "ct": 3000, "subj": "new",
- "files": [(1, 0, "src/a.py")]},
- {"sha": "mid", "an": "A", "ae": "a@x", "ct": 2000, "subj": "mid",
- "files": [(1, 0, "src/a.py")]},
- {"sha": "old", "an": "A", "ae": "a@x", "ct": 1000, "subj": "old",
- "files": [(1, 0, "src/a.py")]},
+ {
+ "sha": "new",
+ "an": "A",
+ "ae": "a@x",
+ "ct": 3000,
+ "subj": "new",
+ "files": [(1, 0, "src/a.py")],
+ },
+ {
+ "sha": "mid",
+ "an": "A",
+ "ae": "a@x",
+ "ct": 2000,
+ "subj": "mid",
+ "files": [(1, 0, "src/a.py")],
+ },
+ {
+ "sha": "old",
+ "an": "A",
+ "ae": "a@x",
+ "ct": 1000,
+ "subj": "old",
+ "files": [(1, 0, "src/a.py")],
+ },
]
)
repo = MagicMock()
diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.py
index 3df6b1b34..8a7c92ccd 100644
--- a/tests/unit/test_git_indexer.py
+++ b/tests/unit/test_git_indexer.py
@@ -46,6 +46,11 @@ def _make_diff(b_path: str, a_path: str | None = None):
# ---------------------------------------------------------------------------
+def _iso(ts: int) -> str:
+ """Git ``%cI`` for a unix timestamp — the offset field the parser expects."""
+ return datetime.fromtimestamp(int(ts), UTC).isoformat()
+
+
class TestSignificantCommitFilter:
"""Merges, bumps, chore, and bot commits are filtered out; normal commits pass.
@@ -391,7 +396,7 @@ class TestStableClassification:
for i in range(15):
ts = int((old_date - timedelta(days=i)).timestamp())
log_lines.append(
- f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old commit {i}\x1f"
+ f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f{_iso(ts)}\x1f\x1ffeat: old commit {i}\x1f"
)
mock_repo.git.log.return_value = "\n".join(log_lines)
@@ -420,7 +425,7 @@ class TestStableClassification:
for i, (name, email, when) in enumerate(specs):
ts = int(when.timestamp())
log_lines.append(
- f"\x00sha{i:04d}\x1f{name}\x1f{email}\x1f{name}\x1f{email}\x1f{ts}\x1f\x1ffeat: c{i}\x1f"
+ f"\x00sha{i:04d}\x1f{name}\x1f{email}\x1f{name}\x1f{email}\x1f{ts}\x1f{_iso(ts)}\x1f\x1ffeat: c{i}\x1f"
)
mock_repo.git.log.return_value = "\n".join(log_lines)
@@ -448,7 +453,7 @@ class TestGitWindowAnchor:
for i in range(15):
ts = int((old_date - timedelta(days=i)).timestamp())
log_lines.append(
- f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old {i}\x1f"
+ f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f{_iso(ts)}\x1f\x1ffeat: old {i}\x1f"
)
mock_repo.git.log.return_value = "\n".join(log_lines)
# HEAD tip = the newest of the (old) batch.
@@ -677,7 +682,9 @@ class TestNumstatParsing:
f"\x1f{e.get('email', '[email protected]')}"
f"\x1f{e.get('committer', e.get('author', 'Dev'))}"
f"\x1f{e.get('committer_email', e.get('email', '[email protected]'))}"
- f"\x1f{e['ts']}\x1f{e.get('parents', '')}"
+ f"\x1f{e['ts']}"
+ f"\x1f{datetime.fromtimestamp(int(e['ts']), UTC).isoformat()}"
+ f"\x1f{e.get('parents', '')}"
f"\x1f{e.get('subject', 'some commit')}"
f"\x1f{e.get('body', '')}"
)
@@ -765,7 +772,7 @@ class TestNumstatParsing:
# First record is malformed (only 3 fields), second is valid
raw = (
f"\x00badsha\x1fAlice\[email protected]\n" # only 3 fields
- f"\x00goodsha\x1fBob\[email protected]\x1fBob\[email protected]\x1f{recent_ts}\x1f\x1ffeat: valid commit\x1f\n"
+ f"\x00goodsha\x1fBob\[email protected]\x1fBob\[email protected]\x1f{recent_ts}\x1f{_iso(recent_ts)}\x1f\x1ffeat: valid commit\x1f\n"
f"10\t5\ttest.py\n"
)
mock_repo.git.log.return_value = raw
@@ -783,7 +790,7 @@ class TestNumstatParsing:
recent_ts = int((datetime.now(UTC) - timedelta(days=5)).timestamp())
raw = (
f"\x00sha1\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{recent_ts}"
- f"\x1fparent1 parent2\x1fMerge branch main\x1f\n"
+ f"\x1f{_iso(recent_ts)}\x1fparent1 parent2\x1fMerge branch main\x1f\n"
f"5\t2\tmerged.py\n"
)
mock_repo.git.log.return_value = raw
@@ -803,13 +810,13 @@ class TestNumstatParsing:
# Simulates --follow output: recent commit uses new name,
# older commit uses rename notation, oldest uses old name.
raw = (
- f"\x00sha1\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{recent_ts}\x1f\x1ffeat: update\x1f\n"
+ f"\x00sha1\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{recent_ts}\x1f{_iso(recent_ts)}\x1f\x1ffeat: update\x1f\n"
f"10\t3\tsrc/new_name.py\n"
f"\n"
- f"\x00sha2\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts}\x1f\x1frename file\x1f\n"
+ f"\x00sha2\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts}\x1f{_iso(old_ts)}\x1f\x1frename file\x1f\n"
f"0\t0\t{{src/old_name.py => src/new_name.py}}\n"
f"\n"
- f"\x00sha3\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts - 86400}\x1f\x1ffeat: old work\x1f\n"
+ f"\x00sha3\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts - 86400}\x1f{_iso(old_ts - 86400)}\x1f\x1ffeat: old work\x1f\n"
f"20\t5\tsrc/old_name.py\n"
)
mock_repo.git.log.return_value = raw