SLOPSHOPPER

repo-radar

A live GitHub dashboard for every repo across every account you're signed into. It installs an always-on-top desktop widget for you on first run.

panecommandtoaststatusprocessnetwork
v0.1.10MITupdated 2026-10-11J-M-Pineapple-Express/repo-radar/mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · repo-radar
│ ┃ 📡 Repo Radar ✕ › fix the failing auth test and add an audit log call │ ┃ 📡 REPO RADAR [ ↻ Refresh ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ No GitHub account found 🔌 ⎿ Read 6 lines │ ┃ Sign in with the GitHub CLI, then press ⏺ Update(src/auth.ts) │ ┃ Refresh: ⎿ Added 2 lines, removed 1 line │ ┃ gh auth login ⏺ Bash(bun test) │ ┃ No gh? Paste a token into Repo Radar's ⎿ 3 pass, 1 fail │ ┃ github_token setting in /config. │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /repos │ ⎿ repo-radar: Repo Radar opened docked on the right. Esc closes it │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · 📡 Repo Radar
📡 REPO RADAR [ ↻ Refresh ] No GitHub account found 🔌 Sign in with the GitHub CLI, then press Refresh: gh auth login No gh? Paste a token into Repo Radar's github_token setting in /config.
README

📡 Repo Radar

A GitHub dashboard for people who ship Claude Code plugins and small apps. It comes in two parts that share one data file:

  • The widget: a small always-on-top window for Windows and macOS.
  • The mod: a Claude Code plugin with a /repos pane, toasts, and /repos widget to open the widget.

Install the mod and you get both. On your first session it downloads the widget's installer for you. After that, the widget opens beside every session.

It sweeps every repo of every account the GitHub CLI is signed into.

What it shows

  • ⚠️ Needs Attention, your to-do list:
  • failing CI
  • Dependabot security alerts
  • releases missing files the previous release had
  • plugin versions that don't match across plugin.json, your marketplace's copy and the latest release
  • issues waiting on your reply, longest wait first
  • open PRs
  • work committed since your last release
  • plugins and marketplaces that fail claude plugin validate, checked on what's on GitHub
  • READMEs that name an older version than your latest release
  • public repos missing a description, topics, a license or a README, so people can find them

Each item has a button that opens Claude Code in that repo with the task written out: 🔧 Fix, 👀 Review or 🚢 Ship it. Claude works in a branch and asks before it pushes, comments, merges or publishes. ✓ Done hides an item, and ✓ Close closes an issue.

  • Tiles and a 30-day chart: stars, lifetime clones, release downloads and CI status. Clones count outside people only: unique cloners, without your CI builds or your own machine.
  • 🧩 Plugins · 📦 Apps · 🗂 Other: your repos, sorted by what they are. Each row shows only the numbers that matter for its kind, plus this week's trend. Open a repo for its chart, where visitors came from, and the pages they read.
  • ⭐ Following: repos you've starred or watch. New releases get a NEW badge, and Windows or macOS notifies you about repos you watch. If a repo has a plugin, marketplace or skill, Install shows the exact commands first, then runs them.
  • Lifetime history: GitHub keeps only 14 days of traffic. Repo Radar saves every day of clones, views and referrers, so your totals keep growing.
  • Notifications for new stars, forks, issues and releases, and 🎉 milestones.

Install

In Claude Code:

/plugin marketplace add J-M-Pineapple-Express/repo-radar
/plugin install repo-radar@repo-radar

Start a new session and the widget's installer opens: click through it, and the widget appears. From then on it opens with each session. It updates itself on Windows, and points you to the new release on macOS.

  • /repos opens the pane in Claude Code, with the same ⚠️ Needs Attention list.
  • /repos widget opens the widget, or installs it if it isn't there.
  • Don't want it opening every session? Turn off Open the widget with each session in /config.
  • On macOS, drag Repo Radar to Applications. The first time, right-click it and choose Open, since the app isn't signed.

Prefer the widget alone? Download it from Releases: RepoRadar-Setup-x.y.z.exe for Windows, RepoRadar-x.y.z-arm64.dmg (Apple silicon) or -x64.dmg (Intel) for macOS.

Both need the GitHub CLI signed in: run gh auth login. Sign in to more than one account and Repo Radar shows them all.

Privacy

Everything stays on your computer. Repo Radar talks only to GitHub, using the tokens gh already has, and never writes them to disk. Your history lives in ~/.claude/repo-radar/data.json.

Build it yourself

cd widget
npm install
npm start          # run the widget
npm run dist:win   # or dist:mac, to build installers

The mod is in mod/. Load it while developing with claude --plugin-dir mod.

License

MIT

Source 3 files
hooks/register.tsx 827 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { Account, Health, Ledger, Needs, Repo, Snapshot, Status, Traffic } from '../types'
5import { ago, changes, compact, dayKeys, describe, importTracker, lifetime, mergeHistory, shortDate, missingAssets, perDay, record, repoKey, summarize, toLedger } from './lib'
6import type { DayRow, History } from './lib'
7
8const PANE = 'repo-radar'
9const REFRESH_MS = 10 * 60 * 1000
10const TICK_MS = 8 * 1000
11const PAGE_LIMIT = 5
12const PREVIEW = 8
13const STALE_DAYS = 90
14const TRAFFIC_MS = 60 * 60 * 1000 // GitHub updates traffic about hourly
15const TRAFFIC_LIMIT = 300 // per account, most recently pushed first: in practice every repo
16const TRAFFIC_BATCH = 10 // repos fetched at once
17const AWAY_MS = 30 * 60 * 1000
18const TOAST_LIMIT = 3
19
20const snapshot = atom({ plugin: 'repo-radar', key: 'snapshot' } as const, null)
21const status = atom({ plugin: 'repo-radar', key: 'status' } as const, 'idle')
22const message = atom({ plugin: 'repo-radar', key: 'message' } as const, '')
23const expanded = atom({ plugin: 'repo-radar', key: 'expanded' } as const, [])
24const digest = atom({ plugin: 'repo-radar', key: 'digest' } as const, '')
25const hiddenColumns = atom({ plugin: 'repo-radar', key: 'hidden' } as const, [])
26const needs = atom({ plugin: 'repo-radar', key: 'needs' } as const, null)
27const NEEDS_PREVIEW = 5
28
29const DOT: Record<Health, { glyph: string; color: string }> = {
30  green: { glyph: '●', color: 'green' },
31  yellow: { glyph: '●', color: 'yellow' },
32  red: { glyph: '●', color: 'red' },
33  archived: { glyph: '○', color: 'gray' },
34}
35
36const QUERY = `query($after: String) {
37  viewer {
38    login
39    repositories(first: 100, after: $after,
40      ownerAffiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER],
41      orderBy: { field: PUSHED_AT, direction: DESC }) {
42      pageInfo { hasNextPage endCursor }
43      nodes {
44        name url isPrivate isFork isArchived pushedAt viewerPermission
45        owner { login }
46        stargazerCount forkCount
47        issues(states: OPEN) { totalCount }
48        pullRequests(states: OPEN) { totalCount }
49        latestRelease { tagName }
50        primaryLanguage { name color }
51        defaultBranchRef { target { ... on Commit { statusCheckRollup { state } } } }
52      }
53    }
54  }
55}`
56
57type Login = { host: string; login: string; token: string }
58type Engine = EngineInterface
59
60const graphqlUrl = (host: string) =>
61  host === 'github.com' ? 'https://api.github.com/graphql' : `https://${host}/api/graphql`
62
63const restBase = (host: string) => (host === 'github.com' ? 'https://api.github.com' : `https://${host}/api/v3`)
64
65const restHeaders = (token: string) => ({
66  Authorization: `bearer ${token}`,
67  Accept: 'application/vnd.github+json',
68  'User-Agent': 'repo-radar',
69})
70
71const winPath = (path: string) => path.replaceAll('/', '\\')
72
73/** The file the widget shares: ~/.claude/repo-radar/data.json. */
74async function sharedPath($: Engine): Promise<string | null> {
75  const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
76  return home ? `${home}/.claude/repo-radar/data.json` : null
77}
78
79type Shared = { history?: History; ledger?: Ledger | null; watchedSince?: string | null; prefs?: Record<string, unknown>; needs?: Needs | null } & Record<string, unknown>
80
81/** The widget's outside clones per repo and day: uniques less CI builds and this machine. */
82const outsideDays = (shared: Shared | null): Record<string, Record<string, number>> =>
83  Object.fromEntries(
84    Object.entries(shared?.history ?? {}).map(([key, e]) => [key, ((e as { outside?: Record<string, number> }).outside ?? {})]),
85  )
86
87async function loadShared($: Engine): Promise<Shared | null> {
88  const file = await sharedPath($)
89  if (!file || !(await $.fs.exists(file))) return null
90  // Both sides move their writes into place; a second read covers an unlucky moment anyway.
91  for (let i = 0; i < 2; i++) {
92    try {
93      return JSON.parse(await $.fs.read(file)) as Shared
94    } catch {
95      await $.clock.sleep(200)
96    }
97  }
98  return null
99}
100
101/** Merges our history, ledger and prefs into the shared file, leaving the widget's own fields alone. */
102async function saveShared($: Engine, patch: { history?: History; ledger?: Ledger; watchedSince?: string; hiddenColumns?: string[] }): Promise<void> {
103  const file = await sharedPath($)
104  if (!file) return
105  try {
106    const data: Shared = (await loadShared($)) ?? { version: 1, accounts: [], fetchedAt: 0, trafficAt: 0 }
107    if (patch.history) data.history = mergeHistory(data.history ?? {}, patch.history)
108    if (patch.ledger && (!data.ledger || patch.ledger.at > data.ledger.at)) data.ledger = patch.ledger
109    if (patch.watchedSince && (!data.watchedSince || patch.watchedSince < data.watchedSince)) data.watchedSince = patch.watchedSince
110    if (patch.hiddenColumns) data.prefs = { ...data.prefs, hiddenColumns: patch.hiddenColumns }
111    // Write beside it, then move into place, so the widget never reads half a file.
112    const tmp = `${file}.mod.tmp`
113    await $.fs.write(tmp, JSON.stringify(data))
114    const isWindows = file.includes('\\') || /^[A-Za-z]:/.test(file)
115    await $.process.run(isWindows ? ['cmd', '/c', 'move', '/y', winPath(tmp), winPath(file)] : ['mv', '-f', tmp, file])
116  } catch {
117    // the widget is a bonus; the mod's own store still has everything
118  }
119}
120
121const WIDGET_REPO = 'J-M-Pineapple-Express/repo-radar'
122const WIDGET_RELEASES = `https://github.com/${WIDGET_REPO}/releases/latest`
123const NO_WIDGET = 'missing'
124
125/**
126 * Starts the widget without waiting on it. The installed app first; while building,
127 * the widget folder beside this mod. `start` (Windows) and `open` (Mac) detach it,
128 * so a mod reload never closes it. `quiet` leaves a widget that's already open where it is.
129 * Returns NO_WIDGET when there's nothing to start.
130 */
131async function startWidget($: Engine, quiet = false): Promise<string> {
132  const root = $.plugin.root.replaceAll('\\', '/').replace(/\/$/, '').replace(/\/\.claude-plugin$/, '')
133  const dev = `${root.slice(0, root.lastIndexOf('/'))}/widget`
134  const ok = '📡 Repo Radar widget launched.'
135  const flags = quiet ? ['--quiet'] : []
136  const failed = (r: { exitCode: number; stderr: string }) => `Couldn't launch the widget: ${r.stderr.trim() || `exit ${r.exitCode}`}`
137  const local = (await $.env.get('LOCALAPPDATA')) ?? ''
138  if (local) {
139    const installed = `${local}/Programs/Repo Radar/Repo Radar.exe`
140    const devElectron = `${dev}/node_modules/electron/dist/electron.exe`
141    const argv = (await $.fs.exists(installed)) ? [installed] : (await $.fs.exists(devElectron)) ? [devElectron, dev] : null
142    if (!argv) return NO_WIDGET
143    const r = await $.process.run(['cmd', '/c', 'start', 'Repo Radar', ...argv.map(winPath), ...flags])
144    return r.exitCode === 0 ? ok : failed(r)
145  }
146  // Mac: `open -a` finds the app wherever it was dragged (Applications, ~/Applications).
147  // `-g` keeps a running app in the background (open hands no arguments to a running app).
148  const app = await $.process.run(['open', ...(quiet ? ['-g'] : []), '-a', 'Repo Radar']).catch(() => null)
149  if (app?.exitCode === 0) return ok
150  const devApp = `${dev}/node_modules/electron/dist/Electron.app`
151  if (await $.fs.exists(devApp)) {
152    const r = await $.process.run(['open', '-a', devApp, '--args', dev, ...flags])
153    return r.exitCode === 0 ? ok : failed(r)
154  }
155  return NO_WIDGET
156}
157
158/**
159 * Downloads the widget from this repo's latest release and opens its installer:
160 * the Setup .exe on Windows, the .dmg for this Mac's chip. The installer asks before it installs.
161 */
162async function installWidget($: Engine): Promise<string> {
163  const manual = `Get it from ${WIDGET_RELEASES}`
164  try {
165    const res = await $.http.fetch(`https://api.github.com/repos/${WIDGET_REPO}/releases/latest`, {
166      headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'repo-radar' },
167    })
168    if (!res.ok) return `Couldn't reach the widget's releases (HTTP ${res.status}). ${manual}`
169    const assets = (JSON.parse(res.text).assets ?? []) as { name: string; browser_download_url: string }[]
170    const isWindows = Boolean(await $.env.get('LOCALAPPDATA'))
171    let pattern: RegExp
172    if (isWindows) {
173      pattern = /^RepoRadar-Setup-[\d.]+\.exe$/
174    } else {
175      const arch = (await $.process.run(['uname', '-m'])).stdout.trim() === 'arm64' ? 'arm64' : 'x64'
176      const os = (await $.process.run(['uname', '-s'])).stdout.trim()
177      if (os !== 'Darwin') return `The widget is built for Windows and Mac. ${manual}`
178      pattern = new RegExp(`^RepoRadar-[\\d.]+-${arch}\\.dmg$`)
179    }
180    const asset = assets.find(a => pattern.test(a.name))
181    if (!asset) return `The latest release has no installer for this computer. ${manual}`
182    const tmp = ((await $.env.get('TEMP')) || (await $.env.get('TMPDIR')) || '/tmp').replace(/[\\/]$/, '')
183    const file = isWindows ? winPath(`${tmp}/${asset.name}`) : `${tmp}/${asset.name}`
184    $.ui.toast(`📡 Downloading the Repo Radar widget (${asset.name})…`, { timeoutMs: 8000 })
185    const get = await $.process.run([isWindows ? 'curl.exe' : 'curl', '-fsSL', '-o', file, asset.browser_download_url], { timeoutMs: 10 * 60 * 1000 })
186    if (get.exitCode !== 0) return `The download failed: ${get.stderr.trim() || `exit ${get.exitCode}`}. ${manual}`
187    const run = await $.process.run(isWindows ? ['cmd', '/c', 'start', '', file] : ['open', file])
188    if (run.exitCode !== 0) return `Downloaded ${file} but couldn't open it. Open it yourself to install.`
189    return isWindows
190      ? '📡 The Repo Radar installer is open. Finish it and the widget starts.'
191      : '📡 The Repo Radar disk image is open: drag Repo Radar to Applications. The first time, right-click it and choose Open (the app isn’t signed).'
192  } catch (err) {
193    return `Couldn't get the widget: ${err instanceof Error ? err.message : err}. ${manual}`
194  }
195}
196
197/** /repos widget: start it, or install it first. */
198async function launchWidget($: Engine): Promise<string> {
199  const r = await startWidget($)
200  return r === NO_WIDGET ? installWidget($) : r
201}
202
203/**
204 * Session start: open the widget beside the session. The first time it isn't installed,
205 * offer it once with the installer; after that, /repos widget installs it.
206 */
207async function widgetAtStart($: Engine): Promise<void> {
208  const r = await startWidget($, true)
209  if (r !== NO_WIDGET) return
210  if (await $.store.get('widgetOffered')) return
211  await $.store.set('widgetOffered', true)
212  $.ui.toast(await installWidget($), { timeoutMs: 12000 })
213}
214
215async function ghLogins($: Engine): Promise<{ host: string; login: string }[]> {
216  try {
217    const json = await $.process.run(['gh', 'auth', 'status', '--json', 'hosts'])
218    if (json.exitCode === 0) {
219      const hosts = JSON.parse(json.stdout).hosts as Record<string, { state: string; host: string; login: string }[]>
220      return Object.values(hosts)
221        .flat()
222        .filter(a => a.state === 'success')
223        .map(a => ({ host: a.host, login: a.login }))
224    }
225    // Older gh: no --json on auth status, so read the human output.
226    const text = await $.process.run(['gh', 'auth', 'status'])
227    const out = `${text.stdout}\n${text.stderr}`
228    return [...out.matchAll(/Logged in to (\S+) (?:account|as) ([\w-]+)/g)].map(m => ({ host: m[1]!, login: m[2]! }))
229  } catch {
230    return [] // gh not installed
231  }
232}
233
234async function discover($: Engine, fallbackToken: string): Promise<Login[]> {
235  const logins: Login[] = []
236  for (const { host, login } of await ghLogins($)) {
237    try {
238      const r = await $.process.run(['gh', 'auth', 'token', '--hostname', host, '--user', login])
239      if (r.exitCode === 0 && r.stdout.trim()) logins.push({ host, login, token: r.stdout.trim() })
240    } catch {
241      // skip an account whose token can't be read
242    }
243  }
244  if (logins.length === 0 && fallbackToken) logins.push({ host: 'github.com', login: '', token: fallbackToken })
245  return logins
246}
247
248function toRepo(node: any, now: number): Repo {
249  const ci = node.defaultBranchRef?.target?.statusCheckRollup?.state
250  const stale = node.pushedAt && now - Date.parse(node.pushedAt) > STALE_DAYS * 86400 * 1000
251  const health: Health = node.isArchived
252    ? 'archived'
253    : ci === 'FAILURE' || ci === 'ERROR'
254      ? 'red'
255      : stale
256        ? 'yellow'
257        : 'green'
258  return {
259    name: node.name,
260    owner: node.owner.login,
261    url: node.url,
262    isPrivate: node.isPrivate,
263    isFork: node.isFork,
264    stars: node.stargazerCount,
265    forks: node.forkCount,
266    issues: node.issues.totalCount,
267    prs: node.pullRequests.totalCount,
268    release: node.latestRelease?.tagName ?? null,
269    pushedAt: node.pushedAt,
270    language: node.primaryLanguage?.name ?? null,
271    languageColor: node.primaryLanguage?.color ?? null,
272    health,
273    canPush: ['ADMIN', 'MAINTAIN', 'WRITE'].includes(node.viewerPermission),
274  }
275}
276
277async function fetchAccount($: Engine, who: Login, now: number): Promise<Account> {
278  const repos: Repo[] = []
279  let login = who.login
280  let after: string | null = null
281  for (let page = 0; page < PAGE_LIMIT; page++) {
282    const res = await $.http.fetch(graphqlUrl(who.host), {
283      method: 'POST',
284      headers: { Authorization: `bearer ${who.token}`, 'Content-Type': 'application/json', 'User-Agent': 'repo-radar' },
285      body: JSON.stringify({ query: QUERY, variables: { after } }),
286    })
287    const body = JSON.parse(res.text)
288    if (!res.ok || body.errors) {
289      const why = body.errors?.[0]?.message ?? body.message ?? `HTTP ${res.status}`
290      return { host: who.host, login: login || '?', repos, error: why }
291    }
292    const conn = body.data.viewer.repositories
293    login = body.data.viewer.login
294    repos.push(...conn.nodes.map((n: any) => toRepo(n, now)))
295    if (!conn.pageInfo.hasNextPage) break
296    after = conn.pageInfo.endCursor
297  }
298  return { host: who.host, login, repos }
299}
300
301function tickerLines(snap: Snapshot): string[] {
302  const all = snap.accounts.flatMap(a => a.repos)
303  const live = all.filter(r => r.health !== 'archived')
304  const red = live.filter(r => r.health === 'red')
305  const stars = all.reduce((n, r) => n + r.stars, 0)
306  const forks = all.reduce((n, r) => n + r.forks, 0)
307  const issues = live.reduce((n, r) => n + r.issues, 0)
308  const prs = live.reduce((n, r) => n + r.prs, 0)
309  const lines = [
310    `${all.length} repos · ⭐ ${compact(stars)} · 🍴 ${compact(forks)}`,
311    `🐛 ${issues} open issues · 🔀 ${prs} open PRs`,
312  ]
313  if (red.length) lines.push(`🔴 CI failing: ${red.slice(0, 3).map(r => r.name).join(', ')}${red.length > 3 ? '…' : ''}`)
314  const top = [...all].sort((a, b) => b.stars - a.stars)[0]
315  if (top && top.stars > 0) lines.push(`🏆 Top repo: ${top.name} (⭐ ${compact(top.stars)})`)
316  return lines
317}
318
319async function fetchTraffic($: Engine, who: Login, r: Repo): Promise<{ clones: DayRow[]; views: DayRow[] } | undefined> {
320  const base = `${restBase(who.host)}/repos/${r.owner}/${r.name}/traffic`
321  const [c, v] = await Promise.all([
322    $.http.fetch(`${base}/clones`, { headers: restHeaders(who.token) }),
323    $.http.fetch(`${base}/views`, { headers: restHeaders(who.token) }),
324  ])
325  if (!c.ok || !v.ok) return undefined
326  return { clones: JSON.parse(c.text).clones ?? [], views: JSON.parse(v.text).views ?? [] }
327}
328
329/**
330 * Fetches the freshest 14 days for every repo we can push to and folds them into the lifetime history.
331 * GitHub keeps only 14 days, so a repo skipped here loses days for good. Batched to stay polite.
332 */
333async function addTraffic($: Engine, who: Login, acct: Account, history: History): Promise<void> {
334  const picks = acct.repos.filter(r => r.canPush && r.health !== 'archived').slice(0, TRAFFIC_LIMIT)
335  for (let i = 0; i < picks.length; i += TRAFFIC_BATCH) {
336    await Promise.all(
337      picks.slice(i, i + TRAFFIC_BATCH).map(async r => {
338        try {
339          const rows = await fetchTraffic($, who, r)
340          if (!rows) return
341          const entry = (history[repoKey(r.owner, r.name)] ??= { clones: {}, views: {} })
342          record(entry.clones, rows.clones)
343          record(entry.views, rows.views)
344        } catch {
345          // traffic is a bonus; a failure leaves the row without it
346        }
347      }),
348    )
349  }
350}
351
352/**
353 * Gives every repo with history its lifetime totals and recent clone days. Where the widget
354 * worked out outside clones for a day, that count stands in for the raw one.
355 */
356function withLifetime(snap: Snapshot, history: History, outside: Record<string, Record<string, number>> = {}): Snapshot {
357  const keys = dayKeys(snap.fetchedAt)
358  const accounts = snap.accounts.map(a => ({
359    ...a,
360    repos: a.repos.map(r => {
361      const key = repoKey(r.owner, r.name)
362      const raw = history[key]
363      if (!raw) return r
364      const entry = { ...raw, clones: { ...raw.clones, ...outside[key] } }
365      const life = lifetime(entry)
366      const recent = Object.entries(entry.clones).map(([timestamp, count]) => ({ timestamp, count }))
367      const traffic: Traffic = { clones: perDay(recent, keys), clonesLifetime: life.clones, viewsLifetime: life.views, since: life.since }
368      return { ...r, traffic }
369    }),
370  }))
371  return { ...snap, accounts }
372}
373
374async function importHistory($: Engine, fallbackToken: string, source: string): Promise<string> {
375  const src = source.trim()
376  if (!src) {
377    return [
378      'Usage: /repos-import <file>  or  /repos-import <owner/repo>:<path>',
379      'The file is JSON: { "by_repo": { "owner/name": { "days": { "YYYY-MM-DD": clones } } } }',
380    ].join('\n')
381  }
382  let text: string
383  const remote = /^([\w.-]+\/[\w.-]+):(.+)$/.exec(src)
384  if (remote) {
385    const logins = await discover($, fallbackToken)
386    const who = logins.find(l => l.host === 'github.com') ?? logins[0]
387    if (!who) return 'No GitHub account found to read that file with.'
388    const res = await $.http.fetch(`${restBase(who.host)}/repos/${remote[1]}/contents/${remote[2]}`, {
389      headers: { ...restHeaders(who.token), Accept: 'application/vnd.github.raw' },
390    })
391    if (!res.ok) return `Couldn't read ${src} (HTTP ${res.status}).`
392    text = res.text
393  } else {
394    text = await $.fs.read(src)
395  }
396  const history = ((await $.store.get('history')) as History | undefined) ?? {}
397  let merged: { repos: number; days: number }
398  try {
399    merged = importTracker(history, JSON.parse(text))
400  } catch (err) {
401    return `Couldn't import ${src}: ${err instanceof Error ? err.message : err}`
402  }
403  await $.store.set('history', history)
404  await saveShared($, { history })
405  const shared = await loadShared($)
406  const snap = await read($, snapshot)
407  if (snap) await update($, snapshot, () => withLifetime(snap, history, outsideDays(shared)))
408  return `📥 Imported ${merged.days} days of clone history across ${merged.repos} repos. Lifetime totals updated.`
409}
410
411async function checkRelease($: Engine, who: Login, r: Repo): Promise<string> {
412  const res = await $.http.fetch(`${restBase(who.host)}/repos/${r.owner}/${r.name}/releases?per_page=5`, {
413    headers: restHeaders(who.token),
414  })
415  if (!res.ok) return `⚠ ${r.name}: couldn't read releases (HTTP ${res.status})`
416  const releases = (JSON.parse(res.text) as any[]).filter(x => !x.draft)
417  if (releases.length === 0) return `· ${r.name}: no published releases`
418  const [latest, previous] = releases
419  const names = (x: any): string[] => (x.assets ?? []).map((a: any) => a.name)
420  const broken = (latest.assets ?? []).filter((a: any) => a.state !== 'uploaded' || a.size === 0).map((a: any) => a.name)
421  const missing = previous ? missingAssets(names(latest), names(previous)) : []
422  const count = names(latest).length
423  if (missing.length === 0 && broken.length === 0) {
424    return `✅ ${r.name} ${latest.tag_name}: ${count} asset${count === 1 ? '' : 's'}${previous ? `, matches ${previous.tag_name}` : ''}`
425  }
426  const lines = [`❌ ${r.name} ${latest.tag_name}: ${count} asset${count === 1 ? '' : 's'}`]
427  for (const n of missing) lines.push(`   missing (was in ${previous.tag_name}): ${n}`)
428  for (const n of broken) lines.push(`   broken upload: ${n}`)
429  return lines.join('\n')
430}
431
432async function releaseCheck($: Engine, fallbackToken: string, args: string): Promise<string> {
433  const snap = await read($, snapshot)
434  if (!snap) return 'Repo Radar has not finished its first scan yet. Try again in a moment.'
435  const want = args.trim().toLowerCase()
436  const targets = snap.accounts.flatMap(a =>
437    a.repos
438      .filter(r => (want ? r.name.toLowerCase() === want || repoKey(r.owner, r.name).toLowerCase() === want : r.release))
439      .map(r => ({ acct: a, repo: r })),
440  )
441  if (targets.length === 0) return want ? `No repo named "${args.trim()}" in Repo Radar.` : 'None of your repos have releases.'
442  const logins = await discover($, fallbackToken)
443  const results = await Promise.all(
444    targets.map(({ acct, repo }) => {
445      const who = logins.find(l => l.host === acct.host && (l.login === acct.login || !l.login))
446      return who
447        ? checkRelease($, who, repo).catch(err => `⚠ ${repo.name}: ${err}`)
448        : Promise.resolve(`⚠ ${repo.name}: signed out of ${acct.login}`)
449    }),
450  )
451  const bad = results.filter(r => r.startsWith('❌')).length
452  return [`📦 Release check: ${results.length} repo${results.length === 1 ? '' : 's'}, ${bad} with problems`, ...results].join('\n')
453}
454
455async function announce($: Engine, before: Snapshot | null, snap: Snapshot, shared?: Ledger | null): Promise<void> {
456  if (before) {
457    // If the widget swept since our last look, it already notified for what it saw.
458    const base = shared && shared.at > before.fetchedAt ? shared : toLedger(before)
459    const news = changes(base, snap).map(describe)
460    news.slice(0, TOAST_LIMIT).forEach(line => $.ui.toast(line, { timeoutMs: 8000 }))
461    if (news.length > TOAST_LIMIT) $.ui.toast(`📡 +${news.length - TOAST_LIMIT} more updates`, { timeoutMs: 8000 })
462    return
463  }
464  // First scan of this session: compare with where things stood last time.
465  const ledger = (await $.store.get('ledger')) as Ledger | undefined
466  if (!ledger || snap.fetchedAt - ledger.at < AWAY_MS) return
467  const since = new Date(ledger.at).toISOString().slice(0, 10)
468  const keys = dayKeys(snap.fetchedAt)
469  const clones = snap.accounts
470    .flatMap(a => a.repos)
471    .reduce((n, r) => n + (r.traffic?.clones.reduce((m, c, i) => ((keys[i] ?? '') >= since ? m + c : m), 0) ?? 0), 0)
472  const list = changes(ledger, snap)
473  if (list.length === 0) return // nothing new: no "all quiet" card
474  const line = `🌅 While you were away (${ago(new Date(ledger.at).toISOString(), snap.fetchedAt)}): ${summarize(list, clones)}`
475  await update($, digest, () => [line, ...list.slice(0, 6).map(describe)].join('\n'))
476  $.ui.toast(line, { timeoutMs: 10000 })
477}
478
479let isRefreshing = false
480
481async function refresh($: Engine, fallbackToken: string): Promise<void> {
482  if (isRefreshing) return
483  isRefreshing = true
484  try {
485    await update($, status, () => 'loading' as Status)
486    const logins = await discover($, fallbackToken)
487    if (logins.length === 0) {
488      await update($, status, () => 'no-auth' as Status)
489      $.ui.status(undefined)
490      return
491    }
492    const now = await $.clock.now()
493    const before = await read($, snapshot)
494    const isTrafficDue = !before?.trafficAt || now - before.trafficAt > TRAFFIC_MS
495    const oldTraffic = new Map(
496      (before?.accounts ?? []).flatMap(a => a.repos).map(r => [repoKey(r.owner, r.name), r.traffic] as const),
497    )
498    const shared = await loadShared($)
499    const history = mergeHistory(((await $.store.get('history')) as History | undefined) ?? {}, shared?.history)
500    // GitHub hands back 14 days, so the first scan's window is where our own record starts.
501    let watchedSince = (await $.store.get('watchedSince')) as string | undefined
502    if (!watchedSince) {
503      watchedSince = dayKeys(now)[0]!
504      await $.store.set('watchedSince', watchedSince)
505    }
506    const accounts: Account[] = []
507    for (const who of logins) {
508      try {
509        const acct = await fetchAccount($, who, now)
510        if (isTrafficDue) await addTraffic($, who, acct, history)
511        else for (const r of acct.repos) r.traffic = oldTraffic.get(repoKey(r.owner, r.name))
512        accounts.push(acct)
513      } catch (err) {
514        accounts.push({ host: who.host, login: who.login || '?', repos: [], error: String(err) })
515      }
516    }
517    const fresh: Snapshot = { accounts, fetchedAt: now, trafficAt: isTrafficDue ? now : (before?.trafficAt ?? now), watchedSince }
518    // The widget's outside counts change between our traffic passes, so totals are worked out every time.
519    const snap = withLifetime(fresh, history, outsideDays(shared))
520    await update($, needs, () => shared?.needs ?? null)
521    if (isTrafficDue) await $.store.set('history', history)
522    // The widget may have swept more recently; its ledger then says what's already been announced.
523    const sharedLedger = shared?.ledger
524    const storeLedger = (await $.store.get('ledger')) as Ledger | undefined
525    if (sharedLedger && (!storeLedger || sharedLedger.at > storeLedger.at)) await $.store.set('ledger', sharedLedger)
526    await announce($, before, snap, shared?.ledger)
527    await update($, snapshot, () => snap)
528    await $.store.set('ledger', toLedger(snap))
529    await saveShared($, { history, ledger: toLedger(snap), watchedSince })
530    // First load: open the person's own repos; everything else starts folded.
531    await update($, expanded, list => (list.length ? list : accounts.map(a => `${a.host}/${a.login}`)))
532    await update($, status, () => 'ready' as Status)
533    await update($, message, () => '')
534  } catch (err) {
535    await update($, status, () => 'error' as Status)
536    await update($, message, () => String(err))
537  } finally {
538    isRefreshing = false
539  }
540}
541
542export const register: Register = (on, options) => {
543  const fallbackToken = String((options as Record<string, unknown>)?.github_token ?? '')
544  const opensWidget = (options as Record<string, unknown>)?.open_widget !== false
545  let tick = 0
546
547  on('session.start', async ($, e, next) => {
548    await $.command.register({ name: 'repos', description: 'Open Repo Radar, your GitHub dashboard (/repos widget opens the desktop widget)' })
549    await $.command.register({
550      name: 'release-check',
551      description: 'Check your latest releases have every asset the release before had (optionally name one repo)',
552    })
553    await $.command.register({
554      name: 'repos-import',
555      description: 'Import older clone history into Repo Radar: a JSON file path, or owner/repo:path on GitHub',
556    })
557    const savedHidden = await $.store.get('hiddenColumns')
558    if (Array.isArray(savedHidden)) await update($, hiddenColumns, () => savedHidden.map(String))
559    void refresh($, fallbackToken)
560    if (opensWidget) void widgetAtStart($)
561    $.clock.every(REFRESH_MS, () => void refresh($, fallbackToken))
562    $.clock.every(TICK_MS, async () => {
563      const snap = await read($, snapshot)
564      if (!snap) return
565      const lines = tickerLines(snap)
566      $.ui.status(lines[tick++ % lines.length])
567    })
568    return next(e)
569  })
570
571  on('command.run', { command: 'repos' }, async ($, e) => {
572    if ((e.args ?? '').trim() === 'widget') return { text: await launchWidget($) }
573    const opened = await $.ui.open({ id: PANE, title: '📡 Repo Radar', focus: true, closeOnEscape: true, rows: 26, columns: 98 })
574    const snap = await read($, snapshot)
575    if (!snap || (await $.clock.now()) - snap.fetchedAt > REFRESH_MS) void refresh($, fallbackToken)
576    else void loadShared($).then(shared => update($, needs, () => shared?.needs ?? null))
577    const where = e.presentation?.isFullscreen
578      ? 'docked on the right'
579      : 'above the prompt (turn on the fullscreen layout to dock it on the right)'
580    return { text: opened.isPlaced ? `Repo Radar opened ${where}. Esc closes it.` : `Repo Radar couldn't open: ${'reason' in opened ? opened.reason : 'no room'}` }
581  })
582
583  on('command.run', { command: 'repos-import' }, async ($, e) => ({
584    text: await importHistory($, fallbackToken, e.args ?? ''),
585  }))
586
587  on('command.run', { command: 'release-check' }, async ($, e) => ({
588    text: await releaseCheck($, fallbackToken, e.args ?? ''),
589  }))
590
591  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
592    const { Box, Text, Button } = $.ui.resolve(e)
593    const snap = await read($, snapshot)
594    const state = await read($, status)
595    const why = await read($, message)
596    const open = await read($, expanded)
597    const away = await read($, digest)
598    const hidden = await read($, hiddenColumns)
599    const todo = await read($, needs)
600    const now = await $.clock.now()
601    const width = e.props.bodyColumns ?? e.viewport?.columns ?? 80
602    const isWide = width >= 70
603    const hasTraffic = width >= 88
604
605    const toggle = (k: string) =>
606      update($, expanded, list => (list.includes(k) ? list.filter(x => x !== k) : [...list, k]))
607
608    const header = (
609      <Box flexDirection="column" marginBottom={1}>
610        <Box gap={2}>
611          <Text bold color="cyan">📡 REPO RADAR</Text>
612          <Button key="refresh" label={state === 'loading' ? 'scanning…' : '↻ Refresh'} hotkey="r" onPress={() => void refresh($, fallbackToken)} />
613        </Box>
614        {snap && (
615          <Text dimColor>
616            {snap.accounts.length} account{snap.accounts.length === 1 ? '' : 's'} ·{' '}
617            {snap.accounts.reduce((n, a) => n + a.repos.length, 0)} repos · swept {ago(new Date(snap.fetchedAt).toISOString(), now)} ago
618            {e.props.isFocused ? ' · ↑↓ scroll · r refresh' : ' · Tab here to scroll'}
619          </Text>
620        )}
621        {away !== '' && (
622          <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginTop={1}>
623            {away.split('\n').map((line, i) => (
624              <Text key={`away:${i}`} bold={i === 0} color={i === 0 ? 'yellow' : undefined}>
625                {line}
626              </Text>
627            ))}
628            <Button key="dismiss-digest" plain dimColor label="dismiss" onPress={() => void update($, digest, () => '')} />
629          </Box>
630        )}
631        {/* The widget works the list out and shares it; its buttons hand each item to Claude. */}
632        {todo && todo.items.length > 0 && (
633          <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginTop={1}>
634            <Text bold color="yellow">
635              ⚠️ Needs Attention {todo.items.length}
636              <Text dimColor> · as of {ago(new Date(todo.at).toISOString(), now)} ago</Text>
637            </Text>
638            {todo.items.slice(0, NEEDS_PREVIEW).map((item, i) => (
639              <Text key={`need:${i}`} wrap="truncate">
640                {item.icon} {item.text}
641              </Text>
642            ))}
643            <Box gap={2}>
644              {todo.items.length > NEEDS_PREVIEW && <Text dimColor>+{todo.items.length - NEEDS_PREVIEW} more</Text>}
645              <Button key="fix-in-widget" plain label="🔧 Fix these in the widget" onPress={() => void launchWidget($).then(t => $.ui.toast(t, { timeoutMs: 6000 }))} />
646            </Box>
647          </Box>
648        )}
649        {todo && todo.items.length === 0 && <Text color="green">✅ Needs Attention: all clear</Text>}
650      </Box>
651    )
652
653    if (state === 'no-auth') {
654      return (
655        <Box flexDirection="column">
656          {header}
657          <Text bold>No GitHub account found 🔌</Text>
658          <Text>Sign in with the GitHub CLI, then press Refresh:</Text>
659          <Text color="cyan">  gh auth login</Text>
660          <Text dimColor>No gh? Paste a token into Repo Radar's github_token setting in /config.</Text>
661        </Box>
662      )
663    }
664
665    if (!snap) {
666      return (
667        <Box flexDirection="column">
668          {header}
669          <Text dimColor>{state === 'error' ? `Scan failed: ${why}` : 'Sweeping the skies for repos…'}</Text>
670        </Box>
671      )
672    }
673
674    const longest = Math.max(10, ...snap.accounts.flatMap(a => a.repos.map(r => r.name.length + (r.isPrivate ? 3 : 0) + (r.isFork ? 2 : 0))))
675    const zero = (n: number) => n === 0
676    const since = snap.accounts
677      .flatMap(a => a.repos)
678      .map(r => r.traffic?.since)
679      .filter((d): d is string => !!d)
680      .sort()[0]
681
682    // Every column but the name: its width, whether the pane has room, and how a row fills it.
683    const COLUMNS: { id: string; label: string; width: number; fits: boolean; cell: (r: Repo) => RenderChildren }[] = [
684      {
685        id: 'lang', label: '◆', width: 2, fits: isWide,
686        cell: r => <Text color={r.languageColor ?? undefined}>{r.languageColor ? '◆' : ' '}</Text>,
687      },
688      {
689        id: 'stars', label: 'stars', width: 7, fits: true,
690        cell: r => <Text color={zero(r.stars) ? undefined : 'yellow'} dimColor={zero(r.stars)}>★ {compact(r.stars)}</Text>,
691      },
692      {
693        id: 'issues', label: 'issues', width: 7, fits: isWide,
694        cell: r => <Text dimColor={zero(r.issues)}>{zero(r.issues) ? '·' : r.issues}</Text>,
695      },
696      {
697        id: 'prs', label: 'PRs', width: 5, fits: isWide,
698        cell: r => <Text dimColor={zero(r.prs)} color={r.prs ? 'magenta' : undefined}>{zero(r.prs) ? '·' : r.prs}</Text>,
699      },
700      {
701        id: 'release', label: 'release', width: 12, fits: isWide,
702        cell: r => <Text color="green" wrap="truncate">{r.release ?? ''}</Text>,
703      },
704      { id: 'pushed', label: 'pushed', width: 7, fits: true, cell: r => <Text dimColor>{ago(r.pushedAt, now)}</Text> },
705      {
706        id: 'clones', label: 'clones', width: 8, fits: hasTraffic,
707        cell: r => (
708          <Text color={r.traffic?.clonesLifetime ? 'cyan' : undefined} dimColor={!r.traffic?.clonesLifetime}>
709            {r.traffic ? compact(r.traffic.clonesLifetime) : ''}
710          </Text>
711        ),
712      },
713      {
714        id: 'views', label: 'views', width: 7, fits: hasTraffic,
715        cell: r => <Text dimColor={!r.traffic?.viewsLifetime}>{r.traffic ? compact(r.traffic.viewsLifetime) : ''}</Text>,
716      },
717    ]
718    const fitting = COLUMNS.filter(c => c.fits)
719    const shown = fitting.filter(c => !hidden.includes(c.id))
720    const folded = fitting.filter(c => hidden.includes(c.id))
721    const used = shown.reduce((n, c) => n + c.width, 0)
722    const nameWidth = Math.max(12, Math.min(longest + 2, 34, width - 8 - used))
723
724    const toggleColumn = (id: string) =>
725      update($, hiddenColumns, list => {
726        const next = list.includes(id) ? list.filter(x => x !== id) : [...list, id]
727        void $.store.set('hiddenColumns', next)
728        void saveShared($, { hiddenColumns: next })
729        return next
730      })
731
732    // Header buttons hide their column; a hidden column waits at the end as "+name".
733    const columns = (scope: string) => (
734      <Box paddingLeft={4}>
735        <Box width={nameWidth}><Text dimColor>repo</Text></Box>
736        {shown.map(c => (
737          <Box key={`col:${scope}:${c.id}`} width={c.width} justifyContent="flex-end">
738            <Button key={`hide:${scope}:${c.id}`} plain dimColor label={c.label} onPress={() => void toggleColumn(c.id)} />
739          </Box>
740        ))}
741        {folded.map(c => (
742          <Box key={`fold:${scope}:${c.id}`} marginLeft={1}>
743            <Button key={`show:${scope}:${c.id}`} plain dimColor label={`+${c.label}`} onPress={() => void toggleColumn(c.id)} />
744          </Box>
745        ))}
746      </Box>
747    )
748
749    const row = (r: Repo) => (
750      <Box key={`${r.owner}/${r.name}`}>
751        <Text color={DOT[r.health].color}>{DOT[r.health].glyph} </Text>
752        <Box width={nameWidth}>
753          <Text wrap="truncate" dimColor={r.health === 'archived'}>
754            {r.name}
755            {r.isPrivate ? ' 🔒' : ''}
756            {r.isFork ? ' ⑂' : ''}
757          </Text>
758        </Box>
759        {shown.map(c => (
760          <Box key={`${r.owner}/${r.name}:${c.id}`} width={c.width} justifyContent="flex-end">
761            {c.cell(r)}
762          </Box>
763        ))}
764      </Box>
765    )
766
767    return (
768      <Box flexDirection="column">
769        {header}
770        {snap.accounts.map(acct => {
771          const owners = [...new Set(acct.repos.map(r => r.owner))].sort((a, b) =>
772            a === acct.login ? -1 : b === acct.login ? 1 : a.localeCompare(b),
773          )
774          return (
775            <Box key={`acct:${acct.host}/${acct.login}`} flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} marginBottom={1}>
776              <Text bold>
777                🐙 {acct.login}
778                <Text dimColor>{acct.host === 'github.com' ? '' : ` @ ${acct.host}`}</Text>
779              </Text>
780              {acct.error && <Text color="red">⚠ {acct.error}</Text>}
781              {columns(`${acct.host}/${acct.login}`)}
782              {owners.map(owner => {
783                const k = `${acct.host}/${owner}`
784                const repos = acct.repos.filter(r => r.owner === owner)
785                const isOpen = open.includes(k)
786                const showAll = open.includes(`${k}:all`)
787                const shown = showAll ? repos : repos.slice(0, PREVIEW)
788                const stars = repos.reduce((n, r) => n + r.stars, 0)
789                const reds = repos.filter(r => r.health === 'red').length
790                return (
791                  <Box key={k} flexDirection="column">
792                    <Box>
793                      <Button key={`fold:${k}`} plain label={isOpen ? '▾' : '▸'} onPress={() => void toggle(k)} />
794                      <Text bold color={owner === acct.login ? 'cyan' : 'blue'}> {owner}</Text>
795                      <Text dimColor>  {repos.length} repos · ★{compact(stars)}</Text>
796                      {reds > 0 && <Text color="red">  🔴 {reds}</Text>}
797                    </Box>
798                    {isOpen && <Box flexDirection="column" paddingLeft={2}>{shown.map(row)}</Box>}
799                    {isOpen && repos.length > PREVIEW && (
800                      <Box paddingLeft={2}>
801                        <Button
802                          key={`more:${k}`}
803                          plain
804                          dimColor
805                          label={showAll ? 'show less' : `+${repos.length - PREVIEW} more`}
806                          onPress={() => void toggle(`${k}:all`)}
807                        />
808                      </Box>
809                    )}
810                  </Box>
811                )
812              })}
813            </Box>
814          )
815        })}
816        {hasTraffic && since && snap.watchedSince && (
817          <Text dimColor>
818            outside clones (no CI, not you) since {shortDate(since < snap.watchedSince ? since : snap.watchedSince, now)} · views since{' '}
819            {shortDate(snap.watchedSince, now)} (GitHub only keeps 14 days of views)
820          </Text>
821        )}
822        <Text dimColor><Text color="green">●</Text> active  <Text color="yellow">●</Text> quiet {STALE_DAYS}d+  <Text color="red">●</Text> CI failing  ○ archived</Text>
823      </Box>
824    )
825  })
826}
827
hooks/lib.ts 151 lines
1import type { Ledger, Snapshot } from '../types'
2
3const DAY = 86400 * 1000
4
5export const ago = (iso: string | null, now: number): string => {
6  if (!iso) return '—'
7  const s = Math.max(0, (now - Date.parse(iso)) / 1000)
8  if (s < 3600) return `${Math.max(1, Math.round(s / 60))}m`
9  if (s < 86400) return `${Math.round(s / 3600)}h`
10  if (s < 86400 * 60) return `${Math.round(s / 86400)}d`
11  if (s < 86400 * 730) return `${Math.round(s / (86400 * 30))}mo`
12  return `${Math.round(s / (86400 * 365))}y`
13}
14
15export const compact = (n: number): string =>
16  n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k` : String(n)
17
18/** The last `days` UTC dates ending at `now`, oldest first, as YYYY-MM-DD. */
19export const dayKeys = (now: number, days = 14): string[] =>
20  Array.from({ length: days }, (_, i) => new Date(now - (days - 1 - i) * DAY).toISOString().slice(0, 10))
21
22/** GitHub's traffic rows mapped onto fixed days, zero where a day is missing. */
23export const perDay = (rows: { timestamp: string; count: number }[], keys: string[]): number[] => {
24  const byDay = new Map(rows.map(r => [r.timestamp.slice(0, 10), r.count]))
25  return keys.map(k => byDay.get(k) ?? 0)
26}
27
28/** "2026-04-14" as "Apr 14", with the year when it isn't this year's. */
29export const shortDate = (day: string, now: number): string => {
30  const d = new Date(`${day}T00:00:00Z`)
31  const month = d.toLocaleString('en-US', { month: 'short', timeZone: 'UTC' })
32  const year = d.getUTCFullYear() === new Date(now).getUTCFullYear() ? '' : ` ${d.getUTCFullYear()}`
33  return `${month} ${d.getUTCDate()}${year}`
34}
35
36export const repoKey = (owner: string, name: string) => `${owner}/${name}`
37
38export function toLedger(snap: Snapshot): Ledger {
39  const repos: Ledger['repos'] = {}
40  for (const r of snap.accounts.flatMap(a => a.repos)) {
41    repos[repoKey(r.owner, r.name)] = { stars: r.stars, forks: r.forks, issues: r.issues, release: r.release }
42  }
43  return { at: snap.fetchedAt, repos }
44}
45
46export type Change = { kind: 'star' | 'fork' | 'issue' | 'release'; repo: string; amount: number; tag?: string }
47
48/** What grew between an earlier ledger and a newer snapshot. Repos new to the ledger are not news. */
49export function changes(before: Ledger, after: Snapshot): Change[] {
50  const out: Change[] = []
51  for (const r of after.accounts.flatMap(a => a.repos)) {
52    const was = before.repos[repoKey(r.owner, r.name)]
53    if (!was) continue
54    if (r.stars > was.stars) out.push({ kind: 'star', repo: r.name, amount: r.stars - was.stars })
55    if (r.forks > was.forks) out.push({ kind: 'fork', repo: r.name, amount: r.forks - was.forks })
56    if (r.issues > was.issues) out.push({ kind: 'issue', repo: r.name, amount: r.issues - was.issues })
57    if (r.release && r.release !== was.release) out.push({ kind: 'release', repo: r.name, amount: 1, tag: r.release })
58  }
59  return out
60}
61
62export function describe(c: Change): string {
63  switch (c.kind) {
64    case 'star':
65      return `⭐ +${c.amount} star${c.amount === 1 ? '' : 's'} on ${c.repo}`
66    case 'fork':
67      return `🍴 ${c.repo} was forked${c.amount > 1 ? ` ${c.amount}×` : ''}`
68    case 'issue':
69      return `🐛 ${c.amount} new issue${c.amount === 1 ? '' : 's'} on ${c.repo}`
70    case 'release':
71      return `🚀 ${c.repo} shipped ${c.tag}`
72  }
73}
74
75/** One line summing a batch of changes, for the digest. */
76export function summarize(list: Change[], clones: number): string {
77  const sum = (k: Change['kind']) => list.filter(c => c.kind === k).reduce((n, c) => n + c.amount, 0)
78  const parts = [
79    sum('star') && `+${sum('star')} ⭐`,
80    sum('fork') && `+${sum('fork')} 🍴`,
81    sum('issue') && `${sum('issue')} new issue${sum('issue') === 1 ? '' : 's'}`,
82    sum('release') && `${sum('release')} release${sum('release') === 1 ? '' : 's'} 🚀`,
83    clones && `${compact(clones)} clones`,
84  ].filter(Boolean)
85  return parts.length ? parts.join(' · ') : 'all quiet'
86}
87
88/** An asset name with its version numbers swapped for a placeholder, so releases compare. */
89export const assetShape = (name: string): string =>
90  name.replace(/v?\d+\.\d+\.\d+(?:-(?:alpha|beta|rc|pre)[.\d]*)?/gi, '{v}')
91
92/** Assets the previous release had that the latest lacks, by shape. */
93export function missingAssets(latest: string[], previous: string[]): string[] {
94  const have = new Set(latest.map(assetShape))
95  return previous.filter(n => !have.has(assetShape(n)))
96}
97
98
99export type DayRow = { timestamp: string; count: number }
100
101/** Daily traffic per repo, kept across sessions; zero days are not stored. */
102export type History = Record<string, { clones: Record<string, number>; views: Record<string, number> }>
103
104/** Folds GitHub's daily rows into a repo's days. A day only ever grows, so keep the larger count. */
105export function record(days: Record<string, number>, rows: DayRow[]): void {
106  for (const row of rows) {
107    const day = row.timestamp.slice(0, 10)
108    if (row.count > 0) days[day] = Math.max(days[day] ?? 0, row.count)
109  }
110}
111
112const total = (days: Record<string, number>) => Object.values(days).reduce((n, c) => n + c, 0)
113
114/** A repo's lifetime totals and the first day on record. */
115export function lifetime(entry: History[string] | undefined): { clones: number; views: number; since: string | null } {
116  if (!entry) return { clones: 0, views: 0, since: null }
117  const days = [...Object.keys(entry.clones), ...Object.keys(entry.views)].sort()
118  return { clones: total(entry.clones), views: total(entry.views), since: days[0] ?? null }
119}
120
121/**
122 * Merges a clone tracker's export into the history:
123 * `{ by_repo: { "owner/name": { days: { "YYYY-MM-DD": count } } } }`.
124 */
125export function importTracker(history: History, data: unknown): { repos: number; days: number } {
126  const byRepo = (data as { by_repo?: Record<string, { days?: Record<string, number> }> })?.by_repo
127  if (!byRepo || typeof byRepo !== 'object') throw new Error('expected a JSON object with a "by_repo" field')
128  let repos = 0
129  let days = 0
130  for (const [key, entry] of Object.entries(byRepo)) {
131    const rows = Object.entries(entry?.days ?? {}).map(([timestamp, count]) => ({ timestamp, count: Number(count) || 0 }))
132    if (rows.length === 0) continue
133    const target = (history[key] ??= { clones: {}, views: {} })
134    record(target.clones, rows)
135    repos += 1
136    days += rows.length
137  }
138  return { repos, days }
139}
140
141/** Folds `from` into `into`, day by day, keeping the larger count; either side may hold days the other lacks. */
142export function mergeHistory(into: History, from: History | undefined): History {
143  for (const [key, entry] of Object.entries(from ?? {})) {
144    const target = (into[key] ??= { clones: {}, views: {} })
145    for (const kind of ['clones', 'views'] as const) {
146      for (const [day, n] of Object.entries(entry?.[kind] ?? {})) target[kind][day] = Math.max(target[kind][day] ?? 0, n)
147    }
148  }
149  return into
150}
151
types/index.d.ts 55 lines
1export type Health = 'green' | 'yellow' | 'red' | 'archived'
2
3export type Repo = {
4  name: string
5  owner: string
6  url: string
7  isPrivate: boolean
8  isFork: boolean
9  stars: number
10  forks: number
11  issues: number
12  prs: number
13  release: string | null
14  pushedAt: string | null
15  language: string | null
16  languageColor: string | null
17  health: Health
18  canPush: boolean
19  traffic?: Traffic
20}
21
22/** `clones` is the last 14 days, oldest first; the lifetime totals count every day on record since `since`. */
23export type Traffic = { clones: number[]; clonesLifetime: number; viewsLifetime: number; since: string | null }
24
25/** Counts per repo at one moment, kept across sessions to say what changed. */
26export type Ledger = {
27  at: number
28  repos: Record<string, { stars: number; forks: number; issues: number; release: string | null }>
29}
30
31export type Account = { host: string; login: string; repos: Repo[]; error?: string }
32
33/** `watchedSince`: the first day Repo Radar's own traffic history covers (views have no older source). */
34export type Snapshot = { accounts: Account[]; fetchedAt: number; trafficAt: number; watchedSince: string }
35
36/** One Needs Attention item, as the widget shares it in data.json. */
37export type NeedItem = { icon: string; text: string; url: string }
38export type Needs = { at: number; items: NeedItem[] }
39
40export type Status = 'idle' | 'loading' | 'ready' | 'no-auth' | 'error'
41
42declare module 'claude-code' {
43  interface PluginState {
44    'repo-radar': {
45      snapshot: Snapshot | null
46      status: Status
47      message: string
48      expanded: string[]
49      digest: string
50      hidden: string[]
51      needs: Needs | null
52    }
53  }
54}
55