devstats: run.sh, HTML report, origin refs
Some checks are pending
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

devstats/run.sh installs python3/git via pacman when missing, refuses
python < 3.11, runs `compare` (capped when capped.sh exists), prints the
tables, writes ~/data/devstats/report.html (bar chart above the tables)
and opens it unless --no-open.

The local default branch is now logged together with its origin/
tracking ref (union, each SHA once), so the 16 "behind its upstream
tracking ref" warnings are gone without pulling any checkout.

Bug-class-check: devstats/tests/test_refs.py
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-27 13:32:40 +01:00
parent 13949dfd65
commit f370d313b5
11 changed files with 473 additions and 76 deletions

View File

@ -1,7 +1,7 @@
# utils # utils
Monorepo of shared gates and libraries (app_errors, dep_freshness, file_length, md_naming, Monorepo of shared gates and libraries (app_errors, dep_freshness, file_length, md_naming,
repo_contract, coverage_gaps, devstats, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording, repo_contract, coverage_gaps, devstats (`devstats/run.sh`: one-shot run + HTML report), crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording,
flutter_web_drive (headless Flutter-web E2E driver + MCP), ...). flutter_web_drive (headless Flutter-web E2E driver + MCP), ...).
`godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests. `godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests.
`kuhy_credit/` is the shared "Created by kuhy" credit, one implementation per stack (web, Flutter, `kuhy_credit/` is the shared "Created by kuhy" credit, one implementation per stack (web, Flutter,

View File

@ -4,9 +4,10 @@ Generated 2026-11-27 by `python -m devstats compare --write` (utils/devstats).
Article: https://veszelovszki.com/a/tpe/ (Cmdr, posted 2026-10-24). Article: https://veszelovszki.com/a/tpe/ (Cmdr, posted 2026-10-24).
- kuhy: every repo under ~/src, each piece of work once (worktrees, clones - kuhy: every repo under ~/src, each piece of work once (worktrees, clones
and rewritten copies folded in), commits on the local default branch and rewritten copies folded in), commits on the local default branch plus
(nothing read from origin/, nothing fetched), `--no-merges`, authored by its `origin/` tracking ref as last fetched (each SHA once; nothing fetched
kuhy's address (agent-made commits included). Committer date, local time. or pulled), `--no-merges`, authored by kuhy's address (agent-made commits
included). Committer date, local time.
- Net LoC = insertions − deletions of code paths. Docs/translations are left - Net LoC = insertions − deletions of code paths. Docs/translations are left
out of the headline like the article's; the "+docs" row adds them back. out of the headline like the article's; the "+docs" row adds them back.
- Cmdr's figures are per calendar day; the baseline (194) is per day with a - Cmdr's figures are per calendar day; the baseline (194) is per day with a
@ -17,34 +18,34 @@ Article: https://veszelovszki.com/a/tpe/ (Cmdr, posted 2026-10-24).
| window | row | kuhy net LoC/day | ins/day | del/day | Cmdr LoC/day | | window | row | kuhy net LoC/day | ins/day | del/day | Cmdr LoC/day |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| 30 d | raw | 24,639 | 34,238 | 9,599 | 12,000 | | 30 d | raw | 26,280 | 36,348 | 10,068 | 12,000 |
| 30 d | ×0.67 | 16,508 | 22,939 | 6,431 | 8,040 | | 30 d | ×0.67 | 17,608 | 24,353 | 6,745 | 8,040 |
| 30 d | +docs | 25,006 | 35,426 | 10,420 | — | | 30 d | +docs | 26,716 | 37,628 | 10,912 | — |
| 90 d | raw | 19,191 | 24,082 | 4,890 | 9,700 | | 90 d | raw | 19,733 | 24,779 | 5,046 | 9,700 |
| 90 d | ×0.67 | 12,858 | 16,135 | 3,277 | 6,499 | | 90 d | ×0.67 | 13,221 | 16,602 | 3,381 | 6,499 |
| 90 d | +docs | 19,598 | 24,920 | 5,322 | — | | 90 d | +docs | 20,163 | 25,647 | 5,484 | — |
| 300 d ≈ lifetime (10 mo) | raw | 7,568 | 11,044 | 3,475 | 4,500 | | 300 d ≈ lifetime (10 mo) | raw | 7,733 | 11,255 | 3,522 | 4,500 |
| 300 d ≈ lifetime (10 mo) | ×0.67 | 5,071 | 7,399 | 2,328 | 3,015 | | 300 d ≈ lifetime (10 mo) | ×0.67 | 5,181 | 7,541 | 2,360 | 3,015 |
| 300 d ≈ lifetime (10 mo) | +docs | 7,909 | 11,756 | 3,848 | — | | 300 d ≈ lifetime (10 mo) | +docs | 8,080 | 11,976 | 3,897 | — |
## Per active day vs the 194 LoC/workday baseline ## Per active day vs the 194 LoC/workday baseline
| window | active days | row | kuhy net LoC/active day | baseline LoC/workday | kuhy ÷ 194 | kuhy commits/active day | Cmdr commits/workday | | window | active days | row | kuhy net LoC/active day | baseline LoC/workday | kuhy ÷ 194 | kuhy commits/active day | Cmdr commits/workday |
|---|---|---|---|---|---|---|---| |---|---|---|---|---|---|---|---|
| 30 d | 24 | raw | 30,799 | 194 | 158.8× | 141 | 160 | | 30 d | 24 | raw | 32,851 | 194 | 169.3× | 148 | 160 |
| 30 d | 24 | ×0.67 | 20,635 | 194 | 106.4× | | | | 30 d | 24 | ×0.67 | 22,010 | 194 | 113.5× | | |
| 90 d | 77 | raw | 22,431 | 194 | 115.6× | 81 | — | | 90 d | 77 | raw | 23,065 | 194 | 118.9× | 83 | — |
| 90 d | 77 | ×0.67 | 15,029 | 194 | 77.5× | | | | 90 d | 77 | ×0.67 | 15,453 | 194 | 79.7× | | |
| 300 d ≈ lifetime (10 mo) | 181 | raw | 12,544 | 194 | 64.7× | 47 | 55 | | 300 d ≈ lifetime (10 mo) | 181 | raw | 12,816 | 194 | 66.1× | 48 | 55 |
| 300 d ≈ lifetime (10 mo) | 181 | ×0.67 | 8,405 | 194 | 43.3× | | | | 300 d ≈ lifetime (10 mo) | 181 | ×0.67 | 8,587 | 194 | 44.3× | | |
## Totals ## Totals
| window | net code LoC | insertions | deletions | net +docs | excluded share | commits | tags | tags/week | Cmdr releases/week | repos with ≥1 tag | | window | net code LoC | insertions | deletions | net +docs | excluded share | commits | tags | tags/week | Cmdr releases/week | repos with ≥1 tag |
|---|---|---|---|---|---|---|---|---|---|---| |---|---|---|---|---|---|---|---|---|---|---|
| 30 d | 739,179 | 1,027,137 | 287,958 | 750,168 | 23% | 3,391 | 726 | 169.4 | ~2 | 26 | | 30 d | 788,415 | 1,090,449 | 302,034 | 801,473 | 23% | 3,556 | 732 | 170.8 | ~2 | 26 |
| 90 d | 1,727,195 | 2,167,336 | 440,141 | 1,763,815 | 23% | 6,219 | 1227 | 95.4 | ~2 | 28 | | 90 d | 1,775,992 | 2,230,132 | 454,140 | 1,814,652 | 23% | 6,383 | 1233 | 95.9 | ~2 | 28 |
| 300 d ≈ lifetime (10 mo) | 2,270,522 | 3,313,061 | 1,042,539 | 2,372,569 | 32% | 8,442 | 1662 | 38.8 | ~2 | 31 | | 300 d ≈ lifetime (10 mo) | 2,319,758 | 3,376,373 | 1,056,615 | 2,423,874 | 32% | 8,607 | 1668 | 38.9 | ~2 | 31 |
## Exclude list (first match wins) ## Exclude list (first match wins)

View File

@ -1,4 +1,4 @@
"""`python -m devstats compare [--root DIR]... [--email ADDR]... [--by-repo [N]] [--write]`.""" """`python -m devstats compare [--root DIR]... [--email ADDR]... [--by-repo [N]] [--write] [--html PATH]`."""
from __future__ import annotations from __future__ import annotations
@ -14,6 +14,7 @@ from typing import TextIO
from devstats import article as A from devstats import article as A
from devstats.aggregate import DAY, RepoData, Window, dedup, window_totals from devstats.aggregate import DAY, RepoData, Window, dedup, window_totals
from devstats.discover import Repo, discover from devstats.discover import Repo, discover
from devstats.html import page
from devstats.numstat import read_commits from devstats.numstat import read_commits
from devstats.refs import list_refs, resolve, tag_times from devstats.refs import list_refs, resolve, tag_times
from devstats.render import by_repo, document, report from devstats.render import by_repo, document, report
@ -36,6 +37,8 @@ def build_parser() -> argparse.ArgumentParser:
cmp.add_argument("--by-repo", nargs="?", type=int, const=10, default=0, metavar="N", cmp.add_argument("--by-repo", nargs="?", type=int, const=10, default=0, metavar="N",
help="also print the top N repos (terminal only, default N=10)") help="also print the top N repos (terminal only, default N=10)")
cmp.add_argument("--write", action="store_true", help="rewrite devstats/DOCS-comparison.md") cmp.add_argument("--write", action="store_true", help="rewrite devstats/DOCS-comparison.md")
cmp.add_argument("--html", type=Path, metavar="PATH",
help="also write the report page (bar chart + tables) to PATH")
return parser return parser
@ -46,12 +49,8 @@ def _collect(repo: Repo, emails: frozenset[str], since: int) -> tuple[RepoData,
tags = tuple(tag_times(refs)) tags = tuple(tag_times(refs))
if default.branch is None: if default.branch is None:
return RepoData(repo.name, (), tags), [f"{repo.name}: no main/master/origin HEAD branch, skipped"] return RepoData(repo.name, (), tags), [f"{repo.name}: no main/master/origin HEAD branch, skipped"]
warnings = []
if default.behind_days is not None:
warnings.append(f"{repo.name} ({default.branch}): default ref is {default.behind_days} days "
"behind its upstream tracking ref")
commits = tuple(c for c in read_commits(repo.path, default.log_refs, since) if c.email in emails) commits = tuple(c for c in read_commits(repo.path, default.log_refs, since) if c.email in emails)
return RepoData(repo.name, commits, tags), warnings return RepoData(repo.name, commits, tags), []
def main(argv: Sequence[str] | None = None, *, now: float | None = None, out: TextIO = sys.stdout, def main(argv: Sequence[str] | None = None, *, now: float | None = None, out: TextIO = sys.stdout,
@ -76,7 +75,12 @@ def main(argv: Sequence[str] | None = None, *, now: float | None = None, out: Te
if args.by_repo: if args.by_repo:
per_repo = [(d.name, [window_totals([d], days, now) for days in A.WINDOWS]) for d in data] per_repo = [(d.name, [window_totals([d], days, now) for days in A.WINDOWS]) for d in data]
print(by_repo(per_repo, args.by_repo), file=out) print(by_repo(per_repo, args.by_repo), file=out)
date = datetime.fromtimestamp(now).date().isoformat()
if args.write: if args.write:
doc_path.write_text(document(windows, datetime.fromtimestamp(now).date().isoformat())) doc_path.write_text(document(windows, date))
print(f"wrote {doc_path}", file=out) print(f"wrote {doc_path}", file=out)
if args.html:
args.html.parent.mkdir(parents=True, exist_ok=True)
args.html.write_text(page(windows, date))
print(f"report: {args.html}", file=out)
return 0 return 0

90
devstats/html.py Normal file
View File

@ -0,0 +1,90 @@
"""Static HTML report: a kuhy-vs-Cmdr bar chart above the three terminal tables.
One self-contained file (inline CSS, no script, no network), so it stays
readable after the run ends and opens from `file://`. Table cells come from
`render.sections`, the same builders the terminal prints, so the numbers match.
Colours are the unified-design-system tokens: kuhy `cat-3`, Cmdr `cat-2` (the
pair that passes the dataviz CVD check; `cat-1`/`cat-2` fall to dE 6.9 protan).
"""
from __future__ import annotations
from collections.abc import Sequence
from html import escape
from devstats import article as A
from devstats.aggregate import Window
from devstats.render import num, sections
KUHY, CMDR = "#C85A32", "#398FC0"
BAR_SHARE = 82 # % of the track the longest bar fills; the rest holds its value label
CSS = """
:root{--bg:#F6F4F3;--card:#FCFBFB;--line:#E0DAD7;--text:#211D1B;--muted:#70625B;color-scheme:light dark}
@media (prefers-color-scheme:dark){:root{--bg:#211D1B;--card:#2B2624;--line:#463E3A;--text:#ECEAE9;
--muted:#AAA09A}}
html{font-size:16px}@media (min-width:2400px){html{font-size:22px}}
body{margin:0;background:var(--bg);color:var(--text);font:1rem/1.5 system-ui,sans-serif}
main{max-width:100rem;margin:0 auto;padding:1.5rem 1rem 3rem;box-sizing:border-box}
h2{font-size:1.125rem;font-weight:600;margin:2rem 0 .75rem}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:1rem}
.scroll{overflow-x:auto}
.legend{display:flex;gap:1.5rem;margin:0 0 .75rem}.legend span{display:flex;align-items:center;gap:.4rem}
.sw{width:.75rem;height:.75rem;border-radius:2px}
.chart{display:grid;grid-template-columns:max-content 1fr;gap:1rem .75rem;align-items:center}
.lab{color:var(--muted);text-align:right;font-size:.875rem}
.pair{display:grid;gap:2px;border-left:1px solid var(--line)}
.track{display:flex;align-items:center;gap:.4rem;font-size:.875rem;font-variant-numeric:tabular-nums}
.bar{height:1rem;border-radius:0 4px 4px 0}
table{border-collapse:collapse;font-variant-numeric:tabular-nums;white-space:nowrap}
th,td{padding:.375rem .75rem;border-bottom:1px solid var(--line);text-align:right}
th{color:var(--muted);font-weight:600}th:nth-child(-n+2),td:nth-child(-n+2){text-align:left}
tr:last-child td{border-bottom:0}
"""
def _bars(windows: Sequence[Window]) -> list[tuple[str, float, float]]:
"""(row label, kuhy net LoC/day, Cmdr LoC/day) for each window, raw then x0.67."""
out = []
for w in windows:
label = A.LABELS[w.days].split(" ≈")[0]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
out.append((f"{label} · {row}", w.net * k / w.days, A.CMDR_LOC_PER_DAY[w.days] * k))
return out
def _track(who: str, label: str, value: float, peak: float, colour: str) -> str:
"""One bar (none when value <= 0) plus its value, with a hover tooltip."""
share = max(value, 0) / peak * BAR_SHARE
bar = (f'<i class="bar" style="width:{share:.1f}%;background:{colour}" '
f'title="{escape(f"{who} {label}: {num(value)}")}"></i>') if share > 0 else ""
return f'<div class="track">{bar}<span>{num(value)}</span></div>'
def chart(windows: Sequence[Window]) -> str:
"""Horizontal paired bars, kuhy above Cmdr, LoC per calendar day; HTML so text scales."""
bars = _bars(windows)
peak = max([1.0, *(max(k, c) for _, k, c in bars)])
legend = "".join(f'<span><i class="sw" style="background:{c}"></i>{who}</span>'
for who, c in (("kuhy", KUHY), ("Cmdr", CMDR)))
rows = "".join(f'<div class="lab">{escape(label)}</div><div class="pair">'
f"{_track('kuhy', label, k, peak, KUHY)}{_track('Cmdr', label, c, peak, CMDR)}</div>"
for label, k, c in bars)
return (f'<div class="legend">{legend}</div>'
f'<div class="chart" role="img" aria-label="kuhy vs Cmdr LoC per day">{rows}</div>')
def _html_table(head: Sequence[str], rows: Sequence[Sequence[str]]) -> str:
cells = "".join(f"<th>{escape(h)}</th>" for h in head)
body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in r) + "</tr>" for r in rows)
return f'<div class="card scroll"><table><thead><tr>{cells}</tr></thead><tbody>{body}</tbody></table></div>'
def page(windows: Sequence[Window], date: str) -> str:
"""The whole report page."""
tables = "".join(f"<h2>{escape(title)}</h2>{_html_table(head, rows)}"
for title, (head, rows) in sections(windows))
return (f'<!doctype html>\n<html lang="en"><head><meta charset="utf-8">'
f'<meta name="viewport" content="width=device-width,initial-scale=1">'
f"<title>devstats {escape(date)}</title><style>{CSS}</style></head><body><main>"
f'<div class="card">{chart(windows)}</div>{tables}</main></body></html>\n')

View File

@ -1,9 +1,12 @@
"""Default-branch resolution from refs on disk (never fetches). """Default-branch resolution from refs on disk (never fetches, never pulls).
Only the LOCAL default branch is counted (kuhy's spec: "read local refs The local default branch is logged together with its `origin/` tracking ref
only"). origin/HEAD only names the branch. When the `origin/` tracking ref is when the two tips differ. Work landed with `git push origin HEAD:main` from a
newer, the caller warns: work landed with `git push origin HEAD:main` from a worktree sits only on the tracking ref until the checkout is pulled, and kuhy's
worktree is then missing from the count until the checkout is pulled. live checkouts (tutor, todo) must not be pulled by a stats run. `git log` walks
the union, so each SHA counts once and a diverged repo counts both sides.
origin/HEAD only names the branch; a branch that exists only on origin/ is not
counted (no local checkout of that work).
""" """
from __future__ import annotations from __future__ import annotations
@ -29,11 +32,10 @@ class Ref:
@dataclass(frozen=True) @dataclass(frozen=True)
class DefaultRefs: class DefaultRefs:
"""The default branch name, the local ref to log, and how stale it is.""" """The default branch name and the refs whose union is logged."""
branch: str | None branch: str | None
log_refs: tuple[str, ...] log_refs: tuple[str, ...]
behind_days: float | None
def list_refs(repo: Path) -> dict[str, Ref]: def list_refs(repo: Path) -> dict[str, Ref]:
@ -59,8 +61,6 @@ def resolve(refs: dict[str, Ref]) -> DefaultRefs:
for branch in (*candidates, "main", "master"): for branch in (*candidates, "main", "master"):
local, remote = refs.get("refs/heads/" + branch), refs.get(_ORIGIN + branch) local, remote = refs.get("refs/heads/" + branch), refs.get(_ORIGIN + branch)
if local: if local:
behind = None tracking = (_ORIGIN + branch,) if remote and remote.sha != local.sha else ()
if remote and local.sha != remote.sha and remote.ts > local.ts: return DefaultRefs(branch, ("refs/heads/" + branch, *tracking))
behind = round((remote.ts - local.ts) / 86_400, 1) return DefaultRefs(None, ())
return DefaultRefs(branch, ("refs/heads/" + branch,), behind)
return DefaultRefs(None, (), None)

View File

@ -1,4 +1,9 @@
"""Markdown tables: kuhy beside the article, plus the optional per-repo breakdown.""" """Tables of kuhy beside the article, plus the optional per-repo breakdown.
The `*_rows` builders return (head, rows) of plain cell strings; the markdown
here and the HTML page in `devstats.html` both render those, so the page and
the terminal always show the same numbers.
"""
from __future__ import annotations from __future__ import annotations
@ -9,9 +14,11 @@ from devstats.aggregate import Window
from devstats.excludes import RULES from devstats.excludes import RULES
DASH = "—" DASH = "—"
Table = tuple[tuple[str, ...], list[list[str]]]
def _n(x: float) -> str: def num(x: float) -> str:
"""Whole number with thousands separators."""
return f"{x:,.0f}" return f"{x:,.0f}"
@ -21,21 +28,21 @@ def _table(head: Sequence[str], rows: Sequence[Sequence[str]]) -> list[str]:
return out return out
def per_calendar_day(windows: Sequence[Window]) -> list[str]: def per_calendar_day(windows: Sequence[Window]) -> Table:
"""kuhy raw / ×0.67 / +docs LoC per calendar day beside Cmdr raw / ×0.67.""" """kuhy raw / ×0.67 / +docs LoC per calendar day beside Cmdr raw / ×0.67."""
rows = [] rows = []
for w in windows: for w in windows:
d, cmdr, label = w.days, A.CMDR_LOC_PER_DAY[w.days], A.LABELS[w.days] d, cmdr, label = w.days, A.CMDR_LOC_PER_DAY[w.days], A.LABELS[w.days]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)): for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
rows.append([label, row, _n(w.net * k / d), _n(w.code_ins * k / d), rows.append([label, row, num(w.net * k / d), num(w.code_ins * k / d),
_n(w.code_del * k / d), _n(cmdr * k)]) num(w.code_del * k / d), num(cmdr * k)])
rows.append([label, "+docs", _n(w.net_with_docs / d), _n((w.code_ins + w.docs_ins) / d), rows.append([label, "+docs", num(w.net_with_docs / d), num((w.code_ins + w.docs_ins) / d),
_n((w.code_del + w.docs_del) / d), DASH]) num((w.code_del + w.docs_del) / d), DASH])
head = ("window", "row", "kuhy net LoC/day", "ins/day", "del/day", "Cmdr LoC/day") head = ("window", "row", "kuhy net LoC/day", "ins/day", "del/day", "Cmdr LoC/day")
return _table(head, rows) return head, rows
def per_active_day(windows: Sequence[Window]) -> list[str]: def per_active_day(windows: Sequence[Window]) -> Table:
"""kuhy per active day beside the 194 baseline, plus commits beside Cmdr's.""" """kuhy per active day beside the 194 baseline, plus commits beside Cmdr's."""
rows = [] rows = []
base = A.BASELINE_LOC_PER_WORKDAY base = A.BASELINE_LOC_PER_WORKDAY
@ -44,40 +51,46 @@ def per_active_day(windows: Sequence[Window]) -> list[str]:
cmdr_commits = A.CMDR_COMMITS_PER_WORKDAY[w.days] cmdr_commits = A.CMDR_COMMITS_PER_WORKDAY[w.days]
for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)): for row, k in (("raw", 1.0), ("×0.67", A.AI_DISCOUNT)):
per = w.net * k / active per = w.net * k / active
commits = [_n(w.commits / active), DASH if cmdr_commits is None else _n(cmdr_commits)] commits = [num(w.commits / active), DASH if cmdr_commits is None else num(cmdr_commits)]
rows.append([A.LABELS[w.days], str(w.active_days), row, _n(per), str(base), rows.append([A.LABELS[w.days], str(w.active_days), row, num(per), str(base),
f"{per / base:.1f}×", *(commits if row == "raw" else ["", ""])]) f"{per / base:.1f}×", *(commits if row == "raw" else ["", ""])])
head = ("window", "active days", "row", "kuhy net LoC/active day", "baseline LoC/workday", head = ("window", "active days", "row", "kuhy net LoC/active day", "baseline LoC/workday",
"kuhy ÷ 194", "kuhy commits/active day", "Cmdr commits/workday") "kuhy ÷ 194", "kuhy commits/active day", "Cmdr commits/workday")
return _table(head, rows) return head, rows
def totals(windows: Sequence[Window]) -> list[str]: def totals(windows: Sequence[Window]) -> Table:
"""Raw totals, the share the exclude list removed, and tags.""" """Raw totals, the share the exclude list removed, and tags."""
rows = [ rows = [
[A.LABELS[w.days], _n(w.net), _n(w.code_ins), _n(w.code_del), _n(w.net_with_docs), [A.LABELS[w.days], num(w.net), num(w.code_ins), num(w.code_del), num(w.net_with_docs),
f"{w.excluded_share:.0%}", _n(w.commits), str(w.tags), f"{w.tags / (w.days / 7):.1f}", f"{w.excluded_share:.0%}", num(w.commits), str(w.tags), f"{w.tags / (w.days / 7):.1f}",
f"~{A.RELEASES_PER_WEEK}", str(w.repos_with_tags)] f"~{A.RELEASES_PER_WEEK}", str(w.repos_with_tags)]
for w in windows for w in windows
] ]
head = ("window", "net code LoC", "insertions", "deletions", "net +docs", "excluded share", head = ("window", "net code LoC", "insertions", "deletions", "net +docs", "excluded share",
"commits", "tags", "tags/week", "Cmdr releases/week", "repos with ≥1 tag") "commits", "tags", "tags/week", "Cmdr releases/week", "repos with ≥1 tag")
return _table(head, rows) return head, rows
def sections(windows: Sequence[Window]) -> list[tuple[str, Table]]:
"""(title, table) of each comparison table, in print order."""
return [("LoC per calendar day vs Cmdr", per_calendar_day(windows)),
("Per active day vs the 194 LoC/workday baseline", per_active_day(windows)),
("Totals", totals(windows))]
def report(windows: Sequence[Window]) -> str: def report(windows: Sequence[Window]) -> str:
"""The comparison tables, as printed and as written to DOCS-comparison.md.""" """The comparison tables, as printed and as written to DOCS-comparison.md."""
parts = ["## LoC per calendar day vs Cmdr", "", *per_calendar_day(windows), "", blocks = ["\n".join([f"## {title}", "", *_table(head, rows)])
"## Per active day vs the 194 LoC/workday baseline", "", *per_active_day(windows), "", for title, (head, rows) in sections(windows)]
"## Totals", "", *totals(windows)] return "\n\n".join(blocks) + "\n"
return "\n".join(parts) + "\n"
def by_repo(per_repo: Sequence[tuple[str, Sequence[Window]]], top: int) -> str: def by_repo(per_repo: Sequence[tuple[str, Sequence[Window]]], top: int) -> str:
"""Top-`top` repos by 300-day net code LoC (terminal only, never written).""" """Top-`top` repos by 300-day net code LoC (terminal only, never written)."""
ranked = sorted(per_repo, key=lambda item: -item[1][-1].net)[:top] ranked = sorted(per_repo, key=lambda item: -item[1][-1].net)[:top]
head = ("repo", *(f"net {A.LABELS[d].split(' ≈')[0]}" for d in A.WINDOWS), "commits 300 d") head = ("repo", *(f"net {A.LABELS[d].split(' ≈')[0]}" for d in A.WINDOWS), "commits 300 d")
rows = [[name, *(_n(w.net) for w in ws), _n(ws[-1].commits)] for name, ws in ranked] rows = [[name, *(num(w.net) for w in ws), num(ws[-1].commits)] for name, ws in ranked]
return "\n".join(["## Top repos", "", *_table(head, rows)]) + "\n" return "\n".join(["## Top repos", "", *_table(head, rows)]) + "\n"
@ -98,9 +111,10 @@ Generated {date} by `python -m devstats compare --write` (utils/devstats).
Article: {A.URL} (Cmdr, posted 2026-10-24). Article: {A.URL} (Cmdr, posted 2026-10-24).
- kuhy: every repo under ~/src, each piece of work once (worktrees, clones - kuhy: every repo under ~/src, each piece of work once (worktrees, clones
and rewritten copies folded in), commits on the local default branch and rewritten copies folded in), commits on the local default branch plus
(nothing read from origin/, nothing fetched), `--no-merges`, authored by its `origin/` tracking ref as last fetched (each SHA once; nothing fetched
kuhy's address (agent-made commits included). Committer date, local time. or pulled), `--no-merges`, authored by kuhy's address (agent-made commits
included). Committer date, local time.
- Net LoC = insertions − deletions of code paths. Docs/translations are left - Net LoC = insertions − deletions of code paths. Docs/translations are left
out of the headline like the article's; the "+docs" row adds them back. out of the headline like the article's; the "+docs" row adds them back.
- Cmdr's figures are per calendar day; the baseline (194) is per day with a - Cmdr's figures are per calendar day; the baseline (194) is per day with a

92
devstats/run.sh Executable file
View File

@ -0,0 +1,92 @@
#!/bin/bash
# ============================================================================
# One-shot devstats run: installs python3/git when missing (pacman), runs
# `python -m devstats compare` over ~/src (or the given --root), prints the
# tables, writes ~/data/devstats/report.html and opens it unless --no-open.
# Works from any cwd: the repo root is found from this script's own path.
# Usage: run.sh [--no-open] [compare flags...] (run.sh --help lists them)
# Exit: devstats' own code (2 = no repos), 3 = setup failed.
# ============================================================================
set -euo pipefail
SELF="$(realpath "${BASH_SOURCE[0]}")"
readonly SELF
REPO_ROOT="$(dirname "$(dirname "$SELF")")"
readonly REPO_ROOT
readonly REPORT="$HOME/data/devstats/report.html"
readonly CAPPED="$HOME/.claude/scripts/capped.sh"
readonly EXIT_SETUP=3
die() {
echo "devstats: $*" >&2
exit "$EXIT_SETUP"
}
# Install every missing tool first, then re-check, so one run installs both.
ensure_tools() {
local pair tool pkg
for pair in python3:python git:git; do
tool="${pair%%:*}" pkg="${pair#*:}"
if ! command -v "$tool" >/dev/null; then
sudo pacman -S --needed "$pkg" || die "pacman could not install $pkg"
fi
done
for tool in python3 git; do
command -v "$tool" >/dev/null || die "$tool still missing after install"
done
}
# devstats needs datetime.UTC (3.11+); it has no third-party dependencies.
check_python() {
local ver major minor
ver="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
major="${ver%%.*}" minor="${ver#*.}"
if ((major < 3 || (major == 3 && minor < 11))); then
die "python3 >= 3.11 required, found $ver"
fi
}
# Capped (2 GiB, 10 % CPU, idle IO) when kuhy's capped.sh exists, plain otherwise.
run_devstats() {
local cmd=(env "PYTHONPATH=$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -m devstats compare "$@")
if [[ -x "$CAPPED" ]]; then
"$CAPPED" "${cmd[@]}"
else
"${cmd[@]}"
fi
}
usage() {
echo "usage: run.sh [--no-open] [compare flags...]"
echo " --no-open write $REPORT but do not open it"
echo
run_devstats --help
}
main() {
local open=1 help=0 args=() arg rc=0
for arg in "$@"; do
case "$arg" in
--no-open) open=0 ;;
-h | --help) help=1 ;;
*) args+=("$arg") ;;
esac
done
ensure_tools
check_python
if ((help)); then
usage
return 0
fi
if ((open)) && ! command -v xdg-open >/dev/null; then
die "xdg-open missing: install xdg-utils or pass --no-open"
fi
run_devstats "${args[@]}" --html "$REPORT" || rc=$?
if ((rc == 0 && open)); then
setsid -f xdg-open "$REPORT" >/dev/null 2>&1
fi
return "$rc"
}
main "$@"; exit $?

View File

@ -14,13 +14,13 @@ from .conftest import DAY, NOW, lines, run
@pytest.fixture @pytest.fixture
def src(make_repo, tmp_path: Path) -> Path: def src(make_repo, tmp_path: Path) -> Path:
"""signal-bot + a worktree, a master-only repo, a collaborator, a stale ref.""" """signal-bot + a worktree, a master-only repo, a collaborator, a local main behind origin."""
bot = make_repo("signal-bot") bot = make_repo("signal-bot")
bot.commit({"bot.py": lines(100), "README.md": lines(40), "pnpm-lock.yaml": lines(500)}, NOW - DAY) bot.commit({"bot.py": lines(100), "README.md": lines(40), "pnpm-lock.yaml": lines(500)}, NOW - DAY)
bot.commit({"bot.py": None}, NOW - 50 * DAY + 1) # dates out of order on purpose: kept by --since bot.commit({"bot.py": None}, NOW - 50 * DAY + 1) # dates out of order on purpose: kept by --since
bot.commit({"x.py": lines(10)}, NOW - 2 * DAY, email="ppolgon@gmail.com") bot.commit({"x.py": lines(10)}, NOW - 2 * DAY, email="ppolgon@gmail.com")
bot.tag("v1", NOW - DAY, annotated=True) bot.tag("v1", NOW - DAY, annotated=True)
bot.commit({"pushed.py": lines(3)}, NOW - DAY) # only origin has it: not counted (local refs only) bot.commit({"pushed.py": lines(3)}, NOW - DAY + 60) # only origin/main has it: counted all the same
run(bot.path, "update-ref", "refs/remotes/origin/main", "HEAD") run(bot.path, "update-ref", "refs/remotes/origin/main", "HEAD")
run(bot.path, "update-ref", "refs/heads/main", "HEAD~1") # local main behind origin run(bot.path, "update-ref", "refs/heads/main", "HEAD~1") # local main behind origin
run(bot.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt") run(bot.path, "worktree", "add", "-q", str(tmp_path / "src" / "sb-wt-a"), "-b", "wt")
@ -44,7 +44,7 @@ def test_compare_prints_all_windows_and_article_figures(src: Path, tmp_path: Pat
for needle in ("30 d", "90 d", "300 d ≈ lifetime (10 mo)", "12,000", "9,700", "4,500", "×0.67", "194", for needle in ("30 d", "90 d", "300 d ≈ lifetime (10 mo)", "12,000", "9,700", "4,500", "×0.67", "194",
"160", "55", "+docs", "excluded", "tags/week", "repos with ≥1 tag", "÷ 194"): "160", "55", "+docs", "excluded", "tags/week", "repos with ≥1 tag", "÷ 194"):
assert needle in out, needle assert needle in out, needle
assert "signal-bot (main): default ref is 1.0 days behind its upstream tracking ref" in err assert "signal-bot" not in err # no "behind its upstream" warning any more
assert "nobranch: no main/master/origin HEAD branch, skipped" in err assert "nobranch: no main/master/origin HEAD branch, skipped" in err
assert not doc.exists() assert not doc.exists()
assert "signal-bot" not in out assert "signal-bot" not in out
@ -63,6 +63,13 @@ def test_by_repo_folds_worktrees_and_write_has_no_repo_names(src: Path, tmp_path
assert f"| {name}" not in text assert f"| {name}" not in text
def test_origin_only_commit_is_counted_once(src: Path, tmp_path: Path) -> None:
rc, out, _ = compare("--root", str(src), "--by-repo", doc=tmp_path / "d.md")
assert rc == 0
# bot.py, its deletion and pushed.py (origin-only); the worktree adds nothing
assert "| signal-bot | 103 | 3 | 3 | 3 |" in out
def test_a_local_clone_changes_nothing_but_the_repo_list(src: Path, tmp_path: Path) -> None: def test_a_local_clone_changes_nothing_but_the_repo_list(src: Path, tmp_path: Path) -> None:
doc = tmp_path / "d.md" doc = tmp_path / "d.md"
_, before, _ = compare("--root", str(src), doc=doc) _, before, _ = compare("--root", str(src), doc=doc)
@ -107,3 +114,11 @@ def test_module_entry_point(monkeypatch: pytest.MonkeyPatch, capsys: pytest.Capt
runpy.run_module("devstats", run_name="__main__") runpy.run_module("devstats", run_name="__main__")
assert exc.value.code == 0 assert exc.value.code == 0
assert "--by-repo" in capsys.readouterr().out assert "--by-repo" in capsys.readouterr().out
def test_html_flag_writes_the_page_and_prints_its_path_last(src: Path, tmp_path: Path) -> None:
target = tmp_path / "deep" / "report.html"
rc, out, _ = compare("--root", str(src), "--html", str(target), doc=tmp_path / "d.md")
assert rc == 0
assert out.rstrip().endswith(f"report: {target}")
assert target.read_text().startswith("<!doctype html>")

View File

@ -0,0 +1,52 @@
"""The static report page: chart above tables, cells identical to the terminal's."""
from __future__ import annotations
import re
from html import unescape
from devstats.aggregate import Window
from devstats.html import CMDR, KUHY, chart, page
from devstats.render import report
def window(days: int, net: int) -> Window:
return Window(days=days, code_ins=max(net, 0), code_del=max(-net, 0), docs_ins=5, docs_del=1,
excluded_lines=10, all_lines=100, active_days=3, commits=7, tags=2, repos_with_tags=1)
WINDOWS = [window(30, 3000), window(90, 900), window(300, 30)]
def md_cells(text: str) -> list[str]:
"""Body cells of every markdown table (header and separator rows skipped)."""
cells = []
for block in text.split("## ")[1:]:
rows = [ln for ln in block.splitlines() if ln.startswith("|")][2:]
cells += [c.strip() for r in rows for c in r.strip("|").split("|")]
return cells
def test_page_cells_match_the_terminal_tables() -> None:
html = page(WINDOWS, "2026-11-27")
tds = [unescape(c) for c in re.findall(r"<td>(.*?)</td>", html)]
assert tds == md_cells(report(WINDOWS))
assert "<title>devstats 2026-11-27</title>" in html
def test_chart_comes_before_the_tables_and_names_both_series() -> None:
html = page(WINDOWS, "d")
assert html.index('class="chart"') < html.index("<table")
assert "</i>kuhy</span>" in html and "</i>Cmdr</span>" in html
assert html.count(f'background:{KUHY}" title=') == 6
assert html.count(f'background:{CMDR}" title=') == 6
assert 'title="kuhy 30 d · raw: 100"' in html
assert 'title="Cmdr 300 d · ×0.67: 3,015"' in html
assert 'style="width:82.0%;background:#398FC0" title="Cmdr 30 d · raw: 12,000"' in html
def test_zero_or_negative_net_draws_no_bar_but_keeps_the_value() -> None:
html = chart([window(30, 0), window(90, -900), window(300, 0)])
assert f"background:{KUHY}\" title=" not in html
assert "<span>-10</span>" in html # -900 / 90 d, printed as is
assert html.count(f'background:{CMDR}" title=') == 6

View File

@ -1,4 +1,4 @@
"""Default-branch resolution and the stale-local-ref warning.""" """Default-branch resolution: the local branch plus its origin/ tracking ref."""
from __future__ import annotations from __future__ import annotations
@ -20,15 +20,13 @@ def test_origin_head_names_the_branch_and_both_tips_are_logged() -> None:
} }
got = resolve(refs) got = resolve(refs)
assert got.branch == "trunk" assert got.branch == "trunk"
assert got.log_refs == ("refs/heads/trunk",) assert got.log_refs == ("refs/heads/trunk", "refs/remotes/origin/trunk")
assert got.behind_days == 2.5
def test_falls_back_to_main_then_master_without_origin() -> None: def test_falls_back_to_main_then_master_without_origin() -> None:
assert resolve({"refs/heads/main": ref(1)}).log_refs == ("refs/heads/main",) assert resolve({"refs/heads/main": ref(1)}).log_refs == ("refs/heads/main",)
got = resolve({"refs/heads/master": ref(1), "refs/heads/dev": ref(2)}) got = resolve({"refs/heads/master": ref(1), "refs/heads/dev": ref(2)})
assert got.branch == "master" assert (got.branch, got.log_refs) == ("master", ("refs/heads/master",))
assert got.behind_days is None
def test_origin_only_branch_is_not_counted() -> None: def test_origin_only_branch_is_not_counted() -> None:
@ -43,11 +41,11 @@ def test_no_default_branch() -> None:
assert got.log_refs == () assert got.log_refs == ()
def test_local_ahead_or_equal_is_not_behind() -> None: def test_equal_tips_log_once_any_difference_logs_both() -> None:
same = {"refs/heads/main": ref(5, sha="a"), "refs/remotes/origin/main": ref(5, sha="a")} same = {"refs/heads/main": ref(5, sha="a"), "refs/remotes/origin/main": ref(5, sha="a")}
ahead = {"refs/heads/main": ref(9, sha="a"), "refs/remotes/origin/main": ref(5, sha="b")} ahead = {"refs/heads/main": ref(9, sha="a"), "refs/remotes/origin/main": ref(5, sha="b")}
assert resolve(same).behind_days is None assert resolve(same).log_refs == ("refs/heads/main",)
assert resolve(ahead).behind_days is None assert resolve(ahead).log_refs == ("refs/heads/main", "refs/remotes/origin/main")
def test_list_refs_reads_branches_remotes_and_tags(make_repo) -> None: def test_list_refs_reads_branches_remotes_and_tags(make_repo) -> None:

View File

@ -0,0 +1,131 @@
"""`devstats/run.sh`: tool setup, the compare run, the HTML report and its opener.
The autouse `isolated_git` fixture points HOME at a scratch dir, so the report
lands under it, `~/.claude/scripts/capped.sh` is absent (uncapped run) and the
real ~/data/devstats is never touched. Every run passes `--no-open` or puts a
recording `xdg-open` first on PATH, so nothing opens on kuhy's display.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import time
from pathlib import Path
import pytest
from .conftest import DAY, lines
RUN_SH = Path(__file__).resolve().parents[1] / "run.sh"
# What run.sh needs besides python3 and git, for the stripped-PATH cases.
BASE_TOOLS = ("bash", "realpath", "dirname", "mkdir", "cat", "setsid", "env")
def run_sh(*args: str, path: str | None = None) -> subprocess.CompletedProcess[str]:
"""Run run.sh from an unrelated cwd, optionally with a replaced PATH."""
env = dict(os.environ)
if path is not None:
env["PATH"] = path
return subprocess.run([str(RUN_SH), *args], cwd="/", env=env, capture_output=True, text=True,
check=False, timeout=50)
def report_path() -> Path:
return Path(os.environ["HOME"]) / "data" / "devstats" / "report.html"
@pytest.fixture
def src(make_repo, tmp_path: Path) -> Path:
"""One repo with a fresh commit by kuhy's address."""
repo = make_repo("app")
repo.commit({"app.py": lines(30)}, int(time.time()) - DAY)
return tmp_path / "src"
def test_run_prints_tables_writes_report_and_no_warnings(src: Path) -> None:
proc = run_sh("--no-open", "--root", str(src))
assert proc.returncode == 0, proc.stderr
assert "## LoC per calendar day vs Cmdr" in proc.stdout
assert "| 30 d | raw | 1 |" in proc.stdout # 30 lines / 30 days
assert proc.stdout.rstrip().endswith(f"report: {report_path()}")
assert "warning:" not in proc.stderr
page = report_path().read_text()
assert page.startswith("<!doctype html>")
assert 'class="chart"' in page
def test_empty_root_exits_2_and_writes_no_report(tmp_path: Path) -> None:
empty = tmp_path / "empty"
empty.mkdir()
proc = run_sh("--no-open", "--root", str(empty))
assert proc.returncode == 2
assert f"devstats: no git repos under {empty}" in proc.stderr
assert not report_path().exists()
def test_help_lists_own_and_compare_flags() -> None:
proc = run_sh("--help")
assert proc.returncode == 0
for flag in ("--no-open", "--root", "--email", "--by-repo", "--write"):
assert flag in proc.stdout, flag
def _recorder(bindir: Path, name: str, log: Path) -> None:
"""A fake `name` that appends its argv to `log` and exits 0."""
exe = bindir / name
exe.write_text(f'#!/bin/bash\necho "$*" >> "{log}"\n')
exe.chmod(0o755)
def _wait_for(path: Path) -> str:
"""The detached opener writes its log a moment after run.sh exits."""
deadline = time.monotonic() + 5
while not path.exists() and time.monotonic() < deadline:
time.sleep(0.05)
return path.read_text() if path.exists() else ""
def test_opens_report_only_without_no_open(src: Path, tmp_path: Path) -> None:
bindir, log = tmp_path / "bin", tmp_path / "xdg-open.log"
bindir.mkdir()
_recorder(bindir, "xdg-open", log)
path = f"{bindir}:{os.environ['PATH']}"
assert run_sh("--no-open", "--root", str(src), path=path).returncode == 0
assert run_sh("--root", str(tmp_path / "nothing"), path=path).returncode == 2
time.sleep(0.3)
assert not log.exists()
assert run_sh("--root", str(src), path=path).returncode == 0
assert _wait_for(log) == f"{report_path()}\n"
def _stripped_path(tmp_path: Path) -> Path:
"""A PATH dir holding only BASE_TOOLS: no python3, no git."""
bindir = tmp_path / "shim"
bindir.mkdir()
for tool in BASE_TOOLS:
found = shutil.which(tool)
assert found, tool
(bindir / tool).symlink_to(found)
return bindir
def test_missing_tools_are_installed_with_pacman(tmp_path: Path) -> None:
bindir, log = _stripped_path(tmp_path), tmp_path / "sudo.log"
_recorder(bindir, "sudo", log)
proc = run_sh("--no-open", path=str(bindir))
assert log.read_text().splitlines() == ["pacman -S --needed python", "pacman -S --needed git"]
assert proc.returncode == 3
assert "devstats: python3 still missing after install" in proc.stderr
def test_old_python_is_refused(tmp_path: Path) -> None:
bindir = _stripped_path(tmp_path)
(bindir / "git").symlink_to(shutil.which("git") or "git")
fake = bindir / "python3"
fake.write_text("#!/bin/bash\necho 3.10\n")
fake.chmod(0o755)
proc = run_sh("--no-open", path=str(bindir))
assert proc.returncode == 3
assert "devstats: python3 >= 3.11 required, found 3.10" in proc.stderr