Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

feat(stats): 10x the GitHub-data dashboard (3 parallel agents)

mrbizarro827c5d8d18d4
diff --git a/docs/STATE.md b/docs/STATE.md
index 0b66c0b..8f81dd0 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -338,6 +338,72 @@ phosphene-dev.git/
## 7. Known bugs / fixed bugs
+### 2026-05-22 — ship-prep pass: GitHub-data dashboard + analytics ROLLED BACK
+
+Mr Bizarro decision: opt-in telemetry won't be well-received in the OSS
+world. Replaced with a GitHub-Traffic-API-only dashboard that gives the
+"how is the app doing" signal without putting any privacy weight on
+users. Three additional commits to dev:
+
+- **`da1d6f5` — analytics fully removed.** -871 lines. `analytics.py`
+ and `TELEMETRY.md` deleted. `mlx_ltx_panel.py` stripped of the
+ default-settings entries, validator branches, public-safe view
+ fields, `/settings` opt-in/opt-out/forget-me lifecycle,
+ `__main__` install + `panel_boot` emit, serve_forever-finally
+ shutdown, worker `render_start` / `render_done` / `render_failed`
+ / `render_cancelled` emits + error_category bucketing, the
+ Settings → Anonymous analytics HTML section, and the three JS
+ functions + modal-open hook. README reverted to "no telemetry".
+ Existing `panel_settings.json` files may still carry the old keys;
+ the loader ignores them silently — no migration script needed.
+
+- **`151d0d2` — solo-maintainer GitHub stats dashboard.** Three
+ files: `scripts/fetch_repo_stats.py` (stdlib-only Python fetches
+ repo + traffic + referrers + paths + releases; appends one JSON
+ line per UTC day to `docs/stats-data.jsonl`; idempotent),
+ `docs/stats.html` (vanilla-JS + Chart.js dashboard with cards,
+ time-series, referrer/path tables), and the seed snapshot.
+ `.github/workflows/repo-stats.yml` is staged locally — Mr Bizarro
+ must run `gh auth refresh -s workflow` + push it from a local
+ clone (the in-session OAuth token doesn't have `workflow` scope).
+
+- **Polish pass (next commit, batched with this STATE update).**
+ Three parallel research/improvement agents:
+ - **Dashboard polish**: period selector (7d/30d/90d/all),
+ week-over-week + yesterday delta per card, sparklines per
+ card, "Growth" daily + weekly card, stars-timeline section
+ (feature-detected), 15-day rolling window from
+ `clones_window`/`views_window` when present, loading
+ skeleton + error card, raw-JSONL header link, theme
+ toggle (light/dark, persists), keyboard focus rings,
+ sticky table headers + internal scroll, K/M number
+ shortening, clickable referrer domains, lazy chart init
+ via IntersectionObserver, mobile stacking, `aria-label`
+ everywhere. 1117 lines total, still single file + one CDN.
+ - **Fetcher enrichment**: full 15-day `clones_window` +
+ `views_window` arrays; `stars_timeline` (cumulative, login
+ DROPPED for privacy, capped at 5000); rate-limit handling
+ (sleep until reset when remaining < 100); 3-retry backoff
+ on 5xx/network; `--dry-run` + `--repo OWNER/NAME` flags;
+ one-line summary at exit for `$GITHUB_STEP_SUMMARY`.
+ - **Workflow hardening + maintainer README**: SHA-pinned
+ `actions/[email protected]` + `actions/[email protected]`;
+ concurrency group; `dry_run` + `repo` inputs on
+ workflow_dispatch; `$GITHUB_STEP_SUMMARY` + commit-body
+ summary; failure-issue creation that DE-DUPES across
+ consecutive outage days; minimized `permissions:`
+ (contents:write + issues:write only); pip cache enabled.
+ Plus a new `docs/stats-README.md` explaining the whole
+ stack for future maintainers (running locally, enabling
+ Pages, adding metrics, what GitHub data CAN'T tell you,
+ FAQ, troubleshooting).
+
+Today's seed data lands on the dashboard the moment Pages comes
+online: 57 stars, 5 forks, 8 open issues, 1 PR, 3954 clones in the
+last 14 days (148 unique today), 1601 views, with Google / GitHub
+/ Huggingface / Twitter / Reddit as the top funnels. W/w delta:
+clones -1130 (last week was a spike — likely a Reddit/HN bump).
+
### Fixed 2026-05-21 EVENING (overnight push — read this first)
Late-evening continuation after Mr Bizarro called out the still-broken
diff --git a/docs/stats-README.md b/docs/stats-README.md
new file mode 100644
index 0000000..0dd8e12
--- /dev/null
+++ b/docs/stats-README.md
@@ -0,0 +1,95 @@
+# Phosphene repo stats — maintainer guide
+
+A tiny, stdlib-only pipeline that snapshots GitHub repo metrics every day at
+03:17 UTC and publishes a static dashboard via GitHub Pages. Live dashboard:
+**https://mrbizarro.github.io/phosphene/stats.html** (served from `main`
+`/docs`). Nothing here calls a paid service or phones home from end-user
+machines — the whole stack is three files you can read in five minutes.
+
+## The three components
+
+| File | Role |
+|---|---|
+| `scripts/fetch_repo_stats.py` | Fetcher. Hits GitHub's REST API, builds one JSON row per UTC day. Pure stdlib (`urllib`). |
+| `docs/stats-data.jsonl` | Store. Append-only, newline-delimited JSON. Lives in git so history survives the Traffic API's 15-day rolling window. |
+| `docs/stats.html` | Dashboard. Loads the JSONL at page load, renders charts client-side. No build step. |
+
+Glue: `.github/workflows/repo-stats.yml` runs the fetcher daily, commits the
+updated JSONL, and opens an issue if anything breaks.
+
+## Run it locally
+
+```bash
+GITHUB_TOKEN=$(gh auth token) python3 scripts/fetch_repo_stats.py
+```
+
+Idempotent — re-running on the same UTC day replaces today's row. Flags:
+
+```bash
+python3 scripts/fetch_repo_stats.py --dry-run # don't write JSONL
+python3 scripts/fetch_repo_stats.py --repo OWNER/NAME # different repo
+```
+
+Both flags are also exposed from **Actions → repo-stats → Run workflow**.
+
+## Enable GitHub Pages
+
+Settings → Pages → Source: **Deploy from a branch**, Branch: `main`, folder
+`/docs`. Dashboard appears at `https://<owner>.github.io/<repo>/stats.html`
+within a minute.
+
+## Add a new metric
+
+1. **`scripts/fetch_repo_stats.py`** — add a fetcher function, add the key
+ to the row dict in `main()`, update the schema comment at the top.
+2. **`docs/stats.html`** — read the new key per row and render it. Plain JS
+ `fetch()` on the JSONL, no build.
+
+Old rows won't have the key, so default missing values (`?? 0` in JS,
+`row.get(key, 0)` in Python). Then run `workflow_dispatch` with
+`dry_run: true` to verify the fetcher still works before committing.
+
+## How to interpret the data
+
+- **clones** — every `git clone`, including CI and bots. Pinokio installs
+ Phosphene by `git clone`, so **a Pinokio install looks identical to a
+ human running `git clone`**. Don't read clones as "humans who installed."
+- **views** — github.com page views. Cached aggressively at the edge — a
+ real visitor may not show up for hours.
+- **referrers** — top 10 over a 14-day rolling window, no per-day
+ breakdown. Direct nav, dark-social (DMs / Slack / email), and most mobile
+ clients show up as "Google" or empty. Twitter / Discord / Reddit traffic
+ arriving without a `Referer` header **won't appear here**.
+- **paths** — top 10 most-viewed paths over the same 14-day window. Same
+ caveats as referrers.
+- **stars / forks / open_issues / open_prs / subscribers** — point-in-time
+ totals. `subscribers` is the real "Watch" count; `watchers` is a legacy
+ alias for stars.
+- **releases.by_release** — cumulative downloads per asset. Phosphene ships
+ through Pinokio, so this is usually empty.
+
+## FAQ
+
+**Why no client telemetry?** Mr Bizarro has explicitly chosen public-only
+metrics. No analytics SDK in the Pinokio app, no phone-home, no third-party
+JS in the dashboard. Everything here is what GitHub already shows in the
+Insights tab — we're just preserving it past the 15-day window.
+
+**Why public data?** The whole stack stays inside `github.com` and the repo
+itself. No secrets beyond the default `GITHUB_TOKEN`, no external services
+to lock us out, no separate dashboard host to forget about and rot.
+
+**How long does data live?** Forever — every snapshot is a git commit. To
+prune, edit `docs/stats-data.jsonl` directly and commit. There's no DB.
+
+## Troubleshooting
+
+- **Action failing** → check Issues filtered by `stats-broken`. The
+ workflow auto-opens one issue per outage and comments on it for each
+ subsequent failure (so a 7-day outage = 1 issue + 6 comments).
+- **Workflow missing from Actions tab** → you pushed without the `workflow`
+ OAuth scope. Run `gh auth refresh -s workflow` and push the
+ `.github/workflows/repo-stats.yml` file again from a local clone.
+- **Dashboard blank** → check `docs/stats-data.jsonl` actually has rows.
+ If empty, run the fetcher locally and commit. If full, open devtools —
+ `fetch()` 404s mean Pages isn't pointed at `/docs` on `main`.
diff --git a/docs/stats-data.jsonl b/docs/stats-data.jsonl
index 2efa53b..1881332 100644
--- a/docs/stats-data.jsonl
+++ b/docs/stats-data.jsonl
@@ -1 +1 @@
-{"date": "2026-05-22", "fetched_at": "2026-05-22T06:28:43Z", "stars": 57, "forks": 5, "open_issues": 8, "watchers": 57, "subscribers": 1, "open_prs": 1, "clones": {"count": 257, "uniques": 148}, "views": {"count": 72, "uniques": 29}, "referrers": [{"referrer": "Google", "count": 177, "uniques": 101}, {"referrer": "github.com", "count": 93, "uniques": 24}, {"referrer": "huggingface.co", "count": 69, "uniques": 42}, {"referrer": "t.co", "count": 60, "uniques": 33}, {"referrer": "reddit.com", "count": 40, "uniques": 20}, {"referrer": "DuckDuckGo", "count": 23, "uniques": 5}, {"referrer": "search.brave.com", "count": 16, "uniques": 7}, {"referrer": "chatgpt.com", "count": 12, "uniques": 3}, {"referrer": "Bing", "count": 4, "uniques": 4}, {"referrer": "mjjcommunity.com", "count": 4, "uniques": 1}], "paths": [{"path": "/mrbizarro/phosphene", "title": "Overview", "count": 869, "uniques": 504}, {"path": "/mrbizarro/phosphene/issues", "title": "/issues", "count": 136, "uniques": 67}, {"path": "/mrbizarro/phosphene/blob/main/assets/screenshot_panel_full.jpg", "title": "/blob/main/assets/screenshot_panel_full.jpg", "count": 46, "uniques": 42}, {"path": "/mrbizarro/phosphene/pulls", "title": "/pulls", "count": 38, "uniques": 27}, {"path": "/mrbizarro/phosphene/issues/8", "title": "/issues/8", "count": 37, "uniques": 18}, {"path": "/mrbizarro/phosphene/issues/4", "title": "/issues/4", "count": 25, "uniques": 16}, {"path": "/mrbizarro/phosphene/tree/dev", "title": "/tree/dev", "count": 25, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/2", "title": "/issues/2", "count": 20, "uniques": 14}, {"path": "/mrbizarro/phosphene/tree/main", "title": "/tree/main", "count": 19, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/3", "title": "/issues/3", "count": 18, "uniques": 14}], "releases": {"total": 0, "by_release": {}}}
+{"date": "2026-05-22", "fetched_at": "2026-05-22T06:40:53Z", "stars": 57, "forks": 5, "open_issues": 8, "watchers": 57, "subscribers": 1, "open_prs": 1, "clones": {"count": 257, "uniques": 148}, "views": {"count": 72, "uniques": 29}, "clones_window": [{"date": "2026-05-07", "count": 510, "uniques": 233}, {"date": "2026-05-08", "count": 492, "uniques": 251}, {"date": "2026-05-09", "count": 514, "uniques": 243}, {"date": "2026-05-10", "count": 188, "uniques": 131}, {"date": "2026-05-11", "count": 244, "uniques": 142}, {"date": "2026-05-12", "count": 313, "uniques": 227}, {"date": "2026-05-13", "count": 281, "uniques": 171}, {"date": "2026-05-14", "count": 154, "uniques": 128}, {"date": "2026-05-15", "count": 187, "uniques": 131}, {"date": "2026-05-16", "count": 186, "uniques": 148}, {"date": "2026-05-17", "count": 303, "uniques": 161}, {"date": "2026-05-18", "count": 193, "uniques": 126}, {"date": "2026-05-19", "count": 132, "uniques": 100}, {"date": "2026-05-20", "count": 257, "uniques": 148}], "views_window": [{"date": "2026-05-07", "count": 94, "uniques": 52}, {"date": "2026-05-08", "count": 137, "uniques": 54}, {"date": "2026-05-09", "count": 89, "uniques": 45}, {"date": "2026-05-10", "count": 105, "uniques": 57}, {"date": "2026-05-11", "count": 140, "uniques": 55}, {"date": "2026-05-12", "count": 110, "uniques": 51}, {"date": "2026-05-13", "count": 95, "uniques": 44}, {"date": "2026-05-14", "count": 113, "uniques": 52}, {"date": "2026-05-15", "count": 65, "uniques": 42}, {"date": "2026-05-16", "count": 183, "uniques": 55}, {"date": "2026-05-17", "count": 142, "uniques": 60}, {"date": "2026-05-18", "count": 108, "uniques": 49}, {"date": "2026-05-19", "count": 148, "uniques": 45}, {"date": "2026-05-20", "count": 72, "uniques": 29}], "stars_timeline": [{"date": "2026-04-30", "count": 3}, {"date": "2026-05-01", "count": 15}, {"date": "2026-05-03", "count": 21}, {"date": "2026-05-04", "count": 34}, {"date": "2026-05-05", "count": 36}, {"date": "2026-05-06", "count": 37}, {"date": "2026-05-07", "count": 41}, {"date": "2026-05-09", "count": 42}, {"date": "2026-05-11", "count": 45}, {"date": "2026-05-13", "count": 46}, {"date": "2026-05-14", "count": 50}, {"date": "2026-05-16", "count": 51}, {"date": "2026-05-18", "count": 54}, {"date": "2026-05-19", "count": 55}, {"date": "2026-05-20", "count": 56}, {"date": "2026-05-21", "count": 57}], "referrers": [{"referrer": "Google", "count": 177, "uniques": 101}, {"referrer": "github.com", "count": 93, "uniques": 24}, {"referrer": "huggingface.co", "count": 69, "uniques": 42}, {"referrer": "t.co", "count": 60, "uniques": 33}, {"referrer": "reddit.com", "count": 40, "uniques": 20}, {"referrer": "DuckDuckGo", "count": 23, "uniques": 5}, {"referrer": "search.brave.com", "count": 16, "uniques": 7}, {"referrer": "chatgpt.com", "count": 12, "uniques": 3}, {"referrer": "Bing", "count": 4, "uniques": 4}, {"referrer": "mjjcommunity.com", "count": 4, "uniques": 1}], "paths": [{"path": "/mrbizarro/phosphene", "title": "Overview", "count": 869, "uniques": 504}, {"path": "/mrbizarro/phosphene/issues", "title": "/issues", "count": 136, "uniques": 67}, {"path": "/mrbizarro/phosphene/blob/main/assets/screenshot_panel_full.jpg", "title": "/blob/main/assets/screenshot_panel_full.jpg", "count": 46, "uniques": 42}, {"path": "/mrbizarro/phosphene/pulls", "title": "/pulls", "count": 38, "uniques": 27}, {"path": "/mrbizarro/phosphene/issues/8", "title": "/issues/8", "count": 37, "uniques": 18}, {"path": "/mrbizarro/phosphene/issues/4", "title": "/issues/4", "count": 25, "uniques": 16}, {"path": "/mrbizarro/phosphene/tree/dev", "title": "/tree/dev", "count": 25, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/2", "title": "/issues/2", "count": 20, "uniques": 14}, {"path": "/mrbizarro/phosphene/tree/main", "title": "/tree/main", "count": 19, "uniques": 12}, {"path": "/mrbizarro/phosphene/issues/3", "title": "/issues/3", "count": 18, "uniques": 14}], "releases": {"total": 0, "by_release": {}}}
diff --git a/docs/stats.html b/docs/stats.html
index 145c259..1cf3cf3 100644
--- a/docs/stats.html
+++ b/docs/stats.html
@@ -19,13 +19,23 @@
No login, no telemetry, no analytics-ception. The data file is
public because it's committed to the public repo — that's by
design (open dashboards build trust).
+
+ Feature-detects future optional fields:
+ - clones_window: [{date,count,uniques}] — 15d rolling window
+ - views_window: [{date,count,uniques}] — 15d rolling window
+ - stars_timeline: [{starred_at,login_hash}] — per-star history
+ Anything else unknown is ignored gracefully.
-->
<style>
- :root {
+ /* Dark theme (default) */
+ :root, [data-theme="dark"] {
--bg: #0d1117;
--bg-card: #161b22;
--bg-card-2: #1f2630;
+ --bg-chip: #21262d;
+ --bg-chip-active: #1f6feb;
--border: #30363d;
+ --border-focus: #58a6ff;
--text: #c9d1d9;
--text-dim: #8b949e;
--text-faint:#6e7681;
@@ -33,6 +43,30 @@
--good: #3fb950;
--warn: #d29922;
--bad: #f85149;
+ --grid: #21262d;
+ --skel-1: #1f2630;
+ --skel-2: #2a323d;
+ --shadow: rgba(0,0,0,0.3);
+ }
+ [data-theme="light"] {
+ --bg: #ffffff;
+ --bg-card: #f6f8fa;
+ --bg-card-2: #ffffff;
+ --bg-chip: #eaeef2;
+ --bg-chip-active: #0969da;
+ --border: #d0d7de;
+ --border-focus: #0969da;
+ --text: #1f2328;
+ --text-dim: #59636e;
+ --text-faint:#818b98;
+ --accent: #0969da;
+ --good: #1a7f37;
+ --warn: #9a6700;
+ --bad: #cf222e;
+ --grid: #eaeef2;
+ --skel-1: #eaeef2;
+ --skel-2: #d0d7de;
+ --shadow: rgba(140,149,159,0.15);
}
* { box-sizing: border-box; }
html, body {
@@ -41,9 +75,17 @@
font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text",
"Segoe UI", system-ui, sans-serif;
min-height: 100vh;
+ transition: background 0.15s ease, color 0.15s ease;
}
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
+ /* Visible focus ring everywhere */
+ :focus { outline: none; }
+ :focus-visible {
+ outline: 2px solid var(--border-focus);
+ outline-offset: 2px;
+ border-radius: 4px;
+ }
.wrap { max-width: 1100px; margin: 0 auto; padding: 28px 24px 80px; }
header {
display: flex; align-items: baseline; justify-content: space-between;
@@ -56,10 +98,33 @@
color: var(--text-dim); font-weight: 400; font-size: 14px;
margin-left: 10px;
}
+ .meta-row {
+ display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
+ }
.meta {
color: var(--text-dim); font-size: 13px;
}
.meta strong { color: var(--text); font-weight: 500; }
+ .header-actions {
+ display: flex; gap: 8px; align-items: center;
+ }
+ .icon-btn {
+ background: var(--bg-card);
+ border: 1px solid var(--border);
+ color: var(--text-dim);
+ font-size: 12px;
+ padding: 6px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
+ font-family: inherit;
+ line-height: 1;
+ }
+ .icon-btn:hover {
+ background: var(--bg-card-2);
+ color: var(--text);
+ border-color: var(--text-dim);
+ }
section {
background: var(--bg-card);
border: 1px solid var(--border);
@@ -71,10 +136,35 @@
font-size: 13px; font-weight: 600; text-transform: uppercase;
letter-spacing: 0.05em; color: var(--text-dim); margin: 0 0 14px;
}
+ .section-head {
+ display: flex; align-items: center; justify-content: space-between;
+ gap: 12px; flex-wrap: wrap; margin-bottom: 14px;
+ }
+ .section-head h2 { margin: 0; }
+ /* Period chips */
+ .chips {
+ display: inline-flex; gap: 4px;
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px; padding: 3px;
+ }
+ .chip {
+ background: transparent; border: 0;
+ color: var(--text-dim);
+ font: inherit; font-size: 12px; font-weight: 500;
+ padding: 4px 10px; border-radius: 4px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
+ .chip:hover { color: var(--text); }
+ .chip[aria-pressed="true"] {
+ background: var(--bg-chip-active);
+ color: white;
+ }
/* Cards row */
.cards {
display: grid;
- grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 12px;
}
.card {
@@ -82,6 +172,8 @@
border: 1px solid var(--border);
border-radius: 6px;
padding: 14px 16px;
+ position: relative;
+ overflow: hidden;
}
.card .label {
color: var(--text-dim);
@@ -91,19 +183,27 @@
.card .value {
font-size: 28px; font-weight: 600; line-height: 1.1;
margin-top: 6px;
+ font-variant-numeric: tabular-nums;
}
- .card .delta {
- font-size: 12px; color: var(--text-faint); margin-top: 4px;
+ .card .deltas {
+ display: flex; gap: 8px; flex-wrap: wrap;
+ margin-top: 6px; font-size: 11px;
}
+ .card .delta { color: var(--text-faint); }
.card .delta.up { color: var(--good); }
.card .delta.down { color: var(--bad); }
+ .card .delta .lbl { color: var(--text-faint); margin-right: 2px; }
+ .card .spark {
+ height: 28px; margin-top: 8px;
+ width: 100%;
+ }
/* Chart blocks */
.chart-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
}
- @media (max-width: 720px) {
+ @media (max-width: 600px) {
.chart-row { grid-template-columns: 1fr; }
}
.chart-card {
@@ -131,12 +231,22 @@
th {
font-weight: 500; color: var(--text-dim);
text-transform: uppercase; font-size: 11px; letter-spacing: 0.05em;
+ position: sticky; top: 0;
+ background: var(--bg-card);
}
td.num { text-align: right; font-variant-numeric: tabular-nums; }
+ .table-wrap {
+ max-height: 360px; overflow-y: auto;
+ border: 1px solid var(--border); border-radius: 6px;
+ }
+ .table-wrap table th, .table-wrap table td { padding: 8px 10px; }
+ .table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 12px; }
+ .table-wrap table th:last-child, .table-wrap table td:last-child { padding-right: 12px; }
+ .table-wrap table tbody tr:last-child td { border-bottom: 0; }
.two-col {
display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
}
- @media (max-width: 720px) {
+ @media (max-width: 600px) {
.two-col { grid-template-columns: 1fr; }
}
.empty {
@@ -151,61 +261,205 @@
color: var(--text-faint); font-size: 12px; text-align: center;
margin-top: 30px;
}
+ /* Skeletons */
+ @keyframes skel-pulse {
+ 0%, 100% { background-color: var(--skel-1); }
+ 50% { background-color: var(--skel-2); }
+ }
+ .skel {
+ animation: skel-pulse 1.4s ease-in-out infinite;
+ border-radius: 4px;
+ display: inline-block;
+ }
+ .skel-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ min-height: 92px;
+ }
+ .skel-card .skel.label { width: 60%; height: 10px; margin-bottom: 12px; }
+ .skel-card .skel.value { width: 50%; height: 24px; margin-bottom: 8px; }
+ .skel-card .skel.delta { width: 70%; height: 10px; }
+ .skel-chart { width: 100%; height: 180px; }
+ /* Error card */
+ .error-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--bad);
+ border-radius: 8px;
+ padding: 20px;
+ color: var(--text);
+ }
+ .error-card .err-title {
+ color: var(--bad);
+ font-weight: 600; font-size: 14px;
+ margin: 0 0 8px;
+ display: flex; align-items: center; gap: 8px;
+ }
+ .error-card .err-msg {
+ color: var(--text-dim); font-size: 13px;
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ margin: 0 0 12px;
+ word-break: break-word;
+ }
+ .error-card .err-actions {
+ display: flex; gap: 8px; flex-wrap: wrap;
+ }
+ .btn {
+ background: var(--accent);
+ color: #fff; border: 0;
+ padding: 7px 14px; border-radius: 6px;
+ cursor: pointer; font: inherit; font-size: 13px; font-weight: 500;
+ }
+ .btn:hover { filter: brightness(1.1); }
+ .btn.ghost {
+ background: var(--bg-card);
+ color: var(--text);
+ border: 1px solid var(--border);
+ }
+ .btn.ghost:hover { background: var(--bg-card-2); }
+ .num-tip { cursor: help; border-bottom: 1px dashed var(--text-faint); }
+ /* Mobile tweaks */
+ @media (max-width: 600px) {
+ .wrap { padding: 20px 14px 60px; }
+ header { gap: 8px; }
+ h1 { font-size: 19px; }
+ h1 .subtitle { display: block; margin: 4px 0 0; }
+ section { padding: 16px 14px; }
+ .card .value { font-size: 24px; }
+ }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>Phosphene · stats <span class="subtitle">solo-maintainer dashboard</span></h1>
- <div class="meta" id="meta">loading…</div>
+ <div class="meta-row">
+ <div class="meta" id="meta" aria-live="polite">
+ <span class="skel" style="width:200px;height:13px"></span>
+ </div>
+ <div class="header-actions">
+ <a class="icon-btn" id="raw-link"
+ href="https://github.com/mrbizarro/phosphene/blob/main/docs/stats-data.jsonl"
+ target="_blank" rel="noopener"
+ title="View raw JSONL data file on GitHub">raw JSONL ↗</a>
+ <button class="icon-btn" id="theme-toggle"
+ type="button" aria-label="Toggle light / dark theme"
+ title="Toggle theme">◐</button>
+ </div>
+ </div>
</header>
+ <!-- Mount point for error state. Hidden unless fetch fails. -->
+ <div id="error-mount" hidden></div>
+
<!-- Big number cards: state TODAY (last snapshot) -->
- <section>
+ <section id="sec-now">
<h2>Right now</h2>
- <div class="cards" id="cards"></div>
+ <div class="cards" id="cards" aria-busy="true" aria-label="Current repository stats">
+ <!-- skeleton placeholders -->
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ </div>
</section>
<!-- Time-series charts: cumulative + daily counts -->
- <section>
- <h2>Over time</h2>
+ <section id="sec-over-time">
+ <div class="section-head">
+ <h2>Over time</h2>
+ <div class="chips" role="group" aria-label="Date range">
+ <button class="chip" type="button" data-period="7" aria-pressed="false">7d</button>
+ <button class="chip" type="button" data-period="30" aria-pressed="true">30d</button>
+ <button class="chip" type="button" data-period="90" aria-pressed="false">90d</button>
+ <button class="chip" type="button" data-period="all" aria-pressed="false">all</button>
+ </div>
+ </div>
<div class="chart-row">
<div class="chart-card">
<h3>Stars · cumulative</h3>
- <div class="chart-wrap"><canvas id="chart-stars"></canvas></div>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-stars"
+ aria-label="Line chart of cumulative star count over the selected date range"
+ role="img"></canvas>
+ </div>
</div>
<div class="chart-card">
<h3>Forks · cumulative</h3>
- <div class="chart-wrap"><canvas id="chart-forks"></canvas></div>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-forks"
+ aria-label="Line chart of cumulative fork count over the selected date range"
+ role="img"></canvas>
+ </div>
</div>
</div>
<div class="chart-row" style="margin-top:14px">
<div class="chart-card">
<h3>Clones per day</h3>
- <div class="chart-wrap"><canvas id="chart-clones"></canvas></div>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-clones"
+ aria-label="Bar chart of git clones per day over the selected date range"
+ role="img"></canvas>
+ </div>
</div>
<div class="chart-card">
<h3>Repo page views per day</h3>
- <div class="chart-wrap"><canvas id="chart-views"></canvas></div>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-views"
+ aria-label="Bar chart of repository page views per day over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ </div>
+ <!-- Stars-gained section, only inserted if stars_timeline is present -->
+ <div id="stars-timeline-row" hidden style="margin-top:14px">
+ <div class="chart-row">
+ <div class="chart-card">
+ <h3>New stars per day</h3>
+ <div class="chart-wrap">
+ <canvas id="chart-stars-gained"
+ aria-label="Bar chart of new stars gained per day over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ <div class="chart-card">
+ <h3>Cumulative stars from history</h3>
+ <div class="chart-wrap">
+ <canvas id="chart-stars-history"
+ aria-label="Line chart of cumulative star count derived from full stargazer history"
+ role="img"></canvas>
+ </div>
+ </div>
</div>
</div>
</section>
<!-- 14-day rolling snapshots from latest fetch -->
- <section>
+ <section id="sec-traffic">
<h2>Where traffic comes from (last 14 days)</h2>
<div class="two-col">
<div>
<h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top referrers</h3>
- <table id="referrers-table"><thead><tr>
- <th>Source</th><th class="num">Views</th><th class="num">Uniques</th>
- </tr></thead><tbody></tbody></table>
+ <div class="table-wrap">
+ <table id="referrers-table"><thead><tr>
+ <th>Source</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody>
+ <tr><td colspan="3" class="empty">loading…</td></tr>
+ </tbody></table>
+ </div>
</div>
<div>
<h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top paths</h3>
- <table id="paths-table"><thead><tr>
- <th>Path</th><th class="num">Views</th><th class="num">Uniques</th>
- </tr></thead><tbody></tbody></table>
+ <div class="table-wrap">
+ <table id="paths-table"><thead><tr>
+ <th>Path</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody>
+ <tr><td colspan="3" class="empty">loading…</td></tr>
+ </tbody></table>
+ </div>
</div>
</div>
</section>
@@ -221,80 +475,342 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script>
+ // ====================================================================
+ // Phosphene stats dashboard — vanilla JS, single file, no build step.
+ // Loads docs/stats-data.jsonl, renders cards/charts/tables.
+ //
+ // State is held in module-scope vars, charts are created/destroyed
+ // on period change. Period selection + theme persist in localStorage.
+ // ====================================================================
+
+ const LS_PERIOD = 'phosphene.stats.period';
+ const LS_THEME = 'phosphene.stats.theme';
+ const REPO_URL = 'https://github.com/mrbizarro/phosphene';
+ const JSONL_URL = 'stats-data.jsonl';
+ const RAW_URL = REPO_URL + '/blob/main/docs/stats-data.jsonl';
+
+ let allRows = []; // every row from JSONL, sorted ascending
+ let currentPeriod = '30'; // '7' | '30' | '90' | 'all'
+ const charts = {}; // id -> Chart instance (so we can destroy & redraw)
+ const sparkCharts = {}; // card-label -> mini Chart
+ const intersectObservers = new Map();
+
+ // ---- theme ---------------------------------------------------------
+ function initTheme() {
+ const saved = localStorage.getItem(LS_THEME);
+ const theme = saved === 'light' ? 'light' : 'dark';
+ document.documentElement.setAttribute('data-theme', theme);
+ const btn = document.getElementById('theme-toggle');
+ btn.textContent = theme === 'light' ? '☀' : '◐';
+ btn.setAttribute('aria-label',
+ theme === 'light' ? 'Switch to dark theme' : 'Switch to light theme');
+ btn.addEventListener('click', toggleTheme);
+ }
+ function toggleTheme() {
+ const cur = document.documentElement.getAttribute('data-theme') || 'dark';
+ const next = cur === 'dark' ? 'light' : 'dark';
+ document.documentElement.setAttribute('data-theme', next);
+ localStorage.setItem(LS_THEME, next);
+ const btn = document.getElementById('theme-toggle');
+ btn.textContent = next === 'light' ? '☀' : '◐';
+ btn.setAttribute('aria-label',
+ next === 'light' ? 'Switch to dark theme' : 'Switch to light theme');
+ // Chart colors come from CSS-var-tinted JS literals; rerender so they pick up.
+ if (allRows.length) {
+ destroyAllCharts();
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ renderCards(allRows); // sparklines too
+ }
+ }
+
// ---- load + parse the JSONL ----------------------------------------
async function loadRows() {
- const r = await fetch('stats-data.jsonl', {cache: 'no-store'});
- if (!r.ok) throw new Error('HTTP ' + r.status + ' on stats-data.jsonl');
+ const r = await fetch(JSONL_URL, {cache: 'no-store'});
+ if (!r.ok) throw new Error('HTTP ' + r.status + ' on ' + JSONL_URL);
const text = await r.text();
- return text.split(/\n+/).filter(Boolean).map(l => JSON.parse(l));
+ const rows = text.split(/\n+/).filter(Boolean).map(l => {
+ try { return JSON.parse(l); }
+ catch (e) { console.warn('skipping bad row', e); return null; }
+ }).filter(Boolean);
+ rows.sort((a, b) => (a.date || '') < (b.date || '') ? -1 : 1);
+ return rows;
}
- // ---- small helpers --------------------------------------------------
- const fmt = n => (n == null ? '—' : n.toLocaleString());
- const dayAgo = (iso) => {
+ // ---- helpers --------------------------------------------------------
+ function fmt(n) {
+ return (n == null || Number.isNaN(n)) ? '—' : Number(n).toLocaleString();
+ }
+ /** Format big numbers with K/M shortening (>9999). */
+ function fmtShort(n) {
+ if (n == null || Number.isNaN(n)) return '—';
+ const abs = Math.abs(n);
+ if (abs < 10000) return Number(n).toLocaleString();
+ if (abs < 1e6) return (n / 1e3).toFixed(n % 1e3 === 0 ? 0 : 1).replace(/\.0$/, '') + 'K';
+ if (abs < 1e9) return (n / 1e6).toFixed(n % 1e6 === 0 ? 0 : 1).replace(/\.0$/, '') + 'M';
+ return (n / 1e9).toFixed(1).replace(/\.0$/, '') + 'B';
+ }
+ function dayAgo(iso) {
const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '—';
const ms = Date.now() - t;
- const d = Math.floor(ms / 86400000);
- if (d === 0) return 'today';
+ if (ms < 60_000) return 'just now';
+ if (ms < 3_600_000) return Math.floor(ms / 60_000) + 'm ago';
+ if (ms < 86_400_000) return Math.floor(ms / 3_600_000) + 'h ago';
+ const d = Math.floor(ms / 86_400_000);
if (d === 1) return 'yesterday';
if (d < 7) return d + 'd ago';
return Math.floor(d / 7) + 'w ago';
- };
+ }
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, c =>
+ ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])
+ );
+ }
+ function escapeAttr(s) { return escapeHtml(s); }
+
+ /** Read a CSS variable from :root so charts respect the active theme. */
+ function cssVar(name) {
+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ }
- function deltaSpan(today, yesterday) {
- if (today == null || yesterday == null) return '';
- const d = today - yesterday;
- if (d === 0) return '<span class="delta">no change</span>';
- const sign = d > 0 ? '+' : '';
- const cls = d > 0 ? 'up' : 'down';
- return `<span class="delta ${cls}">${sign}${d.toLocaleString()} vs yday</span>`;
+ /** Slice rows by period. period ∈ {'7','30','90','all'}. */
+ function sliceByPeriod(rows, period) {
+ if (period === 'all' || !period) return rows;
+ const n = parseInt(period, 10);
+ if (!Number.isFinite(n) || n <= 0) return rows;
+ return rows.slice(-n);
}
+ /** Two-line delta span (yday + week-over-week). */
+ function deltaSpan(today, yesterday, weekAgo) {
+ const out = [];
+ if (today != null && yesterday != null) {
+ out.push(deltaPart(today - yesterday, 'yday'));
+ }
+ // w/w only when we have a value 7+ snapshots back
+ if (today != null && weekAgo != null && weekAgo !== yesterday) {
+ out.push(deltaPart(today - weekAgo, 'w/w'));
+ }
+ if (!out.length) return '';
+ return `<div class="deltas">${out.join('')}</div>`;
+ }
+ function deltaPart(diff, label) {
+ if (diff === 0) return `<span class="delta"><span class="lbl">${label}</span>±0</span>`;
+ const sign = diff > 0 ? '+' : '';
+ const cls = diff > 0 ? 'up' : 'down';
+ return `<span class="delta ${cls}"><span class="lbl">${label}</span>${sign}${diff.toLocaleString()}</span>`;
+ }
+
+ // ---- cards + sparklines --------------------------------------------
+ /**
+ * Build the card row. We always source values from allRows so the
+ * "Right now" snapshot is the true latest (period slider only affects
+ * the charts), and sparklines reflect the last 14 days of history.
+ */
function renderCards(rows) {
+ const mount = document.getElementById('cards');
+ mount.setAttribute('aria-busy', 'false');
+ if (!rows.length) {
+ mount.innerHTML = '<div class="empty">no snapshots yet — first fetch due 03:17 UTC</div>';
+ return;
+ }
const last = rows[rows.length - 1];
const prev = rows.length > 1 ? rows[rows.length - 2] : {};
+ // For week-over-week: prefer rows[len-8] (7 days back). If we don't
+ // have 8 rows, fall back to prev so yday is the only signal.
+ const wkIdx = rows.length - 8;
+ const week = wkIdx >= 0 ? rows[wkIdx] : null;
+
+ // 14-day spark series. (Use full history if fewer than 14 rows exist.)
+ const sparkRows = rows.slice(-14);
+ const sparkOf = pick => sparkRows.map(pick);
+
const cards = [
- {label: "Stars", value: last.stars, yday: prev.stars},
- {label: "Forks", value: last.forks, yday: prev.forks},
- {label: "Watchers", value: last.subscribers, yday: prev.subscribers},
- {label: "Clones · today",value: last.clones?.count, yday: prev.clones?.count},
- {label: "Views · today", value: last.views?.count, yday: prev.views?.count},
- {label: "Open issues", value: last.open_issues, yday: prev.open_issues},
- {label: "Open PRs", value: last.open_prs, yday: prev.open_prs},
+ {
+ key:'stars', label:'Stars', value:last.stars,
+ yday:prev.stars, wk:week?.stars,
+ spark:sparkOf(r => r.stars), color:'#58a6ff',
+ },
+ {
+ key:'forks', label:'Forks', value:last.forks,
+ yday:prev.forks, wk:week?.forks,
+ spark:sparkOf(r => r.forks), color:'#8957e5',
+ },
+ {
+ key:'watchers', label:'Watchers', value:last.subscribers,
+ yday:prev.subscribers, wk:week?.subscribers,
+ spark:sparkOf(r => r.subscribers), color:'#39c5cf',
+ },
+ {
+ key:'clones', label:'Clones · today',
+ value:last.clones?.count,
+ yday:prev.clones?.count, wk:week?.clones?.count,
+ spark:sparkOf(r => r.clones?.count ?? 0), color:'#3fb950',
+ },
+ {
+ key:'views', label:'Views · today',
+ value:last.views?.count,
+ yday:prev.views?.count, wk:week?.views?.count,
+ spark:sparkOf(r => r.views?.count ?? 0), color:'#d29922',
+ },
+ {
+ key:'issues', label:'Open issues',
+ value:last.open_issues,
+ yday:prev.open_issues, wk:week?.open_issues,
+ spark:sparkOf(r => r.open_issues), color:'#f85149',
+ },
+ {
+ key:'prs', label:'Open PRs',
+ value:last.open_prs,
+ yday:prev.open_prs, wk:week?.open_prs,
+ spark:sparkOf(r => r.open_prs), color:'#a371f7',
+ },
];
+
+ // Growth card — the headline "is this growing?" number.
+ // Daily growth = (today_clones - yday_clones) / max(yday,1)
+ // Weekly growth = avg(last 7 clones) vs avg(prev 7 clones).
+ const growth = computeGrowth(rows);
+ cards.push({
+ key:'growth', label:'Clone growth',
+ custom: renderGrowthCard(growth),
+ });
+
const total_dl = last.releases?.total ?? null;
if (total_dl != null && total_dl > 0) {
- cards.push({label: "Release downloads", value: total_dl, yday: prev.releases?.total});
+ cards.push({
+ key:'dl', label:'Release downloads',
+ value:total_dl, yday:prev.releases?.total, wk:week?.releases?.total,
+ spark:sparkOf(r => r.releases?.total ?? 0), color:'#58a6ff',
+ });
}
- document.getElementById('cards').innerHTML = cards.map(c => `
- <div class="card">
- <div class="label">${c.label}</div>
- <div class="value">${fmt(c.value)}</div>
- ${deltaSpan(c.value, c.yday)}
- </div>
- `).join('');
+
+ mount.innerHTML = cards.map(c => {
+ if (c.custom) {
+ return `<div class="card" data-key="${c.key}" tabindex="0">${c.custom}</div>`;
+ }
+ const isBig = c.value != null && Math.abs(c.value) > 9999;
+ const valHtml = isBig
+ ? `<div class="value"><span class="num-tip" title="${escapeAttr(fmt(c.value))}">${escapeHtml(fmtShort(c.value))}</span></div>`
+ : `<div class="value">${fmt(c.value)}</div>`;
+ const sparkOk = c.spark && c.spark.length >= 2 &&
+ c.spark.some(v => v != null && v !== 0);
+ return `
+ <div class="card" data-key="${c.key}" tabindex="0">
+ <div class="label">${escapeHtml(c.label)}</div>
+ ${valHtml}
+ ${deltaSpan(c.value, c.yday, c.wk)}
+ ${sparkOk ? `<canvas class="spark" id="spark-${c.key}" aria-hidden="true"></canvas>` : ''}
+ </div>`;
+ }).join('');
+
+ // Now draw sparklines (after cards are in DOM).
+ cards.forEach(c => {
+ if (!c.spark) return;
+ const sparkOk = c.spark.length >= 2 &&
+ c.spark.some(v => v != null && v !== 0);
+ if (!sparkOk) return;
+ drawSparkline('spark-' + c.key, c.spark, c.color);
+ });
+ }
+
+ function computeGrowth(rows) {
+ // Daily growth rate from clone counts.
+ const counts = rows.map(r => r.clones?.count ?? 0);
+ const today = counts[counts.length - 1] ?? null;
+ const yday = counts[counts.length - 2] ?? null;
+ let daily = null;
+ if (today != null && yday != null) {
+ if (yday === 0) daily = today > 0 ? Infinity : 0;
+ else daily = ((today - yday) / yday) * 100;
+ }
+ // Weekly: last 7 vs prior 7 (if we have 14+ rows).
+ let weekly = null;
+ if (counts.length >= 14) {
+ const cur = counts.slice(-7).reduce((a,b) => a+b, 0);
+ const prev = counts.slice(-14, -7).reduce((a,b) => a+b, 0);
+ if (prev === 0) weekly = cur > 0 ? Infinity : 0;
+ else weekly = ((cur - prev) / prev) * 100;
+ }
+ return { daily, weekly };
}
- // ---- charts ---------------------------------------------------------
- Chart.defaults.color = '#8b949e';
- Chart.defaults.borderColor = '#30363d';
+ function renderGrowthCard(g) {
+ // Build {text, cls} for a percent value (or null / Infinity).
+ const pct = v => {
+ if (v == null) return { text: '—', cls: '' };
+ if (v === Infinity) return { text: 'new', cls: 'up' };
+ if (v === 0) return { text: '0.0%', cls: '' };
+ const sign = v > 0 ? '+' : '';
+ return { text: sign + v.toFixed(1) + '%', cls: v > 0 ? 'up' : 'down' };
+ };
+ const day = pct(g.daily);
+ const week = pct(g.weekly);
+ // Big number prefers weekly (smoother signal), falls back to daily.
+ const big = g.weekly != null ? week : day;
+ const bigColor = big.cls === 'up' ? 'color:var(--good)'
+ : big.cls === 'down' ? 'color:var(--bad)'
+ : '';
+ return `
+ <div class="label" title="Daily and weekly clone growth — the simplest 'is this app catching on?' signal.">Clone growth</div>
+ <div class="value" style="${bigColor}">${escapeHtml(big.text)}</div>
+ <div class="deltas" style="margin-top:8px">
+ <span class="delta ${day.cls}"><span class="lbl">day</span>${escapeHtml(day.text)}</span>
+ <span class="delta ${week.cls}"><span class="lbl">week</span>${escapeHtml(week.text)}</span>
+ </div>`;
+ }
+
+ function drawSparkline(canvasId, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ if (sparkCharts[canvasId]) { sparkCharts[canvasId].destroy(); }
+ sparkCharts[canvasId] = new Chart(el.getContext('2d'), {
+ type: 'line',
+ data: {
+ labels: data.map((_, i) => i),
+ datasets: [{
+ data,
+ borderColor: color,
+ backgroundColor: color + '22',
+ fill: true, tension: 0.3,
+ pointRadius: 0, pointHoverRadius: 3,
+ borderWidth: 1.5,
+ }]
+ },
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ plugins: { legend: { display: false }, tooltip: { enabled: false } },
+ scales: { x: { display: false }, y: { display: false } },
+ animation: false,
+ }
+ });
+ }
+
+ // ---- main charts ---------------------------------------------------
Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, system-ui, sans-serif';
Chart.defaults.font.size = 11;
Chart.defaults.plugins.legend.display = false;
- const COMMON_OPTS = {
- responsive: true, maintainAspectRatio: false,
- scales: {
- x: { grid: { color: '#21262d' }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8 } },
- y: { grid: { color: '#21262d' }, beginAtZero: true, ticks: { precision: 0 } },
- },
- plugins: { tooltip: { intersect: false, mode: 'index' } },
- };
+ function commonOpts() {
+ // Pull colors fresh each render so theme switching works.
+ Chart.defaults.color = cssVar('--text-dim') || '#8b949e';
+ Chart.defaults.borderColor = cssVar('--border') || '#30363d';
+ const grid = cssVar('--grid') || '#21262d';
+ return {
+ responsive: true, maintainAspectRatio: false,
+ scales: {
+ x: { grid: { color: grid }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8 } },
+ y: { grid: { color: grid }, beginAtZero: true, ticks: { precision: 0 } },
+ },
+ plugins: { tooltip: { intersect: false, mode: 'index' } },
+ };
+ }
function lineChart(canvasId, labels, data, color) {
const el = document.getElementById(canvasId);
if (!el) return;
- new Chart(el.getContext('2d'), {
+ if (charts[canvasId]) { charts[canvasId].destroy(); }
+ charts[canvasId] = new Chart(el.getContext('2d'), {
type: 'line',
data: {
labels,
@@ -306,30 +822,135 @@
pointHoverRadius: 4, borderWidth: 2,
}]
},
- options: COMMON_OPTS,
+ options: commonOpts(),
});
}
function barChart(canvasId, labels, data, color) {
const el = document.getElementById(canvasId);
if (!el) return;
- new Chart(el.getContext('2d'), {
+ if (charts[canvasId]) { charts[canvasId].destroy(); }
+ charts[canvasId] = new Chart(el.getContext('2d'), {
type: 'bar',
data: {
labels,
datasets: [{ data, backgroundColor: color, borderWidth: 0 }]
},
- options: COMMON_OPTS,
+ options: commonOpts(),
});
}
- function renderCharts(rows) {
- // X-axis labels in MM-DD so they fit on mobile.
- const labels = rows.map(r => r.date?.slice(5) || '');
- lineChart('chart-stars', labels, rows.map(r => r.stars ?? null), '#58a6ff');
- lineChart('chart-forks', labels, rows.map(r => r.forks ?? null), '#8957e5');
- barChart ('chart-clones', labels, rows.map(r => r.clones?.count ?? 0), '#3fb950');
- barChart ('chart-views', labels, rows.map(r => r.views?.count ?? 0), '#d29922');
+ function destroyAllCharts() {
+ Object.values(charts).forEach(c => c?.destroy?.());
+ for (const k in charts) delete charts[k];
+ }
+
+ /**
+ * Render the four "Over time" charts for the given slice.
+ *
+ * For clones+views, we prefer the freshest `clones_window` / `views_window`
+ * array on the LATEST row (if present), because the daily snapshot files
+ * record only a single per-day number, while the GH API actually gives us
+ * a 15-day rolling window each fetch. Using the window on day 1 means we
+ * already see 15 days of granularity instead of one point.
+ */
+ function renderCharts(slice) {
+ if (!slice.length) return;
+ const last = slice[slice.length - 1];
+ const labels = slice.map(r => r.date?.slice(5) || '');
+
+ lineChart('chart-stars', labels, slice.map(r => r.stars ?? null), '#58a6ff');
+ lineChart('chart-forks', labels, slice.map(r => r.forks ?? null), '#8957e5');
+
+ // Clones: prefer the rolling window if present + we'd otherwise show 1 dot.
+ const useClonesWindow = Array.isArray(last.clones_window) && last.clones_window.length > 1
+ && slice.length < last.clones_window.length;
+ if (useClonesWindow) {
+ const w = last.clones_window;
+ barChart('chart-clones',
+ w.map(p => (p.date || '').slice(5)),
+ w.map(p => p.count ?? 0),
+ '#3fb950');
+ } else {
+ barChart('chart-clones', labels, slice.map(r => r.clones?.count ?? 0), '#3fb950');
+ }
+
+ const useViewsWindow = Array.isArray(last.views_window) && last.views_window.length > 1
+ && slice.length < last.views_window.length;
+ if (useViewsWindow) {
+ const w = last.views_window;
+ barChart('chart-views',
+ w.map(p => (p.date || '').slice(5)),
+ w.map(p => p.count ?? 0),
+ '#d29922');
+ } else {
+ barChart('chart-views', labels, slice.map(r => r.views?.count ?? 0), '#d29922');
+ }
+
+ renderStarsTimeline(last, slice);
+ }
+
+ /**
+ * stars_timeline (optional): list of {starred_at, login_hash}.
+ * If present on the latest row, draw a per-day stars-gained bar chart
+ * and a cumulative line derived from the FULL history (not just the
+ * fetcher's daily snapshot). Feature-detect; silent skip if absent.
+ */
+ function renderStarsTimeline(last, slice) {
+ const row = document.getElementById('stars-timeline-row');
+ const tl = Array.isArray(last.stars_timeline) ? last.stars_timeline : null;
+ if (!tl || tl.length === 0) { row.hidden = true; return; }
+ row.hidden = false;
+
+ // Group by date (UTC yyyy-mm-dd) → count.
+ const byDay = new Map();
+ for (const ev of tl) {
+ const d = (ev.starred_at || '').slice(0, 10);
+ if (!d) continue;
+ byDay.set(d, (byDay.get(d) || 0) + 1);
+ }
+ const sortedDays = [...byDay.keys()].sort();
+ if (!sortedDays.length) { row.hidden = true; return; }
+
+ // Limit timeline to the current period (matches the chip selection).
+ let days = sortedDays;
+ if (currentPeriod !== 'all') {
+ const n = parseInt(currentPeriod, 10);
+ if (Number.isFinite(n)) days = sortedDays.slice(-n);
+ }
+
+ const labels = days.map(d => d.slice(5));
+ const gained = days.map(d => byDay.get(d) || 0);
+
+ // Cumulative from the START of full history (so the line is meaningful
+ // even when sliced).
+ const cum = [];
+ let total = 0;
+ for (const d of sortedDays) {
+ total += byDay.get(d) || 0;
+ if (days.includes(d)) cum.push(total);
+ }
+
+ barChart ('chart-stars-gained', labels, gained, '#58a6ff');
+ lineChart('chart-stars-history', labels, cum, '#58a6ff');
+ }
+
+ // ---- tables --------------------------------------------------------
+ /** Turn a referrer string (e.g. "reddit.com" or "Google") into a URL
+ * if we can confidently link it. Returns null for opaque search-engine
+ * names like "Google" / "DuckDuckGo" / "Bing" where the real URL is
+ * hidden by GitHub. */
+ function referrerHref(name) {
+ if (!name) return null;
+ const SEARCH_ENGINES = new Set(['google','bing','duckduckgo','yahoo','baidu','yandex']);
+ if (SEARCH_ENGINES.has(name.toLowerCase())) return null;
+ // Heuristic: looks like a domain if it contains a dot and no spaces.
+ if (/\s/.test(name)) return null;
+ if (!/\./.test(name)) return null;
+ // Strip stray protocol if present.
+ const host = name.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
+ if (!host) return null;
+ return 'https://' + host;
}
function renderTables(rows) {
@@ -341,57 +962,154 @@
if (refs.length === 0) {
refBody.innerHTML = '<tr><td colspan="3" class="empty">no referrer data yet</td></tr>';
} else {
- refBody.innerHTML = refs.map(r => `
- <tr><td>${escapeHtml(r.referrer)}</td>
- <td class="num">${fmt(r.count)}</td>
- <td class="num">${fmt(r.uniques)}</td></tr>
- `).join('');
+ refBody.innerHTML = refs.map(r => {
+ const href = referrerHref(r.referrer);
+ const name = href
+ ? `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(r.referrer)}</a>`
+ : escapeHtml(r.referrer);
+ return `<tr>
+ <td>${name}</td>
+ <td class="num" title="${escapeAttr(fmt(r.count))}">${escapeHtml(fmtShort(r.count))}</td>
+ <td class="num" title="${escapeAttr(fmt(r.uniques))}">${escapeHtml(fmtShort(r.uniques))}</td>
+ </tr>`;
+ }).join('');
}
if (paths.length === 0) {
pathBody.innerHTML = '<tr><td colspan="3" class="empty">no path data yet</td></tr>';
} else {
pathBody.innerHTML = paths.map(p => `
- <tr><td><a href="https://github.com/mrbizarro/phosphene${escapeAttr(p.path)}"
+ <tr><td><a href="https://github.com${escapeAttr(p.path)}"
target="_blank" rel="noopener">${escapeHtml(p.path)}</a></td>
- <td class="num">${fmt(p.count)}</td>
- <td class="num">${fmt(p.uniques)}</td></tr>
+ <td class="num" title="${escapeAttr(fmt(p.count))}">${escapeHtml(fmtShort(p.count))}</td>
+ <td class="num" title="${escapeAttr(fmt(p.uniques))}">${escapeHtml(fmtShort(p.uniques))}</td></tr>
`).join('');
}
}
- function escapeHtml(s) {
- return String(s ?? '').replace(/[&<>"']/g, c =>
- ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])
- );
- }
- function escapeAttr(s) { return escapeHtml(s); }
-
function renderMeta(rows) {
const last = rows[rows.length - 1];
const meta = document.getElementById('meta');
- if (!last) { meta.textContent = 'no data yet — first snapshot due 03:17 UTC'; return; }
+ if (!last) {
+ meta.textContent = 'no data yet — first snapshot due 03:17 UTC';
+ return;
+ }
+ const local = new Date(last.fetched_at);
+ const localStr = Number.isFinite(local.getTime()) ? local.toString() : last.fetched_at;
meta.innerHTML = `
- <strong>${rows.length}</strong> daily snapshots ·
- last refresh <strong>${escapeHtml(dayAgo(last.fetched_at))}</strong>
- (${escapeHtml(last.fetched_at)}) ·
- <a href="https://github.com/mrbizarro/phosphene" target="_blank" rel="noopener">repo ↗</a>
+ <strong>${rows.length}</strong> ${rows.length === 1 ? 'snapshot' : 'daily snapshots'} ·
+ last refresh <span title="${escapeAttr(last.fetched_at)} (UTC)&#10;${escapeAttr(localStr)} (local)"><strong>${escapeHtml(dayAgo(last.fetched_at))}</strong></span> ·
+ <a href="${REPO_URL}" target="_blank" rel="noopener">repo ↗</a>
`;
}
- (async function main() {
+ // ---- period chips --------------------------------------------------
+ function initChips() {
+ const saved = localStorage.getItem(LS_PERIOD);
+ if (saved && ['7','30','90','all'].includes(saved)) currentPeriod = saved;
+ document.querySelectorAll('.chip').forEach(b => {
+ b.setAttribute('aria-pressed', String(b.dataset.period === currentPeriod));
+ b.addEventListener('click', () => {
+ currentPeriod = b.dataset.period;
+ localStorage.setItem(LS_PERIOD, currentPeriod);
+ document.querySelectorAll('.chip').forEach(x =>
+ x.setAttribute('aria-pressed', String(x === b)));
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ });
+ });
+ }
+
+ // ---- error state ---------------------------------------------------
+ function showError(err) {
+ // Hide the loading/skeleton sections.
+ document.getElementById('sec-now').hidden = true;
+ document.getElementById('sec-over-time').hidden = true;
+ document.getElementById('sec-traffic').hidden = true;
+
+ const meta = document.getElementById('meta');
+ meta.innerHTML = `<span style="color:var(--bad)">could not load stats</span>`;
+
+ const mount = document.getElementById('error-mount');
+ mount.hidden = false;
+ mount.innerHTML = `
+ <div class="error-card" role="alert">
+ <p class="err-title">Could not load stats-data.jsonl</p>
+ <p class="err-msg">${escapeHtml(err.message || String(err))}</p>
+ <p style="color:var(--text-dim);font-size:12px;margin:0 0 12px">
+ URL: <a href="${JSONL_URL}" target="_blank" rel="noopener">${JSONL_URL}</a>
+ (relative to this page)
+ </p>
+ <div class="err-actions">
+ <button class="btn" id="retry-btn" type="button">Try again</button>
+ <a class="btn ghost" href="${RAW_URL}" target="_blank" rel="noopener">View on GitHub ↗</a>
+ </div>
+ </div>`;
+ document.getElementById('retry-btn').addEventListener('click', () => {
+ mount.hidden = true;
+ document.getElementById('sec-now').hidden = false;
+ document.getElementById('sec-over-time').hidden = false;
+ document.getElementById('sec-traffic').hidden = false;
+ main();
+ });
+ }
+
+ // ---- lazy chart init via IntersectionObserver ----------------------
+ /**
+ * Defers main-section chart rendering until the section scrolls into
+ * view. The "Right now" cards (+ their sparklines) draw immediately,
+ * since they're above the fold and small.
+ */
+ function lazyMountCharts() {
+ const section = document.getElementById('sec-over-time');
+ if (!section) return;
+ let drawn = false;
+ const draw = () => {
+ if (drawn) return;
+ drawn = true;
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ };
+ if (!('IntersectionObserver' in window)) {
+ // Fallback for very old browsers.
+ draw();
+ return;
+ }
+ const io = new IntersectionObserver(entries => {
+ for (const e of entries) {
+ if (e.isIntersecting) {
+ draw();
+ io.disconnect();
+ return;
+ }
+ }
+ }, { rootMargin: '200px' });
+ io.observe(section);
+ // Also redraw on chip change after initial paint.
+ }
+
+ // ---- main flow -----------------------------------------------------
+ async function main() {
try {
- const rows = await loadRows();
- rows.sort((a, b) => (a.date || '') < (b.date || '') ? -1 : 1);
- renderMeta(rows);
- if (!rows.length) return;
- renderCards(rows);
- renderCharts(rows);
- renderTables(rows);
+ allRows = await loadRows();
+ renderMeta(allRows);
+ if (!allRows.length) {
+ // Render empty cards row with a friendly message.
+ document.getElementById('cards').setAttribute('aria-busy', 'false');
+ document.getElementById('cards').innerHTML =
+ '<div class="empty" style="grid-column:1 / -1">no snapshots yet — first fetch due 03:17 UTC</div>';
+ return;
+ }
+ renderCards(allRows);
+ renderTables(allRows);
+ lazyMountCharts();
} catch (e) {
- document.getElementById('meta').innerHTML =
- `<span style="color:var(--bad)">could not load stats-data.jsonl: ${escapeHtml(e.message)}</span>`;
+ console.error(e);
+ showError(e);
}
- })();
+ }
+
+ // ---- boot ----------------------------------------------------------
+ initTheme();
+ initChips();
+ main();
</script>
</body>
</html>
diff --git a/scripts/fetch_repo_stats.py b/scripts/fetch_repo_stats.py
index ca8682c..e725de1 100644
--- a/scripts/fetch_repo_stats.py
+++ b/scripts/fetch_repo_stats.py
@@ -12,34 +12,77 @@ Why a custom script (not the off-the-shelf `github-repo-stats` Action):
- Schema lives next to us; we can add fields later without renegotiating
with an upstream marketplace action.
-Output schema (one JSON object per UTC day, newline-delimited):
+------------------------------------------------------------------------
+RUNNING LOCALLY
+------------------------------------------------------------------------
+
+ GITHUB_TOKEN=$(gh auth token) python3 scripts/fetch_repo_stats.py
+ GITHUB_TOKEN=$(gh auth token) python3 scripts/fetch_repo_stats.py --dry-run
+ GITHUB_TOKEN=$(gh auth token) python3 scripts/fetch_repo_stats.py \
+ --repo owner/name
+
+Env vars:
+- GITHUB_TOKEN default token (auto-injected in GitHub Actions)
+- GH_STATS_TOKEN explicit override; wins over GITHUB_TOKEN
+- PHOSPHENE_REPO default repo override (CLI --repo wins over env)
+
+Required token scopes for the default repo:
+- public_repo / repo (Traffic API requires push access)
+- read:org (only if querying a private org repo)
+
+The classic `gh auth token` for the repo owner is sufficient.
+
+------------------------------------------------------------------------
+OUTPUT SCHEMA (one JSON object per UTC day, newline-delimited)
+------------------------------------------------------------------------
{
"date": "2026-05-22", # UTC YYYY-MM-DD (the day fetched)
"fetched_at": "...Z", # full ISO timestamp
- "clones": {"count": N, "uniques": N}, # daily-window slice
- "views": {"count": N, "uniques": N},
"stars": N, # total today
"forks": N,
- "open_issues": N,
+ "open_issues": N, # excludes PRs
+ "watchers": N, # alias for stars (GH legacy)
+ "subscribers": N, # actual GitHub "watch"
"open_prs": N,
- "watchers": N,
- "subscribers": N, # actual GitHub watch
+ # Back-compat: most-recent-day slice. Same numbers as the last
+ # element of clones_window/views_window. Kept so older dashboards
+ # don't break.
+ "clones": {"count": N, "uniques": N},
+ "views": {"count": N, "uniques": N},
+ # Full 15-day window from the Traffic API. The API window rotates
+ # daily — snapshotting this gives us a continuous record once we
+ # accumulate a few days.
+ "clones_window": [{"date": "2026-05-08", "count": N, "uniques": N}, ...],
+ "views_window": [{"date": "2026-05-08", "count": N, "uniques": N}, ...],
+ # Cumulative star count per day, derived from /stargazers. Lets a
+ # fresh dashboard show a stars curve from day 1 instead of
+ # waiting for daily snapshots to accumulate.
+ "stars_timeline": [{"date": "2024-09-12", "count": 1}, ...],
"referrers": [{"referrer": "...", "count": N, "uniques": N}, ...],
- "paths": [{"path": "...", "count": N, "uniques": N, "title": "..."}, ...]
+ "paths": [{"path": "...", "count": N, "uniques": N, "title": "..."}, ...],
+ "releases": {"total": N, "by_release": {"v1.0": N, ...}}
}
-The clones/views counts here are the SUM of the latest 24 hours of the
-Traffic API's 15-day day-array. The full 15-day curve from the API rotates
-out by tomorrow, so the only way to retain it is to snapshot daily and
-append. The dashboard reads the JSONL append-only.
+Schema invariants:
+- `date` is UTC YYYY-MM-DD, lexicographic-sortable.
+- New fields may be added; existing field names/shapes must not change.
+- stars_timeline is cumulative (not per-day). The dashboard derives
+ deltas itself. Cumulative is monotonic, which is friendlier for
+ partial / capped fetches.
+- All counts are non-negative ints.
Idempotent: if today's date already has an entry, the new fetch REPLACES
it (so re-runs in the same UTC day don't duplicate rows).
+
+The clones/views fields are duplicated for back-compat: they're the
+SUM of the latest 24-hour entry. clones_window/views_window have the
+full 15-day curve from the same API call.
"""
from __future__ import annotations
+import argparse
import json
import os
import sys
@@ -51,7 +94,7 @@ from pathlib import Path
# ---- config --------------------------------------------------------------
-REPO = os.environ.get("PHOSPHENE_REPO", "mrbizarro/phosphene")
+DEFAULT_REPO = os.environ.get("PHOSPHENE_REPO", "mrbizarro/phosphene")
TOKEN = (
os.environ.get("GH_STATS_TOKEN") # explicit override
or os.environ.get("GITHUB_TOKEN") # default in GH Actions
@@ -60,7 +103,21 @@ TOKEN = (
OUTPUT = Path(__file__).resolve().parent.parent / "docs" / "stats-data.jsonl"
API = "https://api.github.com"
-UA = "phosphene-repo-stats/1"
+UA = "phosphene-repo-stats/2"
+
+# Star scan ceiling. /stargazers paginates 100/page so this is 50 pages.
+# A real repo crossing 5k stars deserves a deliberate revisit, not a
+# silent runaway.
+STARS_CAP = 5000
+
+# Retry policy for transient failures.
+RETRY_BACKOFFS = (2, 8, 30)
+
+# Rate-limit floor — sleep until reset if we drop below this.
+RATE_LIMIT_FLOOR = 100
+
+# Tracked across the run so we can print a single-line summary at exit.
+_last_rate_limit: dict = {"remaining": None, "limit": None, "reset": None}
if not TOKEN:
sys.stderr.write(
@@ -69,12 +126,49 @@ if not TOKEN:
)
sys.exit(1)
+
# ---- http helpers --------------------------------------------------------
-def _get(path: str, accept: str = "application/vnd.github+json") -> dict | list:
- """GET an API path. Raises on non-2xx so the Action surfaces failures."""
- url = path if path.startswith("http") else f"{API}{path}"
+def _handle_rate_limit(headers) -> None:
+ """Record current rate-limit state. If we're below the floor, sleep
+ until the documented reset time."""
+ remaining_raw = headers.get("X-RateLimit-Remaining")
+ limit_raw = headers.get("X-RateLimit-Limit")
+ reset_raw = headers.get("X-RateLimit-Reset")
+ if remaining_raw is None:
+ return
+ try:
+ remaining = int(remaining_raw)
+ except (TypeError, ValueError):
+ return
+ try:
+ limit = int(limit_raw) if limit_raw is not None else None
+ except (TypeError, ValueError):
+ limit = None
+ try:
+ reset = int(reset_raw) if reset_raw is not None else None
+ except (TypeError, ValueError):
+ reset = None
+ _last_rate_limit["remaining"] = remaining
+ _last_rate_limit["limit"] = limit
+ _last_rate_limit["reset"] = reset
+
+ if remaining < RATE_LIMIT_FLOOR and reset:
+ now = int(time.time())
+ wait = max(0, reset - now) + 2 # small cushion
+ # Cap absurd waits so a misconfigured token doesn't hang CI.
+ wait = min(wait, 3600)
+ sys.stderr.write(
+ f" rate-limit low: {remaining}/{limit} — sleeping {wait}s "
+ f"until reset\n"
+ )
+ time.sleep(wait)
+
+
+def _do_request(url: str, accept: str):
+ """Single HTTP request. Returns (parsed_body, headers).
+ Raises HTTPError on non-2xx and URLError on network failure."""
req = urllib.request.Request(
url,
headers={
@@ -84,17 +178,65 @@ def _get(path: str, accept: str = "application/vnd.github+json") -> dict | list:
"X-GitHub-Api-Version": "2022-11-28",
},
)
- try:
- with urllib.request.urlopen(req, timeout=20) as resp:
- return json.loads(resp.read())
- except urllib.error.HTTPError as exc:
- body = exc.read().decode("utf-8", errors="replace")
- sys.stderr.write(f"HTTP {exc.code} on {url}: {body[:300]}\n")
- raise
+ with urllib.request.urlopen(req, timeout=20) as resp:
+ body = resp.read()
+ headers = resp.headers
+ _handle_rate_limit(headers)
+ parsed = json.loads(body) if body else None
+ return parsed, headers
-def _get_paginated(path: str, accept: str = "application/vnd.github+json") -> list:
- """Drain ?per_page=100 pages. Used for stargazers timeline."""
+def _get(path: str, accept: str = "application/vnd.github+json", *,
+ with_headers: bool = False):
+ """GET an API path with retries. Permanent errors (4xx) fail fast;
+ transient ones (5xx / network) retry per RETRY_BACKOFFS.
+
+ If with_headers=True, returns (body, headers); else just body.
+ """
+ url = path if path.startswith("http") else f"{API}{path}"
+ last_exc: Exception | None = None
+ for attempt, backoff in enumerate((0,) + RETRY_BACKOFFS):
+ if backoff:
+ sys.stderr.write(
+ f" retry {attempt}/{len(RETRY_BACKOFFS)} after {backoff}s: {url}\n"
+ )
+ time.sleep(backoff)
+ try:
+ body, headers = _do_request(url, accept)
+ return (body, headers) if with_headers else body
+ except urllib.error.HTTPError as exc:
+ err_body = b""
+ try:
+ err_body = exc.read()
+ except Exception:
+ pass
+ # Try to record rate-limit headers even on errors.
+ _handle_rate_limit(exc.headers or {})
+ text = err_body.decode("utf-8", errors="replace")
+ if exc.code in (401, 403, 404, 422):
+ sys.stderr.write(
+ f"HTTP {exc.code} on {url}: {text[:300]}\n"
+ )
+ # 403 with rate-limit body is technically transient, but
+ # without a token-permission diff we can't distinguish a
+ # "you can't see this" 403 from a "you hit the limit"
+ # 403. Fail fast; the operator can re-run later.
+ raise
+ sys.stderr.write(
+ f"HTTP {exc.code} on {url} (transient): {text[:200]}\n"
+ )
+ last_exc = exc
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ sys.stderr.write(f"network error on {url}: {exc}\n")
+ last_exc = exc
+ assert last_exc is not None
+ raise last_exc
+
+
+def _get_paginated(path: str, accept: str = "application/vnd.github+json",
+ *, max_items: int | None = None) -> list:
+ """Drain ?per_page=100 pages. Used for stargazers timeline. Stops
+ when a page is short or when max_items is hit."""
out: list = []
page = 1
sep = "&" if "?" in path else "?"
@@ -102,11 +244,16 @@ def _get_paginated(path: str, accept: str = "application/vnd.github+json") -> li
chunk = _get(f"{path}{sep}per_page=100&page={page}", accept=accept)
if not chunk:
break
+ if not isinstance(chunk, list):
+ break
out.extend(chunk)
+ if max_items is not None and len(out) >= max_items:
+ out = out[:max_items]
+ break
if len(chunk) < 100:
break
page += 1
- if page > 200: # safety — 20k stars is enough
+ if page > 200: # absolute safety
break
return out
@@ -114,9 +261,9 @@ def _get_paginated(path: str, accept: str = "application/vnd.github+json") -> li
# ---- metric fetchers -----------------------------------------------------
-def fetch_repo() -> dict:
+def fetch_repo(repo: str) -> dict:
"""The repo object — covers stars/forks/issues/watchers."""
- r = _get(f"/repos/{REPO}")
+ r = _get(f"/repos/{repo}")
return {
"stars": int(r.get("stargazers_count", 0)),
"forks": int(r.get("forks_count", 0)),
@@ -126,43 +273,95 @@ def fetch_repo() -> dict:
}
-def fetch_open_prs() -> int:
+def fetch_open_prs(repo: str) -> int:
"""The repo's open_issues_count includes PRs. Disambiguate so the
dashboard can show issues and PRs separately."""
# /search counts are cheap and don't paginate full result lists.
- q = f"repo:{REPO}+is:pr+is:open"
+ q = f"repo:{repo}+is:pr+is:open"
r = _get(f"/search/issues?q={q}")
return int(r.get("total_count", 0))
-def fetch_clones() -> tuple[int, int]:
- """Last 24 hours of clones (the most recent entry in the 15-day array).
- Returns (count, uniques) for the most-recent day so we can graph day-
- over-day. Older entries get permanently archived in previous JSONL
- rows."""
- r = _get(f"/repos/{REPO}/traffic/clones")
+def _normalize_traffic_day(entry: dict) -> dict:
+ """Map a Traffic-API entry to our schema. `timestamp` arrives as an
+ ISO-8601 datetime (e.g. '2026-05-08T00:00:00Z'); we keep only the
+ date portion to match our row-level `date` field."""
+ ts = entry.get("timestamp", "")
+ date = ts[:10] if isinstance(ts, str) and len(ts) >= 10 else ""
+ return {
+ "date": date,
+ "count": int(entry.get("count", 0)),
+ "uniques": int(entry.get("uniques", 0)),
+ }
+
+
+def fetch_clones_window(repo: str) -> list[dict]:
+ """Full 15-day clones array. Per-day, normalized to {date,count,uniques}.
+ The Traffic API rotates this window daily, so the only way to retain
+ older days is to snapshot them into JSONL rows."""
+ r = _get(f"/repos/{repo}/traffic/clones")
days = r.get("clones") or []
- if not days:
- return 0, 0
- today = days[-1]
- return int(today.get("count", 0)), int(today.get("uniques", 0))
+ return [_normalize_traffic_day(d) for d in days]
-def fetch_views() -> tuple[int, int]:
- """Last 24h of repo page views — same shape as clones."""
- r = _get(f"/repos/{REPO}/traffic/views")
+def fetch_views_window(repo: str) -> list[dict]:
+ """Full 15-day views array — same shape as clones."""
+ r = _get(f"/repos/{repo}/traffic/views")
days = r.get("views") or []
- if not days:
- return 0, 0
- today = days[-1]
- return int(today.get("count", 0)), int(today.get("uniques", 0))
+ return [_normalize_traffic_day(d) for d in days]
+
+
+def fetch_stars_timeline(repo: str, total_stars: int) -> tuple[list[dict], bool]:
+ """Cumulative star count per UTC day.
+
+ Walks /stargazers with the star+json accept header (which adds
+ `starred_at`). We DO NOT keep `user.login` — only the timestamp.
+ Aggregates into a cumulative count: for each day where ≥1 star
+ landed, emit {date, count}. Days with no stars are omitted so
+ sparse history stays small; the dashboard can ffill itself.
+
+ Returns (timeline, partial).
+ `partial` is True if we hit STARS_CAP and bailed out — the dashboard
+ can show a "showing first N stars" note.
+ """
+ # Skip the heavy pagination if the repo is empty.
+ if total_stars <= 0:
+ return [], False
+
+ capped = total_stars > STARS_CAP
+ max_items = STARS_CAP if capped else None
+ entries = _get_paginated(
+ f"/repos/{repo}/stargazers",
+ accept="application/vnd.github.v3.star+json",
+ max_items=max_items,
+ )
+
+ # Buckets keyed by YYYY-MM-DD. Use timestamps only — no login.
+ counts_by_day: dict[str, int] = {}
+ for e in entries:
+ if not isinstance(e, dict):
+ continue
+ ts = e.get("starred_at", "")
+ if not isinstance(ts, str) or len(ts) < 10:
+ continue
+ day = ts[:10]
+ counts_by_day[day] = counts_by_day.get(day, 0) + 1
+ # Convert to cumulative timeline.
+ timeline: list[dict] = []
+ running = 0
+ for day in sorted(counts_by_day.keys()):
+ running += counts_by_day[day]
+ timeline.append({"date": day, "count": running})
-def fetch_referrers() -> list[dict]:
+ return timeline, capped
+
+
+def fetch_referrers(repo: str) -> list[dict]:
"""Top 10 referring domains over the rolling 14-day window. We snapshot
the 14d aggregate every day rather than try to derive a per-day
breakdown (the API doesn't give one)."""
- r = _get(f"/repos/{REPO}/traffic/popular/referrers")
+ r = _get(f"/repos/{repo}/traffic/popular/referrers")
if not isinstance(r, list):
return []
return [
@@ -175,10 +374,10 @@ def fetch_referrers() -> list[dict]:
]
-def fetch_paths() -> list[dict]:
+def fetch_paths(repo: str) -> list[dict]:
"""Top 10 paths viewed over the rolling 14d. Tells us which docs are
actually getting read (README vs STATE vs ROADMAP, etc)."""
- r = _get(f"/repos/{REPO}/traffic/popular/paths")
+ r = _get(f"/repos/{repo}/traffic/popular/paths")
if not isinstance(r, list):
return []
return [
@@ -192,13 +391,13 @@ def fetch_paths() -> list[dict]:
]
-def fetch_release_downloads() -> dict:
+def fetch_release_downloads(repo: str) -> dict:
"""Cumulative downloads per release asset. GitHub provides no time
series here, so we just take a snapshot — the dashboard can derive
deltas across snapshots itself. Empty when the repo has no releases
(Phosphene currently ships via Pinokio clone, not release binaries)."""
try:
- rs = _get(f"/repos/{REPO}/releases?per_page=100")
+ rs = _get(f"/repos/{repo}/releases?per_page=100")
if not isinstance(rs, list):
return {}
except urllib.error.HTTPError:
@@ -216,67 +415,184 @@ def fetch_release_downloads() -> dict:
return {"total": total, "by_release": per_release}
+# ---- summary helpers -----------------------------------------------------
+
+
+def _window_total(window: list[dict]) -> int:
+ return sum(int(d.get("count", 0)) for d in window)
+
+
+def _wow_delta(window: list[dict]) -> int:
+ """Week-over-week count delta inside the same 15-day window. Compares
+ the last 7 entries to the 7 before them. Returns 0 if we don't have
+ 14 days of data yet."""
+ if len(window) < 14:
+ return 0
+ recent = sum(int(d.get("count", 0)) for d in window[-7:])
+ prior = sum(int(d.get("count", 0)) for d in window[-14:-7])
+ return recent - prior
+
+
+def _stars_wow_delta(timeline: list[dict]) -> int:
+ """Stars gained in the last 7 UTC days, vs the 7 before. Cumulative
+ timeline → derive deltas."""
+ if len(timeline) < 2:
+ return 0
+ now = datetime.now(timezone.utc).date()
+ today_iso = now.isoformat()
+ # Find cumulative star count as of T, T-7d, T-14d. timeline is
+ # cumulative-by-day with gaps; carry-forward by using the last entry
+ # whose date <= target.
+ def cum_at(target: str) -> int:
+ last = 0
+ for entry in timeline:
+ if entry.get("date", "") <= target:
+ last = int(entry.get("count", 0))
+ else:
+ break
+ return last
+ seven = (now.toordinal() - 7)
+ fourteen = (now.toordinal() - 14)
+ seven_iso = datetime.fromordinal(seven).strftime("%Y-%m-%d")
+ fourteen_iso = datetime.fromordinal(fourteen).strftime("%Y-%m-%d")
+ recent = cum_at(today_iso) - cum_at(seven_iso)
+ prior = cum_at(seven_iso) - cum_at(fourteen_iso)
+ return recent - prior
+
+
# ---- main ----------------------------------------------------------------
-def main() -> int:
+def _parse_args(argv: list[str]) -> argparse.Namespace:
+ p = argparse.ArgumentParser(
+ description="Fetch GitHub repo stats and append a daily JSONL row.",
+ )
+ p.add_argument(
+ "--repo",
+ default=DEFAULT_REPO,
+ help=f"OWNER/NAME (default: {DEFAULT_REPO}, or $PHOSPHENE_REPO)",
+ )
+ p.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Fetch and print, but don't write the JSONL file.",
+ )
+ return p.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _parse_args(argv or sys.argv[1:])
+ repo = args.repo
+
now = datetime.now(timezone.utc)
today = now.strftime("%Y-%m-%d")
iso_now = now.strftime("%Y-%m-%dT%H:%M:%SZ")
- print(f"[{iso_now}] fetching stats for {REPO}", flush=True)
+ print(f"[{iso_now}] fetching stats for {repo}"
+ + (" (dry-run)" if args.dry_run else ""), flush=True)
- repo = fetch_repo()
- print(f" repo: {repo}", flush=True)
- open_prs = fetch_open_prs()
- repo["open_prs"] = open_prs
+ repo_obj = fetch_repo(repo)
+ print(f" repo: {repo_obj}", flush=True)
+ open_prs = fetch_open_prs(repo)
+ repo_obj["open_prs"] = open_prs
# open_issues from the repo API includes PRs — subtract to disambiguate.
- repo["open_issues"] = max(0, repo["open_issues"] - open_prs)
- print(f" prs: {open_prs} (open_issues adjusted to {repo['open_issues']})", flush=True)
+ repo_obj["open_issues"] = max(0, repo_obj["open_issues"] - open_prs)
+ print(f" prs: {open_prs} (open_issues adjusted to {repo_obj['open_issues']})",
+ flush=True)
- clones_count, clones_uniques = fetch_clones()
- views_count, views_uniques = fetch_views()
- print(f" clones today: {clones_count} ({clones_uniques} unique)", flush=True)
- print(f" views today: {views_count} ({views_uniques} unique)", flush=True)
+ clones_window = fetch_clones_window(repo)
+ views_window = fetch_views_window(repo)
+ # Back-compat: most-recent-day slice as a dict.
+ if clones_window:
+ last = clones_window[-1]
+ clones_today = {"count": last["count"], "uniques": last["uniques"]}
+ else:
+ clones_today = {"count": 0, "uniques": 0}
+ if views_window:
+ last = views_window[-1]
+ views_today = {"count": last["count"], "uniques": last["uniques"]}
+ else:
+ views_today = {"count": 0, "uniques": 0}
+ print(f" clones window: {len(clones_window)} days, "
+ f"total={_window_total(clones_window)}, "
+ f"today={clones_today['count']} ({clones_today['uniques']} unique)",
+ flush=True)
+ print(f" views window: {len(views_window)} days, "
+ f"total={_window_total(views_window)}, "
+ f"today={views_today['count']} ({views_today['uniques']} unique)",
+ flush=True)
- referrers = fetch_referrers()
- paths = fetch_paths()
- releases = fetch_release_downloads()
+ timeline, partial = fetch_stars_timeline(repo, repo_obj["stars"])
+ if partial:
+ print(f" stars timeline: PARTIAL — capped at {STARS_CAP} "
+ f"(repo has {repo_obj['stars']})", flush=True)
+ else:
+ print(f" stars timeline: {len(timeline)} day-buckets, "
+ f"final cum={(timeline[-1]['count'] if timeline else 0)}",
+ flush=True)
+
+ referrers = fetch_referrers(repo)
+ paths = fetch_paths(repo)
+ releases = fetch_release_downloads(repo)
print(f" referrers: {len(referrers)} paths: {len(paths)} "
f"release downloads total: {releases.get('total', 0)}", flush=True)
row = {
"date": today,
"fetched_at": iso_now,
- **repo,
- "clones": {"count": clones_count, "uniques": clones_uniques},
- "views": {"count": views_count, "uniques": views_uniques},
+ **repo_obj,
+ "clones": clones_today,
+ "views": views_today,
+ "clones_window": clones_window,
+ "views_window": views_window,
+ "stars_timeline": timeline,
"referrers": referrers,
"paths": paths,
"releases": releases,
}
- # Idempotent append: replace today's row if it already exists.
- OUTPUT.parent.mkdir(parents=True, exist_ok=True)
- existing: list[dict] = []
- if OUTPUT.exists():
- for line in OUTPUT.read_text(encoding="utf-8").splitlines():
- line = line.strip()
- if not line:
- continue
- try:
- obj = json.loads(line)
- if obj.get("date") == today:
- continue # drop today's prior row
- existing.append(obj)
- except json.JSONDecodeError:
- continue
- existing.append(row)
- OUTPUT.write_text(
- "\n".join(json.dumps(r, ensure_ascii=False) for r in existing) + "\n",
- encoding="utf-8",
+ if args.dry_run:
+ print(" dry-run: not writing JSONL", flush=True)
+ else:
+ # Idempotent append: replace today's row if it already exists.
+ OUTPUT.parent.mkdir(parents=True, exist_ok=True)
+ existing: list[dict] = []
+ if OUTPUT.exists():
+ for line in OUTPUT.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ if obj.get("date") == today:
+ continue # drop today's prior row
+ existing.append(obj)
+ except json.JSONDecodeError:
+ continue
+ existing.append(row)
+ OUTPUT.write_text(
+ "\n".join(json.dumps(r, ensure_ascii=False) for r in existing) + "\n",
+ encoding="utf-8",
+ )
+ print(f" wrote {len(existing)} rows -> "
+ f"{OUTPUT.relative_to(OUTPUT.parent.parent)}", flush=True)
+
+ # Summary line for GitHub Actions step output.
+ clones_wow = _wow_delta(clones_window)
+ views_wow = _wow_delta(views_window)
+ stars_wow = _stars_wow_delta(timeline)
+ summary = (
+ f"summary: stars={repo_obj['stars']} ({stars_wow:+d} w/w) "
+ f"clones={_window_total(clones_window)} ({clones_wow:+d} w/w) "
+ f"views={_window_total(views_window)} ({views_wow:+d} w/w) "
+ f"referrers={len(referrers)} paths={len(paths)}"
)
- print(f" wrote {len(existing)} rows → {OUTPUT.relative_to(OUTPUT.parent.parent)}",
- flush=True)
+ print(summary, flush=True)
+
+ rl = _last_rate_limit
+ if rl["remaining"] is not None:
+ print(f" rate-limit remaining: {rl['remaining']}/{rl['limit']}",
+ flush=True)
+
return 0