claude-rpc 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +72 -62
  2. package/SECURITY.md +99 -20
  3. package/package.json +2 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +430 -459
  9. package/src/commands.js +245 -0
  10. package/src/community.js +101 -60
  11. package/src/completion.js +196 -0
  12. package/src/config.js +4 -1
  13. package/src/daemon.js +45 -47
  14. package/src/default-config.js +4 -3
  15. package/src/discord-ipc.js +24 -13
  16. package/src/doctor.js +64 -38
  17. package/src/ensure-daemon.js +11 -4
  18. package/src/fmt.js +8 -6
  19. package/src/format.js +8 -13
  20. package/src/gist.js +8 -18
  21. package/src/git.js +4 -1
  22. package/src/help.js +117 -0
  23. package/src/hook.js +27 -32
  24. package/src/insights.js +3 -4
  25. package/src/install.js +100 -79
  26. package/src/leaderboard.js +3 -2
  27. package/src/mcp.js +2 -8
  28. package/src/nudge.js +10 -5
  29. package/src/png.js +135 -0
  30. package/src/pricing.js +25 -3
  31. package/src/privacy.js +22 -7
  32. package/src/profile.js +0 -6
  33. package/src/recap.js +4 -17
  34. package/src/scanner.js +103 -71
  35. package/src/select.js +60 -0
  36. package/src/server/api.js +64 -36
  37. package/src/server/assets/dashboard.client.js +75 -44
  38. package/src/server/assets/dashboard.css +18 -18
  39. package/src/server/assets/dashboard.html +13 -15
  40. package/src/server/assets/wrapped.client.js +26 -11
  41. package/src/server/assets/wrapped.css +2 -2
  42. package/src/server/index.js +43 -32
  43. package/src/server/page.js +6 -3
  44. package/src/server/sse.js +90 -34
  45. package/src/session-card.js +3 -1
  46. package/src/statcards.js +278 -0
  47. package/src/state.js +14 -24
  48. package/src/tui.js +3 -12
  49. package/src/ui.js +7 -5
  50. package/src/verify.js +3 -7
  51. package/src/version.js +1 -1
  52. package/src/week.js +4 -4
package/src/cli.js CHANGED
@@ -1,90 +1,52 @@
1
1
  #!/usr/bin/env node
2
- import { spawn, spawnSync } from 'node:child_process';
3
- import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync, mkdirSync } from 'node:fs';
2
+ // First, before anything probes stdio (ui.js does at load): the dashboard and
3
+ // npm scripts run this file directly, not through bin/claude-rpc.js.
4
+ import './safe-stdio.js';
5
+ import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync } from 'node:fs';
4
6
  import process from 'node:process';
5
-
6
- // Force the console code page to UTF-8 (65001) on Windows so Unicode box
7
- // drawing, block elements, and other chars render correctly. Default cmd.exe
8
- // code page on Win10 is 437/850, which displays many of our chars as `?`.
9
- // Hook events (no TTY) skip this — they don't print anything user-visible.
10
- if (process.platform === 'win32' && process.stdout.isTTY) {
11
- try { spawnSync('chcp.com', ['65001'], { stdio: 'ignore', windowsHide: true }); } catch { /* chcp absent (Wine, custom shell) — accept whatever code page is set */ }
12
- }
13
- import { DAEMON_SCRIPT, STATE_PATH, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
14
- import { readActiveState } from './state.js';
15
- import { runHookCli } from './hook.js';
16
- import { parseDuration, setPause, clearPause, pauseUntil } from './pause.js';
17
- import { loadConfig, hasUserConfig } from './config.js';
18
- import { spawnDaemonDetached, daemonAlive } from './ensure-daemon.js';
19
-
20
- // ── Lazy-loaded heavy module graph ───────────────────────────────────────────
21
- // format→scanner→pricing→languages→git→usage (plus install/tui/insights/nudge/
22
- // badge/privacy/leaderboard) is ~60ms of module-load that the fast-exit commands
23
- // (--version, --help, start, stop, restart) never touch. We declare the bindings
24
- // here and fill them via loadStats() only for commands that actually fan out into
25
- // the stats/format/install code, so daemon-control and version stay near-instant.
26
- // (The repo already lazy-imports cold deps like doctor.js/card.js/mcp.js inside
27
- // their handlers — this just extends that to the graph the main switch needs.)
7
+ import { basename, join } from 'node:path';
8
+ import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, USER_CONFIG_DIR, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
9
+ import { VERSION } from './version.js';
10
+ import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
11
+ import * as lb from './leaderboard.js';
12
+ import { writeFileAtomic } from './atomic-rename.js';
13
+
14
+ // ── Lazy-loaded module graph ─────────────────────────────────────────────────
15
+ // Only the static imports above (all cheap) load up front, so --version,
16
+ // --help, hook, mcp, daemon, serve, tail and pause never pay for subsystems
17
+ // they don't touch. Every other command awaits loadCore() once before dispatch:
18
+ // state/config/daemon-control plus the format→scanner→pricing→usage stats
19
+ // chain the shared helpers below draw on. Modules only one command needs
20
+ // (install, tui, insights, nudge, badge, privacy, pause, week, hook,
21
+ // node:crypto, node:readline, node:child_process) are imported inside that
22
+ // command's handler, like doctor.js/card.js/mcp.js always were.
23
+ let readActiveState, statePathFor, loadConfig, hasUserConfig, spawnDaemonDetached, daemonAlive;
28
24
  let buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours;
29
25
  let scan, readAggregate, findLiveSessions, dayKey, weekKey;
30
- let weekGrid;
31
- let runInstall, runUninstall, isInstalled, migrateConfig, installHooks, ensureCanonicalExe, installMcp, uninstallMcp, setupOutro;
32
- let startTui;
33
- let generateInsights;
34
- let maybeNudge, pickTodayMilestone;
35
- let badgeSvg;
36
26
  let fmtCost;
37
- let addPrivateCwd, removePrivateCwd, listPrivateCwds, resolveVisibility;
38
27
  let readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay;
39
- let lb;
40
-
41
- let statsLoaded = false;
42
- async function loadStats() {
43
- if (statsLoaded) return;
44
- // Load the graph concurrently — these are all leaf-ish modules with no
45
- // ordering dependency, so Promise.all beats a sequential import chain.
46
- const [fmt, scn, wk, inst, tui, ins, ndg, bdg, prc, priv, usg, leaderboard] = await Promise.all([
47
- import('./format.js'), import('./scanner.js'), import('./week.js'),
48
- import('./install.js'), import('./tui.js'), import('./insights.js'),
49
- import('./nudge.js'), import('./badge.js'), import('./pricing.js'),
50
- import('./privacy.js'), import('./usage.js'), import('./leaderboard.js'),
28
+
29
+ async function loadDaemonCtl() {
30
+ ({ spawnDaemonDetached, daemonAlive } = await import('./ensure-daemon.js'));
31
+ }
32
+
33
+ // Idempotent — repeat imports resolve from the module cache.
34
+ async function loadCore() {
35
+ const [st, cfg, fmt, scn, prc, usg] = await Promise.all([
36
+ import('./state.js'), import('./config.js'), import('./format.js'),
37
+ import('./scanner.js'), import('./pricing.js'), import('./usage.js'), loadDaemonCtl(),
51
38
  ]);
39
+ ({ readActiveState, statePathFor } = st);
40
+ ({ loadConfig, hasUserConfig } = cfg);
52
41
  ({ buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours } = fmt);
53
42
  ({ scan, readAggregate, findLiveSessions, dayKey, weekKey } = scn);
54
- ({ weekGrid } = wk);
55
- ({ install: runInstall, uninstall: runUninstall, isInstalled, migrateConfig, installHooks, ensureCanonicalExe, installMcp, uninstallMcp, setupOutro } = inst);
56
- ({ startTui } = tui);
57
- ({ generateInsights } = ins);
58
- ({ maybeNudge, pickTodayMilestone } = ndg);
59
- ({ badgeSvg } = bdg);
60
43
  ({ fmtCost } = prc);
61
- ({ addPrivateCwd, removePrivateCwd, listPrivateCwds, resolveVisibility } = priv);
62
44
  ({ readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay } = usg);
63
- lb = leaderboard;
64
- statsLoaded = true;
65
45
  }
66
- import { VERSION } from './version.js';
67
- import { fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
68
- import { randomUUID } from 'node:crypto';
69
- import { createInterface } from 'node:readline';
70
- import { basename, join, dirname } from 'node:path';
71
46
 
72
47
  const cmd = process.argv[2];
48
+ const args = process.argv.slice(3);
73
49
 
74
- // ── ANSI styling (degrades gracefully) ────────────────────────────────────────
75
- const tty = process.stdout.isTTY && !process.env.NO_COLOR;
76
- const c = {
77
- reset: tty ? '\x1b[0m' : '',
78
- dim: tty ? '\x1b[2m' : '',
79
- bold: tty ? '\x1b[1m' : '',
80
- cyan: tty ? '\x1b[36m' : '',
81
- green: tty ? '\x1b[32m' : '',
82
- yellow: tty ? '\x1b[33m' : '',
83
- red: tty ? '\x1b[31m' : '',
84
- magenta: tty ? '\x1b[35m' : '',
85
- blue: tty ? '\x1b[34m' : '',
86
- gray: tty ? '\x1b[90m' : '',
87
- };
88
50
  const ansiRe = /\x1b\[[0-9;]*m/g;
89
51
  const visibleLen = (s) => String(s).replace(ansiRe, '').length;
90
52
 
@@ -93,13 +55,13 @@ function readJson(path, fallback) {
93
55
  try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
94
56
  }
95
57
 
96
- // Persist a mutated config.json. The config dir doesn't exist until `setup`
97
- // runs (npm/npx install no install script), so a bare writeFileSync threw an
98
- // uncaught ENOENT for any config-mutating command run before setup
99
- // (`profile set`, `community on`, `link`, …). mkdirSync first.
58
+ // Persist a mutated config.json. tmp + rename (like verify.updateUserConfig),
59
+ // so the daemon's config watcher never reads a half-written file. The helper
60
+ // also creates the config dir, which doesn't exist until `setup` runs — a
61
+ // config-mutating command run before setup (`profile set`, `community on`,
62
+ // `link`, …) used to throw an uncaught ENOENT.
100
63
  function writeUserConfig(userCfg) {
101
- mkdirSync(dirname(CONFIG_PATH), { recursive: true });
102
- writeFileSync(CONFIG_PATH, JSON.stringify(userCfg, null, 2) + '\n');
64
+ writeFileAtomic(CONFIG_PATH, JSON.stringify(userCfg, null, 2) + '\n');
103
65
  }
104
66
 
105
67
  // Validate a flag's value taken with `argv[++i]`. A value that's missing or
@@ -158,7 +120,7 @@ async function confirmDaemonUp({ timeoutMs = 3000, intervalMs = 100 } = {}) {
158
120
  for (;;) {
159
121
  await new Promise((r) => setTimeout(r, intervalMs));
160
122
  if (daemonAlive()) {
161
- console.log(` ${c.green}✓${c.reset} ${'daemon confirmed'.padEnd(16)}${c.dim}up — connecting to Discord${c.reset}`);
123
+ console.log(` ${c.green}✓${c.reset} ${'daemon is up'.padEnd(16)}${c.dim}connecting to Discord${c.reset}`);
162
124
  return true;
163
125
  }
164
126
  if (Date.now() >= deadline) {
@@ -181,24 +143,28 @@ function stopDaemon({ quiet = false } = {}) {
181
143
  }
182
144
  }
183
145
 
146
+ // Resolves once the replacement daemon has been spawned (true) or couldn't be
147
+ // (false), so callers can confirm it and a following `stop` finds its pid.
184
148
  function restartDaemon() {
185
- if (!stopDaemon({ quiet: true })) { startDaemon(); return; }
186
- // Poll for the old daemon to release the PID file rather than guessing with a
187
- // fixed sleep — under load 600ms wasn't always enough, and startDaemon would
188
- // then see it "still up" and no-op, leaving NO daemon running once the old
189
- // one exited. Give up after ~3s, force-kill the wedged pid, and start anyway.
190
- const deadline = Date.now() + 3000;
191
- const tick = () => {
192
- if (!daemonAlive()) { startDaemon(); return; }
193
- if (Date.now() >= deadline) {
194
- const pid = daemonAlive();
195
- if (pid) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
196
- startDaemon();
197
- return;
198
- }
149
+ return new Promise((resolve) => {
150
+ if (!stopDaemon({ quiet: true })) { resolve(startDaemon()); return; }
151
+ // Poll for the old daemon to release the PID file rather than guessing with a
152
+ // fixed sleep — under load 600ms wasn't always enough, and startDaemon would
153
+ // then see it "still up" and no-op, leaving NO daemon running once the old
154
+ // one exited. Give up after ~3s, force-kill the wedged pid, and start anyway.
155
+ const deadline = Date.now() + 3000;
156
+ const tick = () => {
157
+ if (!daemonAlive()) { resolve(startDaemon()); return; }
158
+ if (Date.now() >= deadline) {
159
+ const pid = daemonAlive();
160
+ if (pid) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
161
+ resolve(startDaemon());
162
+ return;
163
+ }
164
+ setTimeout(tick, 50);
165
+ };
199
166
  setTimeout(tick, 50);
200
- };
201
- setTimeout(tick, 50);
167
+ });
202
168
  }
203
169
 
204
170
  // ── Box drawing — auto-widens to fit longest line ────────────────────────────
@@ -288,7 +254,7 @@ function renderHeatmap(byDay, days = 91) {
288
254
  const cursor = new Date(start);
289
255
  while (cursor <= today) {
290
256
  const k = dayKey(cursor.getTime());
291
- cells.push({ key: k, ms: byDay?.[k]?.activeMs || 0, future: cursor > today });
257
+ cells.push({ key: k, ms: byDay?.[k]?.activeMs || 0 });
292
258
  cursor.setDate(cursor.getDate() + 1);
293
259
  }
294
260
  const cols = Math.ceil(cells.length / 7);
@@ -343,7 +309,7 @@ function renderHeatmap(byDay, days = 91) {
343
309
  let line = ` ${c.dim}${dayLabels[row]}${c.reset} `;
344
310
  for (let col = 0; col < cols; col++) {
345
311
  const cell = cells[col * 7 + row];
346
- if (!cell || cell.future) line += ' ';
312
+ if (!cell) line += ' '; // past today: the walk stops there
347
313
  else line += shade(cell.ms) + ' ';
348
314
  }
349
315
  lines.push(line);
@@ -384,6 +350,21 @@ function lastDays(byDay, n) {
384
350
  return out;
385
351
  }
386
352
 
353
+ // "42m" / "3.5h" / "12h" — compact active-time label for bar-chart rows.
354
+ const hoursLabel = (ms) => {
355
+ const h = ms / 3_600_000;
356
+ return h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
357
+ };
358
+
359
+ // ISO-week key of last week, stepped back from local noon so a DST shift
360
+ // can't land the subtraction in the wrong week.
361
+ function lastWeekKey() {
362
+ const d = new Date();
363
+ d.setHours(12, 0, 0, 0);
364
+ d.setDate(d.getDate() - 7);
365
+ return weekKey(d.getTime());
366
+ }
367
+
387
368
  const dayTokens = (d) => d
388
369
  ? (d.inputTokens || 0) + (d.outputTokens || 0) + (d.cacheReadTokens || 0) + (d.cacheWriteTokens || 0)
389
370
  : 0;
@@ -425,7 +406,8 @@ function todayBoxLines(vars, aggregate) {
425
406
  return lines;
426
407
  }
427
408
 
428
- function showStatus() {
409
+ async function showStatus() {
410
+ const { generateInsights } = await import('./insights.js');
429
411
  const state = readActiveState();
430
412
  const aggregate = readAggregate();
431
413
  const config = loadConfig();
@@ -443,7 +425,9 @@ function showStatus() {
443
425
  pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}` : `${c.red}○ not running${c.reset}`, ''),
444
426
  pair('client', config.clientId || '—'),
445
427
  pair('config', shortPath(CONFIG_PATH), c.gray),
446
- pair('state', shortPath(STATE_PATH), c.gray),
428
+ // The file behind the session shown below (hooks write one per session),
429
+ // or the state dir when no session has written one yet.
430
+ pair('state', shortPath(state.sessionId ? statePathFor(state.sessionId) : STATE_DIR), c.gray),
447
431
  pair('log', shortPath(LOG_PATH), c.gray),
448
432
  ]);
449
433
  console.log('');
@@ -541,11 +525,8 @@ function showStatus() {
541
525
  .slice(0, 6);
542
526
  if (top.length) {
543
527
  const maxMs = top[0][1].activeMs;
544
- const lines = top.map(([name, p]) => {
545
- const h = (p.activeMs / 3_600_000);
546
- const hStr = h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
547
- return `${humanProject(name).slice(0, 20).padEnd(22)} ${bar(p.activeMs, maxMs)} ${c.cyan}${hStr.padStart(5)}${c.reset} ${c.dim}${p.sessions} sess · ${p.userMessages} prompts${c.reset}`;
548
- });
528
+ const lines = top.map(([name, p]) =>
529
+ `${humanProject(name).slice(0, 20).padEnd(22)} ${bar(p.activeMs, maxMs)} ${c.cyan}${hoursLabel(p.activeMs).padStart(5)}${c.reset} ${c.dim}${p.sessions} sess · ${p.userMessages} prompts${c.reset}`);
549
530
  box('top projects by active time', lines, 72);
550
531
  console.log('');
551
532
  }
@@ -607,7 +588,8 @@ function showStatus() {
607
588
  }
608
589
  }
609
590
 
610
- function showToday() {
591
+ async function showToday() {
592
+ const { maybeNudge, pickTodayMilestone } = await import('./nudge.js');
611
593
  const state = readActiveState();
612
594
  const aggregate = readAggregate();
613
595
  const config = loadConfig();
@@ -640,7 +622,8 @@ function showToday() {
640
622
  }
641
623
  }
642
624
 
643
- function showWeek() {
625
+ async function showWeek() {
626
+ const { weekGrid } = await import('./week.js');
644
627
  const state = readActiveState();
645
628
  const aggregate = readAggregate();
646
629
  const config = loadConfig();
@@ -653,11 +636,8 @@ function showWeek() {
653
636
 
654
637
  // Week-over-week context: this week so far vs the whole of last week.
655
638
  // Early in the week "▼" is expected — the vs label keeps that honest.
656
- const prevRef = new Date();
657
- prevRef.setHours(12, 0, 0, 0); // noon — immune to DST midnight edges
658
- prevRef.setDate(prevRef.getDate() - 7);
659
639
  const wkNow = aggregate?.byWeek?.[weekKey(Date.now())];
660
- const wkPrev = aggregate?.byWeek?.[weekKey(prevRef.getTime())];
640
+ const wkPrev = aggregate?.byWeek?.[lastWeekKey()];
661
641
  const dWkActive = fmtDelta(wkNow?.activeMs || 0, wkPrev?.activeMs || 0, { vs: 'vs last week' });
662
642
  const dWkPrompts = fmtDelta(wkNow?.userMessages || 0, wkPrev?.userMessages || 0);
663
643
  const dWkTokens = fmtDelta(dayTokens(wkNow), dayTokens(wkPrev));
@@ -676,11 +656,9 @@ function showWeek() {
676
656
  const { days, maxMs } = weekGrid(aggregate.byDay);
677
657
  const lines = days.map(({ label, ms, isFuture, isToday }) => {
678
658
  if (isFuture) return `${c.dim}${label.padEnd(12)} ${'·'.repeat(22)} —${c.reset}`;
679
- const h = ms / 3_600_000;
680
- const hStr = h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
681
659
  const prefix = isToday ? `${c.bold}` : '';
682
660
  const peak = ms === maxMs && ms > 0 ? ` ${c.bold}${heat(1)}◆${c.reset}` : '';
683
- return `${prefix}${label.padEnd(12)}${c.reset} ${bar(ms, maxMs)} ${c.cyan}${hStr.padStart(5)}${c.reset}${peak}${isToday ? ` ${c.dim}← today${c.reset}` : ''}`;
661
+ return `${prefix}${label.padEnd(12)}${c.reset} ${bar(ms, maxMs)} ${c.cyan}${hoursLabel(ms).padStart(5)}${c.reset}${peak}${isToday ? ` ${c.dim}← today${c.reset}` : ''}`;
684
662
  });
685
663
  box('this week · daily breakdown', lines);
686
664
  console.log('');
@@ -715,14 +693,14 @@ function showProjects(argv = []) {
715
693
  });
716
694
  if (ranked.length > limit) lines.push(`${c.dim}… ${ranked.length - limit} more — --limit ${ranked.length} to see all${c.reset}`);
717
695
  box('projects', lines, 76);
718
- console.log(`\n ${c.dim}drill in: ${c.reset}${c.cyan}claude-rpc project <name>${c.reset}\n`);
696
+ console.log(`\n ${c.dim}drill in: ${c.reset}${c.cyan}claude-rpc projects <name>${c.reset}\n`);
719
697
  }
720
698
 
721
699
  // `project <name>` — one project's full record + its recent daily rhythm
722
700
  // (attributed per-day since scan cache v5).
723
701
  function showProject(rawName) {
724
702
  if (!rawName) {
725
- console.log(`\n Usage: ${c.cyan}claude-rpc project <name>${c.reset} (see ${c.cyan}claude-rpc projects${c.reset})\n`);
703
+ console.log(`\n Usage: ${c.cyan}claude-rpc projects <name>${c.reset} (see ${c.cyan}claude-rpc projects${c.reset})\n`);
726
704
  process.exitCode = EX_USER_ERROR;
727
705
  return;
728
706
  }
@@ -776,11 +754,8 @@ function showCompare() {
776
754
  console.log(`\n No history yet — run ${c.cyan}claude-rpc scan${c.reset} first.\n`);
777
755
  return;
778
756
  }
779
- const prevRef = new Date();
780
- prevRef.setHours(12, 0, 0, 0);
781
- prevRef.setDate(prevRef.getDate() - 7);
782
757
  const nowKey = weekKey(Date.now());
783
- const prevKey = weekKey(prevRef.getTime());
758
+ const prevKey = lastWeekKey();
784
759
  const wk = aggregate.byWeek[nowKey] || {};
785
760
  const pw = aggregate.byWeek[prevKey] || {};
786
761
 
@@ -863,14 +838,7 @@ function statusColor(status) {
863
838
  }
864
839
 
865
840
  function showPreview() {
866
- let state = readActiveState();
867
- const aggregate = readAggregate();
868
- const config = loadConfig();
869
- const live = findLiveSessions({ thresholdMs: 90_000 });
870
- state.liveSessions = live;
871
- state = applyIdle(state, config);
872
- state.usage = readUsageCache();
873
- const vars = buildVars(state, config, aggregate);
841
+ const { vars, config, state } = liveVars();
874
842
  const p = config.presence || {};
875
843
  // Preview the frames the daemon ACTUALLY uses: byStatus (base frame + its
876
844
  // rotation, per status) when present — pickFrames in the daemon prefers it
@@ -935,19 +903,21 @@ function dumpVars() {
935
903
  process.stdout.write(JSON.stringify({ vars: Object.keys(live).sort(), live }));
936
904
  }
937
905
 
906
+ // scan() onProgress callback: a `parsed n/total…` line redrawn at most every 500ms.
907
+ function progressLine() {
908
+ let lastReport = 0;
909
+ return ({ scanned, total }) => {
910
+ if (Date.now() - lastReport > 500) {
911
+ process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
912
+ lastReport = Date.now();
913
+ }
914
+ };
915
+ }
916
+
938
917
  function doScan(force = false) {
939
918
  console.log(` ${c.dim}scanning ~/.claude/projects ${force ? '(force re-parse)' : '(incremental)'}…${c.reset}`);
940
919
  const t0 = Date.now();
941
- let lastReport = 0;
942
- const result = scan({
943
- force,
944
- onProgress: ({ scanned, total }) => {
945
- if (Date.now() - lastReport > 500) {
946
- process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
947
- lastReport = Date.now();
948
- }
949
- },
950
- });
920
+ const result = scan({ force, onProgress: progressLine() });
951
921
  process.stdout.write('\n');
952
922
  console.log(` ${c.green}✓${c.reset} scan complete ${c.dim}${Date.now() - t0}ms — ${c.reset}${c.cyan}${result.scanned}${c.reset}${c.dim} parsed · ${result.skipped} cached · ${result.removed} removed (${result.total} total)${c.reset}`);
953
923
  if (result.dirs && result.dirs.length > 1) {
@@ -976,20 +946,10 @@ function doBackfill(argv) {
976
946
  }
977
947
  console.log(` ${c.dim}backfilling from ${c.reset}${c.cyan}${path}${c.reset}${c.dim}…${c.reset}`);
978
948
  const t0 = Date.now();
979
- let lastReport = 0;
980
949
  // Pass `extraDirs` rather than `projectsDirs` — this way the default
981
950
  // ~/.claude/projects (+ any auto-discovered alt paths) ALSO gets scanned
982
951
  // and the user's existing cache for those isn't pruned.
983
- const result = scan({
984
- force: false,
985
- extraDirs: [path],
986
- onProgress: ({ scanned, total }) => {
987
- if (Date.now() - lastReport > 500) {
988
- process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
989
- lastReport = Date.now();
990
- }
991
- },
992
- });
952
+ const result = scan({ force: false, extraDirs: [path], onProgress: progressLine() });
993
953
  process.stdout.write('\n');
994
954
  console.log(` ${c.green}✓${c.reset} backfill complete ${c.dim}${Date.now() - t0}ms — ${c.reset}${c.cyan}${result.scanned}${c.reset}${c.dim} new/changed · ${result.skipped} cached${c.reset}`);
995
955
  console.log(` ${c.dim}roots: ${result.dirs.join(', ')}${c.reset}`);
@@ -997,7 +957,8 @@ function doBackfill(argv) {
997
957
  console.log(` ${c.dim}aggregate now: ${result.aggregate.sessions} sessions · ${hours}h · ${result.aggregate.userMessages} prompts${c.reset}`);
998
958
  }
999
959
 
1000
- function showInsights() {
960
+ async function showInsights() {
961
+ const { generateInsights } = await import('./insights.js');
1001
962
  const aggregate = readAggregate();
1002
963
  const insights = generateInsights(aggregate, { limit: 6 });
1003
964
  console.log('');
@@ -1035,37 +996,44 @@ async function doRecap(argv) {
1035
996
  }
1036
997
  }
1037
998
 
1038
- function parseBadgeArgs(argv) {
999
+ // Parse `--flag value` / `--flag=value` / boolean `--flag` args onto a copy of
1000
+ // `defaults`. `flags` maps each option key to its spellings — the first is the
1001
+ // name takeValue's error shows; a key whose default is `false` is a boolean
1002
+ // switch. Unknown args are ignored.
1003
+ function parseFlags(argv, defaults, flags) {
1039
1004
  argv = splitEqArgs(argv);
1040
- const out = { metric: 'hours', range: '7d', out: '', gist: false };
1005
+ const out = { ...defaults };
1041
1006
  for (let i = 0; i < argv.length; i++) {
1042
- const a = argv[i];
1043
- if (a === '--metric' || a === '-m') out.metric = takeValue(argv[++i], '--metric');
1044
- else if (a === '--range' || a === '-r') out.range = takeValue(argv[++i], '--range');
1045
- else if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1046
- else if (a === '--label' || a === '-l') out.label = takeValue(argv[++i], '--label');
1047
- else if (a === '--gist') out.gist = true;
1007
+ const key = Object.keys(flags).find((k) => flags[k].includes(argv[i]));
1008
+ if (key) out[key] = defaults[key] === false ? true : takeValue(argv[++i], flags[key][0]);
1048
1009
  }
1049
1010
  return out;
1050
1011
  }
1051
1012
 
1052
- async function doBadge(argv) {
1053
- const opts = parseBadgeArgs(argv);
1013
+ // The aggregate, or a wrong-state exit for the commands that render it.
1014
+ function aggregateOr(what) {
1054
1015
  const aggregate = readAggregate();
1055
- if (!aggregate) {
1056
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1057
- }
1016
+ if (!aggregate) fail(`no aggregate yet — nothing to ${what}`, { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1017
+ return aggregate;
1018
+ }
1019
+
1020
+ // Write a rendered artifact to --out with a one-line receipt (plus any
1021
+ // follow-up lines), or with no --out straight to stdout for piping.
1022
+ function emit(body, out, { note = `${body.length} bytes`, after = [] } = {}) {
1023
+ if (!out) { process.stdout.write(body); return; }
1024
+ writeFileSync(out, body);
1025
+ console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${out}${c.reset} ${c.dim}(${note})${c.reset}`);
1026
+ for (const line of after) console.log(line);
1027
+ }
1028
+
1029
+ async function doBadge(argv) {
1030
+ const opts = parseFlags(argv, { metric: 'hours', range: '7d', out: '', gist: false },
1031
+ { metric: ['--metric', '-m'], range: ['--range', '-r'], out: ['--out', '-o'], label: ['--label', '-l'], gist: ['--gist'] });
1032
+ const aggregate = aggregateOr('render');
1033
+ const { badgeSvg } = await import('./badge.js');
1058
1034
  const svg = badgeSvg({ aggregate, metric: opts.metric, range: opts.range, label: opts.label });
1059
- if (opts.gist) {
1060
- await publishBadgeToGist(svg, opts);
1061
- return;
1062
- }
1063
- if (opts.out) {
1064
- writeFileSync(opts.out, svg);
1065
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1066
- } else {
1067
- process.stdout.write(svg);
1068
- }
1035
+ if (opts.gist) return publishBadgeToGist(svg, opts);
1036
+ emit(svg, opts.out);
1069
1037
  }
1070
1038
 
1071
1039
  // Publish the rendered badge to a GitHub gist and emit the README-ready
@@ -1127,136 +1095,76 @@ async function publishBadgeToGist(svg, opts, kind = 'badge') {
1127
1095
  // Poster-style SVG card. Bigger sibling of `badge` — shareable summary
1128
1096
  // for a range (year / month / week / all-time). Output is SVG only;
1129
1097
  // screenshot or convert to PNG offline if needed.
1130
- function parseCardArgs(argv) {
1131
- argv = splitEqArgs(argv);
1132
- const out = { range: 'year', out: '' };
1133
- for (let i = 0; i < argv.length; i++) {
1134
- const a = argv[i];
1135
- if (a === '--range' || a === '-r') out.range = takeValue(argv[++i], '--range');
1136
- else if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1137
- }
1138
- return out;
1139
- }
1140
-
1141
1098
  async function doCard(argv) {
1142
- const opts = parseCardArgs(argv);
1143
- const aggregate = readAggregate();
1144
- if (!aggregate) {
1145
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1146
- }
1099
+ const opts = parseFlags(argv, { range: 'year', out: '' }, { range: ['--range', '-r'], out: ['--out', '-o'] });
1100
+ const aggregate = aggregateOr('render');
1147
1101
  const { renderCard } = await import('./card.js');
1148
- const svg = renderCard(aggregate, { range: opts.range });
1149
- if (opts.out) {
1150
- writeFileSync(opts.out, svg);
1151
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1152
- console.log(` ${c.dim}tip: open in a browser and save as PNG — or drop it straight into a Discord message; it renders inline${c.reset}`);
1153
- } else {
1154
- process.stdout.write(svg);
1155
- }
1102
+ emit(renderCard(aggregate, { range: opts.range }), opts.out, {
1103
+ after: [` ${c.dim}tip: open in a browser and save as PNG — or drop it straight into a Discord message; it renders inline${c.reset}`],
1104
+ });
1156
1105
  }
1157
1106
 
1158
1107
  // GitHub profile stat card — a compact, embeddable lifetime summary meant
1159
1108
  // for a profile README. `--gist` publishes it to a gist (raw URL stays stable
1160
1109
  // across re-runs) so the README image auto-refreshes when you re-run it.
1161
- function parseGithubStatArgs(argv) {
1162
- argv = splitEqArgs(argv);
1163
- const out = { out: '', gist: false, handle: '' };
1164
- for (let i = 0; i < argv.length; i++) {
1165
- const a = argv[i];
1166
- if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1167
- else if (a === '--handle' || a === '-u') out.handle = takeValue(argv[++i], '--handle');
1168
- else if (a === '--gist') out.gist = true;
1169
- }
1170
- return out;
1171
- }
1172
-
1173
1110
  async function doGithubStat(argv) {
1174
- const opts = parseGithubStatArgs(argv);
1175
- const aggregate = readAggregate();
1176
- if (!aggregate) {
1177
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1178
- }
1111
+ const opts = parseFlags(argv, { out: '', gist: false, handle: '' },
1112
+ { out: ['--out', '-o'], handle: ['--handle', '-u'], gist: ['--gist'] });
1113
+ const aggregate = aggregateOr('render');
1179
1114
  const { renderProfileCard } = await import('./profile.js');
1180
1115
  const svg = renderProfileCard(aggregate, { handle: opts.handle });
1181
- if (opts.gist) {
1182
- await publishBadgeToGist(svg, { metric: 'profile', range: 'all-time' }, 'github-stat');
1183
- return;
1184
- }
1185
- if (opts.out) {
1186
- writeFileSync(opts.out, svg);
1187
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1188
- console.log(` ${c.dim}embed in your README: <img src="${opts.out}" alt="Claude Code stats" width="500" />${c.reset}`);
1189
- } else {
1190
- process.stdout.write(svg);
1191
- }
1116
+ if (opts.gist) return publishBadgeToGist(svg, { metric: 'profile', range: 'all-time' }, 'github-stat');
1117
+ emit(svg, opts.out, {
1118
+ after: [` ${c.dim}embed in your README: <img src="${opts.out}" alt="Claude Code stats" width="500" />${c.reset}`],
1119
+ });
1192
1120
  }
1193
1121
 
1194
1122
  // Build the live template-variable table the way the daemon does — current
1195
- // state + idle/stale resolution + aggregate. Shared by statusline/session-card.
1123
+ // state + idle/stale resolution + aggregate. Shared by preview/statusline/
1124
+ // session-card.
1196
1125
  function liveVars() {
1197
- const state = readActiveState();
1198
- state.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
1126
+ const raw = readActiveState();
1127
+ raw.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
1199
1128
  const config = loadConfig();
1200
- const resolved = applyIdle(state, config);
1201
- resolved.usage = readUsageCache();
1202
- return { vars: buildVars(resolved, config, readAggregate()), config };
1129
+ const state = applyIdle(raw, config);
1130
+ state.usage = readUsageCache();
1131
+ return { vars: buildVars(state, config, readAggregate()), config, state };
1203
1132
  }
1204
1133
 
1205
1134
  // statusline — a compact one-line status for tmux / starship / shell prompts
1206
1135
  // and Claude Code's own statusline. `--template "..."` overrides the format.
1207
1136
  function doStatusline(argv) {
1208
- argv = splitEqArgs(argv);
1209
- let tpl = '{statusVerbose} · {project} · {modelPretty}{tokensLabelPad}';
1210
- for (let i = 0; i < argv.length; i++) {
1211
- if (argv[i] === '--template' || argv[i] === '-t') tpl = takeValue(argv[++i], '--template');
1212
- }
1137
+ const { template } = parseFlags(argv, { template: '{statusVerbose} · {project} · {modelPretty}{tokensLabelPad}' },
1138
+ { template: ['--template', '-t'] });
1213
1139
  const { vars } = liveVars();
1214
1140
  vars.tokensLabelPad = vars.tokensLabel ? ` · ${vars.tokensLabel}` : '';
1215
- process.stdout.write(fillTemplate(tpl, vars));
1141
+ process.stdout.write(fillTemplate(template, vars));
1216
1142
  }
1217
1143
 
1218
1144
  // Activity calendar — GitHub-contributions-style year heatmap SVG.
1219
1145
  // --metric hours (default) | tokens; --card wraps it in the stats card.
1220
1146
  async function doCalendar(argv) {
1221
- argv = splitEqArgs(argv);
1222
- const opts = { out: '', gist: false, metric: 'hours', card: false };
1223
- for (let i = 0; i < argv.length; i++) {
1224
- if (argv[i] === '--out' || argv[i] === '-o') opts.out = takeValue(argv[++i], '--out');
1225
- else if (argv[i] === '--gist') opts.gist = true;
1226
- else if (argv[i] === '--card') opts.card = true;
1227
- else if (argv[i] === '--metric') opts.metric = takeValue(argv[++i], '--metric');
1228
- }
1147
+ const opts = parseFlags(argv, { out: '', gist: false, metric: 'hours', card: false },
1148
+ { out: ['--out', '-o'], gist: ['--gist'], card: ['--card'], metric: ['--metric'] });
1229
1149
  if (!['hours', 'tokens'].includes(opts.metric)) {
1230
1150
  fail(`unknown --metric \`${opts.metric}\``, { hint: 'use --metric hours or --metric tokens', code: EX_USER_ERROR });
1231
1151
  }
1232
- const aggregate = readAggregate();
1233
- if (!aggregate) fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1152
+ const aggregate = aggregateOr('render');
1234
1153
  const { renderCalendar, renderCalendarCard } = await import('./calendar.js');
1235
1154
  const svg = opts.card
1236
1155
  ? renderCalendarCard(aggregate, { metric: opts.metric, handle: loadConfig().profile?.handle })
1237
1156
  : renderCalendar(aggregate, { metric: opts.metric });
1238
1157
  const kind = opts.card ? 'stats' : 'calendar';
1239
1158
  if (opts.gist) return publishBadgeToGist(svg, { metric: kind, range: 'year' }, kind);
1240
- if (opts.out) {
1241
- writeFileSync(opts.out, svg);
1242
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1243
- } else process.stdout.write(svg);
1159
+ emit(svg, opts.out);
1244
1160
  }
1245
1161
 
1246
1162
  // Per-session recap card — current/most-recent session as a shareable SVG.
1247
1163
  async function doSessionCard(argv) {
1248
- argv = splitEqArgs(argv);
1249
- const opts = { out: '' };
1250
- for (let i = 0; i < argv.length; i++) {
1251
- if (argv[i] === '--out' || argv[i] === '-o') opts.out = takeValue(argv[++i], '--out');
1252
- }
1164
+ const { out } = parseFlags(argv, { out: '' }, { out: ['--out', '-o'] });
1253
1165
  const { vars } = liveVars();
1254
1166
  const { renderSessionCard } = await import('./session-card.js');
1255
- const svg = renderSessionCard(vars, {});
1256
- if (opts.out) {
1257
- writeFileSync(opts.out, svg);
1258
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1259
- } else process.stdout.write(svg);
1167
+ emit(renderSessionCard(vars, {}), out);
1260
1168
  }
1261
1169
 
1262
1170
  // `claude-rpc readme` — paste-ready markdown for putting your live Claude Code
@@ -1330,13 +1238,7 @@ function doReadme(argv) {
1330
1238
  }
1331
1239
 
1332
1240
  console.log('');
1333
- console.log(` ${c.dim}── self-host on a GitHub gist instead (works without a profile) ──${c.reset}`);
1334
- console.log(` ${c.cyan}claude-rpc badge --metric hours --gist${c.reset} ${c.dim}# prints README markdown${c.reset}`);
1335
- console.log('');
1336
- console.log(` ${c.dim}Shareable cards:${c.reset}`);
1337
- console.log(` ${c.cyan}claude-rpc card --range year --out year.svg${c.reset} ${c.dim}# poster${c.reset}`);
1338
- console.log(` ${c.cyan}claude-rpc calendar --gist${c.reset} ${c.dim}# live year heatmap${c.reset}`);
1339
- console.log(` ${c.cyan}claude-rpc github-stat --gist${c.reset} ${c.dim}# profile stat card${c.reset}`);
1241
+ console.log(` ${c.dim}Every card as a link, PNG or SVG, from a menu:${c.reset} ${c.cyan}claude-rpc statcards${c.reset}`);
1340
1242
  console.log('');
1341
1243
  }
1342
1244
 
@@ -1347,9 +1249,12 @@ async function doMcp() {
1347
1249
  runMcpServer();
1348
1250
  }
1349
1251
 
1252
+ const mcpScope = (argv) => argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1253
+
1350
1254
  // One-command wiring into Claude Code — runs `claude mcp add` for the user.
1351
- function doMcpInstall(argv) {
1352
- const scope = argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1255
+ async function doMcpInstall(argv) {
1256
+ const { installMcp } = await import('./install.js');
1257
+ const scope = mcpScope(argv);
1353
1258
  const res = installMcp({ exePath: EXE_PATH || process.execPath, scope });
1354
1259
  const manual = (r) => `claude mcp add claude-rpc --scope ${scope} -- ${r.command} ${r.args.join(' ')}`;
1355
1260
  if (res.ok) {
@@ -1367,8 +1272,9 @@ function doMcpInstall(argv) {
1367
1272
  }
1368
1273
  }
1369
1274
 
1370
- function doMcpUninstall(argv) {
1371
- const scope = argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1275
+ async function doMcpUninstall(argv) {
1276
+ const { uninstallMcp } = await import('./install.js');
1277
+ const scope = mcpScope(argv);
1372
1278
  const res = uninstallMcp({ scope });
1373
1279
  if (res.ok) console.log(` ${c.green}✓${c.reset} removed the claude-rpc MCP server ${c.dim}(scope: ${scope})${c.reset}`);
1374
1280
  else if (res.reason === 'no-claude') fail('the `claude` CLI was not found on your PATH', { code: EX_USER_ERROR });
@@ -1384,25 +1290,30 @@ function doMcpUninstall(argv) {
1384
1290
  // Per-project overrides live in <project>/.claude-rpc.json and take priority
1385
1291
  // over the runtime list. See src/privacy.js for the full resolution chain.
1386
1292
 
1387
- function doPrivate() {
1293
+ async function doPrivate() {
1294
+ const { addPrivateCwd } = await import('./privacy.js');
1388
1295
  const cwd = process.cwd();
1389
1296
  const list = addPrivateCwd(cwd);
1390
1297
  console.log(` ${c.green}✓${c.reset} ${c.cyan}${cwd}${c.reset} marked private`);
1391
1298
  console.log(` ${c.dim}${list.length} ${list.length === 1 ? 'path' : 'paths'} in the private list — the daemon picks it up within ~5 min, or ${c.reset}${c.cyan}claude-rpc restart${c.reset}`);
1392
1299
  }
1393
1300
 
1394
- function doPublic() {
1301
+ async function doPublic() {
1302
+ const { listPrivateCwds, listVisibility, removePrivateCwd } = await import('./privacy.js');
1395
1303
  const cwd = process.cwd();
1396
- const before = listPrivateCwds().length;
1397
- const list = removePrivateCwd(cwd);
1398
- if (list.length === before) {
1304
+ // Either store may have hidden it: the private list or the dashboard's map.
1305
+ const snapshot = () => JSON.stringify([listPrivateCwds(), listVisibility()]);
1306
+ const before = snapshot();
1307
+ removePrivateCwd(cwd);
1308
+ if (snapshot() === before) {
1399
1309
  console.log(` ${c.yellow}!${c.reset} ${c.cyan}${cwd}${c.reset} wasn't in the private list`);
1400
1310
  } else {
1401
1311
  console.log(` ${c.green}✓${c.reset} ${c.cyan}${cwd}${c.reset} removed from the private list`);
1402
1312
  }
1403
1313
  }
1404
1314
 
1405
- function doPrivacy() {
1315
+ async function doPrivacy() {
1316
+ const { resolveVisibility, listPrivateCwds } = await import('./privacy.js');
1406
1317
  const cwd = process.cwd();
1407
1318
  const cfg = loadConfig();
1408
1319
  const { visibility, projectName, reason } = resolveVisibility(cwd, cfg);
@@ -1418,7 +1329,7 @@ function doPrivacy() {
1418
1329
  for (const p of list) console.log(` ${p === cwd ? c.cyan + '●' + c.reset : ' '} ${p}`);
1419
1330
  }
1420
1331
  console.log('');
1421
- console.log(` ${c.dim}toggle: claude-rpc private / claude-rpc public${c.reset}`);
1332
+ console.log(` ${c.dim}toggle: claude-rpc private / claude-rpc private off${c.reset}`);
1422
1333
  console.log(` ${c.dim}per-proj: drop a {"private": true} into .claude-rpc.json at the repo root${c.reset}`);
1423
1334
  console.log('');
1424
1335
  }
@@ -1435,7 +1346,8 @@ function fmtClock(ts) {
1435
1346
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
1436
1347
  }
1437
1348
 
1438
- function doPause(argv) {
1349
+ async function doPause(argv) {
1350
+ const { parseDuration, setPause, pauseUntil } = await import('./pause.js');
1439
1351
  const arg = (argv[0] || '').toLowerCase();
1440
1352
  if (arg === 'off' || arg === 'resume') return doResume();
1441
1353
  if (arg === 'status') {
@@ -1451,10 +1363,11 @@ function doPause(argv) {
1451
1363
  }
1452
1364
  const until = setPause(ms);
1453
1365
  console.log(` ${c.green}✓${c.reset} presence paused until ${c.cyan}${fmtClock(until)}${c.reset}`);
1454
- console.log(` ${c.dim}the daemon clears the card within seconds — resume early with ${c.reset}${c.cyan}claude-rpc resume${c.reset}`);
1366
+ console.log(` ${c.dim}the daemon clears the card within seconds — resume early with ${c.reset}${c.cyan}claude-rpc pause off${c.reset}`);
1455
1367
  }
1456
1368
 
1457
- function doResume() {
1369
+ async function doResume() {
1370
+ const { pauseUntil, clearPause } = await import('./pause.js');
1458
1371
  const was = pauseUntil();
1459
1372
  clearPause();
1460
1373
  if (was) {
@@ -1472,29 +1385,12 @@ function doResume() {
1472
1385
  // pipes cleanly into jq / a spreadsheet import.
1473
1386
 
1474
1387
  async function doExport(argv) {
1475
- argv = splitEqArgs(argv);
1476
- const csv = argv.includes('--csv');
1477
- let out = '';
1478
- for (let i = 0; i < argv.length; i++) {
1479
- if (argv[i] === '--out' || argv[i] === '-o') out = takeValue(argv[++i], '--out');
1480
- }
1481
- const aggregate = readAggregate();
1482
- if (!aggregate) {
1483
- fail('no aggregate yet — nothing to export', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1484
- }
1485
- let payload;
1486
- if (csv) {
1487
- const { aggregateToCsv } = await import('./server/api.js');
1488
- payload = aggregateToCsv(aggregate);
1489
- } else {
1490
- payload = JSON.stringify(aggregate, null, 2) + '\n';
1491
- }
1492
- if (out) {
1493
- writeFileSync(out, payload);
1494
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${out}${c.reset} ${c.dim}(${payload.length} bytes, ${csv ? 'CSV' : 'JSON'})${c.reset}`);
1495
- } else {
1496
- process.stdout.write(payload);
1497
- }
1388
+ const { csv, out } = parseFlags(argv, { csv: false, out: '' }, { csv: ['--csv'], out: ['--out', '-o'] });
1389
+ const aggregate = aggregateOr('export');
1390
+ const payload = csv
1391
+ ? (await import('./server/api.js')).aggregateToCsv(aggregate)
1392
+ : JSON.stringify(aggregate, null, 2) + '\n';
1393
+ emit(payload, out, { note: `${payload.length} bytes, ${csv ? 'CSV' : 'JSON'}` });
1498
1394
  }
1499
1395
 
1500
1396
  // ── Squads — private mini-leaderboards (terminal parity for the web UI) ───
@@ -1522,30 +1418,24 @@ function squadAuth() {
1522
1418
  code: EX_BAD_STATE,
1523
1419
  });
1524
1420
  }
1525
- const netFail = (e) => fail(`couldn't reach the squads service: ${e.message}`, {
1526
- hint: 'check your connection and retry — this never blocks Claude Code',
1527
- code: EX_SYS_ERROR,
1528
- });
1529
- const post = async (path, body) => {
1421
+ const call = async (path, init = {}) => {
1530
1422
  let res;
1531
1423
  try {
1532
- res = await fetch(endpoint + path, {
1533
- method: 'POST',
1534
- headers: { 'Content-Type': 'application/json' },
1535
- body: JSON.stringify({ instanceId, ...body }),
1536
- signal: AbortSignal.timeout(10_000),
1424
+ res = await fetch(endpoint + path, { ...init, signal: AbortSignal.timeout(10_000) });
1425
+ } catch (e) {
1426
+ return fail(`couldn't reach the squads service: ${e.message}`, {
1427
+ hint: 'check your connection and retry — this never blocks Claude Code',
1428
+ code: EX_SYS_ERROR,
1537
1429
  });
1538
- } catch (e) { return netFail(e); }
1539
- return { status: res.status, json: await res.json().catch(() => ({})) };
1540
- };
1541
- const get = async (path) => {
1542
- let res;
1543
- try {
1544
- res = await fetch(endpoint + path, { signal: AbortSignal.timeout(10_000) });
1545
- } catch (e) { return netFail(e); }
1430
+ }
1546
1431
  return { status: res.status, json: await res.json().catch(() => ({})) };
1547
1432
  };
1548
- return { cfg, endpoint, instanceId, post, get };
1433
+ const post = (path, body) => call(path, {
1434
+ method: 'POST',
1435
+ headers: { 'Content-Type': 'application/json' },
1436
+ body: JSON.stringify({ instanceId, ...body }),
1437
+ });
1438
+ return { cfg, endpoint, instanceId, post, get: call };
1549
1439
  }
1550
1440
 
1551
1441
  function squadPageUrl(id) { return `https://claude-rpc.com/squad/${id}`; }
@@ -1735,7 +1625,8 @@ async function doLink(argv) {
1735
1625
  // for the receiving end. As of v0.7 this is on by default for fresh
1736
1626
  // installs and preserved-off for pre-v0.7 upgraders (see migrateConfig).
1737
1627
 
1738
- function prompt(question) {
1628
+ async function prompt(question) {
1629
+ const { createInterface } = await import('node:readline');
1739
1630
  return new Promise((resolve) => {
1740
1631
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1741
1632
  rl.question(question, (answer) => { rl.close(); resolve(answer); });
@@ -1794,13 +1685,18 @@ async function communityOn() {
1794
1685
  return;
1795
1686
  }
1796
1687
  const userCfg = readJson(CONFIG_PATH, {});
1688
+ const { randomUUID } = await import('node:crypto');
1689
+ const priorId = userCfg.community?.instanceId || community.instanceId;
1797
1690
  const next = {
1798
1691
  ...(userCfg.community || {}),
1799
1692
  enabled: true,
1800
- instanceId: userCfg.community?.instanceId || community.instanceId || randomUUID(),
1693
+ instanceId: priorId || randomUUID(),
1801
1694
  };
1802
1695
  userCfg.community = next;
1803
1696
  writeUserConfig(userCfg);
1697
+ // A brand-new id has reported nothing: its first flush sends the history.
1698
+ // A re-enable keeps its cursor (see community.ensureCursor).
1699
+ if (!priorId) (await import('./community.js')).markCursorFresh();
1804
1700
  console.log('');
1805
1701
  console.log(` ${c.green}✓${c.reset} community totals enabled`);
1806
1702
  console.log(` ${c.dim}id: …${next.instanceId.slice(-8)}${c.reset}`);
@@ -1976,7 +1872,7 @@ function profileSet(argv) {
1976
1872
  profileNextStep();
1977
1873
  }
1978
1874
 
1979
- function profileEnable(on) {
1875
+ async function profileEnable(on) {
1980
1876
  const userCfg = readJson(CONFIG_PATH, {});
1981
1877
  const next = { ...(userCfg.profile || {}) };
1982
1878
  if (on && !lb.isValidHandle(next.handle)) {
@@ -1992,8 +1888,9 @@ function profileEnable(on) {
1992
1888
  if (on) {
1993
1889
  const community = { ...(userCfg.community || {}) };
1994
1890
  if (!community.instanceId) {
1995
- community.instanceId = randomUUID();
1891
+ community.instanceId = (await import('node:crypto')).randomUUID();
1996
1892
  userCfg.community = community;
1893
+ (await import('./community.js')).markCursorFresh();
1997
1894
  }
1998
1895
  }
1999
1896
  userCfg.profile = next;
@@ -2201,7 +2098,7 @@ async function setupGhConnect() {
2201
2098
  // privacy filter can't see everything the presence valve can, so the human
2202
2099
  // check is part of the design, not politeness).
2203
2100
  async function doWrappedPublish(argv) {
2204
- await loadStats();
2101
+ await loadCore();
2205
2102
  const cfg = loadConfig();
2206
2103
  const aggregate = readAggregate();
2207
2104
  if (!aggregate) return fail('no aggregate yet', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
@@ -2214,8 +2111,11 @@ async function doWrappedPublish(argv) {
2214
2111
  const instanceId = cfg.community?.instanceId;
2215
2112
  if (!instanceId) return fail('no instanceId — run `claude-rpc setup`', { code: EX_BAD_STATE });
2216
2113
 
2217
- const yearFlag = argv.indexOf('--year');
2218
- const year = yearFlag !== -1 ? Number(argv[yearFlag + 1]) : new Date().getFullYear();
2114
+ const opts = parseFlags(argv, { year: String(new Date().getFullYear()), yes: false }, { year: ['--year'], yes: ['--yes'] });
2115
+ if (!/^\d{4}$/.test(opts.year)) {
2116
+ return fail(`--year needs a 4-digit year, got \`${opts.year}\``, { hint: 'e.g. --year 2025', code: EX_USER_ERROR });
2117
+ }
2118
+ const year = Number(opts.year);
2219
2119
  const { buildWrappedPayload, publishWrapped } = await import('./community.js');
2220
2120
  const payload = buildWrappedPayload(aggregate, cfg, { instanceId, year });
2221
2121
  const w = payload.wrapped;
@@ -2240,7 +2140,7 @@ async function doWrappedPublish(argv) {
2240
2140
  console.log(` ${c.dim}full payload: the fields above plus lines/cache%/peaks — nothing else.${c.reset}`);
2241
2141
  console.log(` ${c.dim}private-listed and pattern-matched project names are already excluded.${c.reset}\n`);
2242
2142
 
2243
- if (!argv.includes('--yes')) {
2143
+ if (!opts.yes) {
2244
2144
  if (!process.stdout.isTTY) {
2245
2145
  return fail('refusing to publish without confirmation on a non-TTY', {
2246
2146
  hint: 'pass --yes to publish non-interactively', code: EX_USER_ERROR,
@@ -2386,75 +2286,103 @@ function overview() {
2386
2286
  console.log('');
2387
2287
  }
2388
2288
 
2389
- function help() {
2390
- const cmds = [
2391
- ['setup', 'Install Claude Code hooks + Windows startup entry (~/.claude/settings.json)'],
2392
- ['setup --link <code>', 'One-liner onboarding: install + verify via a claude-rpc.com code (+ --wrapped publishes your year)'],
2393
- ['uninstall', 'Remove Claude Code hooks + Windows startup entry'],
2394
- ['upgrade-config', 'Re-run idempotent migrations on an existing config.json'],
2395
- ['start', 'Start the Discord RPC daemon (detached)'],
2396
- ['stop', 'Stop the daemon'],
2397
- ['restart', 'Stop then start the daemon'],
2398
- ['status', 'Interactive stats TUI; --dump (or piped) prints static text'],
2399
- ['today', 'Focus view: today\'s stats + 24h activity histogram'],
2400
- ['week', 'Focus view: this week, daily breakdown'],
2401
- ['compare', 'This week vs last week — the full side-by-side diff'],
2402
- ['projects', 'Every project ranked by active time (--limit N)'],
2403
- ['project', 'One project\'s full record + recent daily rhythm'],
2404
- ['usage', 'Subscription limits — session + weekly % (what /usage shows)'],
2405
- ['serve', 'Open a live web dashboard in your browser'],
2406
- ['preview', 'Show how each rotation frame renders right now'],
2407
- ['scan', 'Incrementally scan ~/.claude/projects for all-time totals'],
2408
- ['rescan', 'Force re-parse every transcript (ignores cache)'],
2409
- ['backfill', 'Import transcripts from any folder (e.g. a backup)'],
2410
- ['insights', 'Auto-generated insights from your history'],
2411
- ['recap', 'Standup summary (yesterday by default; today|week|date, --md for markdown)'],
2412
- ['badge', 'Render a Shields-style SVG (--metric --range --out --gist)'],
2413
- ['card', 'Render a poster-style SVG summary (--range year|month|week|all)'],
2414
- ['github-stat', 'Render an embeddable profile stat card (--handle --out --gist)'],
2415
- ['statusline', 'One-line status for tmux/shell prompts (--template)'],
2416
- ['calendar', 'Year activity heatmap SVG (--metric hours|tokens --card --out --gist)'],
2417
- ['session-card', 'Recap card for the current session (--out)'],
2418
- ['readme', 'Paste-ready README card + badges for your profile (--raw to pipe)'],
2419
- ['mcp install', 'Wire the stats MCP server into Claude Code (one command)'],
2420
- ['mcp uninstall', 'Remove the stats MCP server from Claude Code'],
2421
- ['mcp', 'Run the MCP server (stdio) — exposes your stats to Claude'],
2422
- ['wrapped', 'Open your animated year-in-review (Claude Wrapped)'],
2423
- ['wrapped --publish', 'Put your Wrapped on the web at claude-rpc.com/wrapped/<handle>'],
2424
- ['pause', 'Snooze the Discord card globally (pause [30m|2h], default 1h)'],
2425
- ['resume', 'Lift a pause early'],
2426
- ['export', 'Dump the aggregate as JSON, or daily rows as CSV (--csv --out)'],
2427
- ['private', 'Mark the current directory as private (hide from Discord)'],
2428
- ['public', 'Un-mark the current directory'],
2429
- ['privacy', 'Show resolved visibility for the current directory'],
2430
- ['community', 'Opt in/out of anonymous community totals (on|off|status|report)'],
2431
- ['profile', 'Public leaderboard identity (status|set|on|off|publish|verify)'],
2432
- ['squad', 'Private mini-leaderboards with friends (create|join|leave|status)'],
2433
- ['link', 'Link machines into one profile (mints a code; `link <code>` claims it)'],
2434
- ['doctor', 'Run a diagnostic checklist — common-failure triage (--fix to auto-repair)'],
2435
- ['tail', 'Tail the daemon log file'],
2436
- ['daemon', 'Run daemon in foreground (debug)'],
2437
- ];
2438
- const colW = cmds.reduce((m, [name]) => Math.max(m, name.length), 0);
2439
- console.log('');
2440
- console.log(` ${c.bold}${c.magenta}◆ claude-rpc${c.reset} ${c.dim}— Discord Rich Presence for Claude Code${c.reset}`);
2441
- console.log('');
2442
- console.log(` ${c.dim}Commands:${c.reset}`);
2443
- for (const [name, desc] of cmds) {
2444
- console.log(` ${c.cyan}${name.padEnd(colW)}${c.reset} ${desc}`);
2289
+ async function help(name) {
2290
+ const { renderHelp, renderCommandHelp } = await import('./help.js');
2291
+ if (!name) { console.log(renderHelp()); return; }
2292
+ const page = renderCommandHelp(name);
2293
+ if (page) { console.log(page); return; }
2294
+ const { suggestCommand } = await import('./commands.js');
2295
+ const guess = suggestCommand(name);
2296
+ fail(`no command called \`${name}\``, {
2297
+ hint: guess ? `did you mean \`claude-rpc help ${guess}\`?` : 'claude-rpc help lists them all',
2298
+ code: EX_USER_ERROR,
2299
+ });
2300
+ }
2301
+
2302
+ // `__complete <words…>` — candidates for the shell scripts in completion.js,
2303
+ // one per line. Never prints errors: a broken <Tab> must stay silent.
2304
+ async function doComplete(words) {
2305
+ const { complete } = await import('./commands.js');
2306
+ if (process.env.CLAUDE_RPC_COMP_CUR !== undefined) words = [...words, process.env.CLAUDE_RPC_COMP_CUR];
2307
+ const projects = () => {
2308
+ try { return Object.keys(JSON.parse(readFileSync(AGGREGATE_PATH, 'utf8')).projects || {}); } catch { return []; }
2309
+ };
2310
+ try {
2311
+ const out = complete(words, { projects });
2312
+ if (out.length) process.stdout.write(out.join('\n') + '\n');
2313
+ } catch { /* stay silent */ }
2314
+ }
2315
+
2316
+ // `completion [install|uninstall|<shell>]`
2317
+ async function doCompletion(argv) {
2318
+ const comp = await import('./completion.js');
2319
+ const { SHELLS } = await import('./commands.js');
2320
+ const sub = argv[0] || '';
2321
+ if (SHELLS.includes(sub)) { process.stdout.write(comp.scriptFor(sub)); return; }
2322
+ const shell = (sub === 'install' && argv[1]) || comp.detectShell();
2323
+ if (sub === 'install' && !SHELLS.includes(shell)) {
2324
+ return fail(`unknown shell: ${shell}`, { hint: `one of: ${SHELLS.join(', ')}`, code: EX_USER_ERROR });
2325
+ }
2326
+ const opts = { configDir: USER_CONFIG_DIR, profilePath: shell === 'powershell' ? await comp.powershellProfile() : undefined };
2327
+ if (sub === 'install') {
2328
+ let r;
2329
+ try { r = comp.install(shell, opts); } catch (e) { return fail(e.message, { code: EX_SYS_ERROR }); }
2330
+ if (!r.changed) { console.log(` ${c.green}✓${c.reset} tab completion already on for ${c.bold}${shell}${c.reset}`); return; }
2331
+ console.log(` ${c.green}✓${c.reset} tab completion on for ${c.bold}${shell}${c.reset} ${c.dim}${shortPath(r.rc || r.script)}${c.reset}`);
2332
+ const reload = shell === 'fish' ? 'works in new fish sessions'
2333
+ : shell === 'powershell' ? 'open a new PowerShell window'
2334
+ : `open a new terminal, or: ${c.reset}${c.cyan}source ${shortPath(r.rc)}${c.reset}${c.dim}`;
2335
+ console.log(` ${c.dim}${reload} — then try ${c.reset}${c.cyan}claude-rpc st<Tab>${c.reset}`);
2336
+ return;
2445
2337
  }
2338
+ if (sub === 'uninstall') {
2339
+ const touched = comp.uninstall(opts);
2340
+ console.log(touched.length
2341
+ ? ` ${c.green}✓${c.reset} tab completion removed ${c.dim}${touched.map(shortPath).join(', ')}${c.reset}`
2342
+ : ` ${c.cyan}·${c.reset} tab completion wasn't installed`);
2343
+ return;
2344
+ }
2345
+ if (sub) return fail(`unknown option: ${sub}`, { hint: 'claude-rpc completion [install|uninstall|bash|zsh|fish|powershell]', code: EX_USER_ERROR });
2346
+ const on = comp.isInstalled(shell, opts);
2446
2347
  console.log('');
2447
- console.log(` ${c.dim}First-time setup:${c.reset}`);
2448
- console.log(` 1. ${c.cyan}claude-rpc setup${c.reset} — wires hooks, seeds config, starts the daemon.`);
2449
- console.log(` 2. Open Claude Code and send a prompt — the card appears in Discord.`);
2450
- console.log(` 3. ${c.dim}(optional)${c.reset} Use your own Discord app: set ${c.cyan}clientId${c.reset} in ${c.cyan}config.json${c.reset} and upload art under Rich Presence → Art Assets: ${c.cyan}claude${c.reset}, ${c.cyan}working${c.reset}, ${c.cyan}idle${c.reset}, ${c.cyan}thinking${c.reset}.`);
2451
- console.log('');
2452
- console.log(` ${c.dim}Tip: ${c.reset}edit ${c.cyan}config.json${c.reset} to customize rotation frames. Run ${c.cyan}claude-rpc preview${c.reset} to see the result without Discord.`);
2348
+ console.log(` ${c.bold}${c.magenta}◆ Tab completion${c.reset} ${c.dim}— ${shell}${c.reset} ${on ? `${c.green}● on${c.reset}` : `${c.yellow}○ off${c.reset}`}`);
2453
2349
  console.log('');
2454
- console.log(` ${c.dim}Exit codes:${c.reset} ${c.dim}0 ok · 1 user error · 2 system error · 3 wrong state${c.reset}`);
2350
+ if (!on) console.log(` ${c.cyan}claude-rpc completion install${c.reset} ${c.dim}turn it on for ${shell}${c.reset}`);
2351
+ else console.log(` ${c.cyan}claude-rpc completion uninstall${c.reset} ${c.dim}turn it off${c.reset}`);
2352
+ console.log(` ${c.cyan}claude-rpc completion <shell>${c.reset} ${c.dim}print the script (${SHELLS.join(', ')})${c.reset}`);
2455
2353
  console.log('');
2456
2354
  }
2457
2355
 
2356
+ // Offer tab completion once during a first setup, on a terminal only.
2357
+ async function setupCompletionOffer() {
2358
+ if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CLAUDE_RPC_NO_COMPLETION) return;
2359
+ const comp = await import('./completion.js');
2360
+ const shell = comp.detectShell();
2361
+ const profilePath = shell === 'powershell' ? await comp.powershellProfile() : undefined;
2362
+ const opts = { configDir: USER_CONFIG_DIR, profilePath };
2363
+ if (shell === 'powershell' && !profilePath) return;
2364
+ if (comp.isInstalled(shell, opts)) return;
2365
+ const answer = (await prompt(` tab completion for ${shell}? ${c.dim}[Y/n]${c.reset} `)).trim().toLowerCase();
2366
+ if (answer && answer !== 'y' && answer !== 'yes') return;
2367
+ try {
2368
+ const r = comp.install(shell, opts);
2369
+ console.log(` ${c.green}✓${c.reset} ${'tab completion'.padEnd(16)}${c.dim}${shell} · ${shortPath(r.rc || r.script)} (new terminals)${c.reset}`);
2370
+ } catch (e) {
2371
+ console.log(` ${c.yellow}!${c.reset} ${'tab completion'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
2372
+ }
2373
+ }
2374
+
2375
+ async function doStatcards(argv) {
2376
+ const { runStatcards } = await import('./statcards.js');
2377
+ await runStatcards(argv, {
2378
+ config: loadConfig(),
2379
+ aggregate: () => aggregateOr('render'),
2380
+ liveVars: () => liveVars().vars,
2381
+ prompt,
2382
+ enableProfile: () => profileEnable(true),
2383
+ });
2384
+ }
2385
+
2458
2386
  // Packaged exe: `claude-rpc.exe` with no args → first-run install + start.
2459
2387
  // `claude-rpc.exe hook PreToolUse` → handle hook.
2460
2388
  // Dev mode keeps the original `help` fallback so behavior is unchanged.
@@ -2472,29 +2400,47 @@ process.on('unhandledRejection', (e) => {
2472
2400
  // ESM (dev) and CommonJS (esbuild → SEA bundle) — CJS doesn't allow
2473
2401
  // top-level await.
2474
2402
  (async () => {
2475
- // Fast-exit commands touch none of the lazy stats/format/install graph, so
2476
- // skip the module load and keep them instant. Everything else loads it once
2477
- // up front, which makes every binding available to the handlers below exactly
2478
- // as before. (daemon/serve/wrapped/hook only dynamic-import their own module.)
2479
- const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', 'start', 'stop', 'restart', 'hook', 'daemon', 'serve', 'wrapped']);
2480
- if (!FAST_PATHS.has(cmd)) await loadStats();
2403
+ // Force the console code page to UTF-8 (65001) on Windows so Unicode box
2404
+ // drawing, block elements, and other chars render correctly. Default cmd.exe
2405
+ // code page on Win10 is 437/850, which displays many of our chars as `?`.
2406
+ // Hook events (no TTY) skip this — they don't print anything user-visible.
2407
+ if (process.platform === 'win32' && process.stdout.isTTY) {
2408
+ const { spawnSync } = await import('node:child_process');
2409
+ try { spawnSync('chcp.com', ['65001'], { stdio: 'ignore', windowsHide: true }); } catch { /* chcp absent (Wine, custom shell) — accept whatever code page is set */ }
2410
+ }
2411
+ // Fast-exit commands touch none of the core graph (they import their own
2412
+ // module, if any); daemon control needs only ensure-daemon. Everything else
2413
+ // loads the core once up front, so its bindings are set for every handler.
2414
+ const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', '__complete', 'hook', 'mcp', 'daemon', 'serve', 'wrapped', 'scan-worker', 'tail', 'logs', 'log', 'pause', 'resume', 'unpause']);
2415
+ // `<command> --help` → that command's page (before it runs at all).
2416
+ if (cmd && (args.includes('--help') || args.includes('-h')) && !['hook', 'scan-worker', '__complete'].includes(cmd)) {
2417
+ const { findCommand } = await import('./commands.js');
2418
+ if (findCommand(cmd)) { await help(cmd); return; }
2419
+ }
2420
+ if (['start', 'stop', 'restart'].includes(cmd)) await loadDaemonCtl();
2421
+ else if (!FAST_PATHS.has(cmd)) await loadCore();
2481
2422
  switch (cmd) {
2482
2423
  case '--version':
2483
2424
  case '-V':
2484
2425
  case '-v': console.log(`claude-rpc ${VERSION}`); break;
2485
2426
  case '--help':
2486
2427
  case '-h':
2487
- case 'help': help(); break;
2428
+ case 'help': await help(cmd === 'help' ? args[0] : undefined); break;
2429
+ case '__complete': await doComplete(args); break;
2430
+ case 'completion': await doCompletion(args); break;
2431
+ case 'statcards': await doStatcards(args); break;
2488
2432
  // `setup` and `install` are aliases as of v0.7: both register hooks AND
2489
- // the Windows startup entry. Older behavior split them (setup = no
2490
- // startup, install = with) but in practice users expect one command
2491
- // to do everything. Non-Windows: addStartupEntry is a no-op + warning.
2433
+ // the login autostart entry (Windows Run key, macOS LaunchAgent, Linux
2434
+ // systemd --user unit). Older behavior split them (setup = no startup,
2435
+ // install = with) but in practice users expect one command to do
2436
+ // everything. Other platforms skip autostart with an info row.
2492
2437
  case 'setup':
2493
2438
  case 'install': {
2494
2439
  // runInstall prints the phased checklist (or a one-line "already set
2495
2440
  // up" on clean re-runs); the daemon row lands after it, then setupOutro
2496
2441
  // closes the screen — only when something actually changed.
2497
- const { target, changed } = await runInstall({ exePath: EXE_PATH || process.execPath });
2442
+ const { install: runInstall, setupOutro } = await import('./install.js');
2443
+ const { target, changed, cli } = await runInstall({ exePath: EXE_PATH || process.execPath });
2498
2444
  // Slimmer first run: bring the daemon up now so the card appears
2499
2445
  // immediately, instead of making the user run a separate `start`.
2500
2446
  // Best-effort — a start hiccup must never make `setup` look failed.
@@ -2511,6 +2457,7 @@ process.on('unhandledRejection', (e) => {
2511
2457
  // pops it as a visible Windows Terminal window whose closure kills
2512
2458
  // the daemon.
2513
2459
  if (!daemonAlive()) {
2460
+ const { spawn, spawnSync } = await import('node:child_process');
2514
2461
  let script = null;
2515
2462
  try {
2516
2463
  const r = spawnSync('npm', ['root', '-g'], {
@@ -2547,13 +2494,11 @@ process.on('unhandledRejection', (e) => {
2547
2494
  // best-effort-loud: a failure explains itself but never rolls back the
2548
2495
  // completed install above.
2549
2496
  {
2550
- const argv = process.argv.slice(3);
2551
- const linkAt = argv.indexOf('--link');
2552
- const linkCode = linkAt !== -1 ? (argv[linkAt + 1] || '').trim() : null;
2497
+ const linkAt = args.indexOf('--link');
2498
+ const linkCode = linkAt !== -1 ? (args[linkAt + 1] || '').trim() : null;
2553
2499
  if (linkCode) {
2554
2500
  console.log('');
2555
- await doLink([linkCode]);
2556
- if (process.exitCode) break; // link failed — its own message + hint already printed
2501
+ await doLink([linkCode]); // a failed link exits via fail() with its own message + hint
2557
2502
  console.log(` ${c.dim}first scan — counting your history…${c.reset}`);
2558
2503
  doScan(false);
2559
2504
  const { flushProfile } = await import('./community.js');
@@ -2561,73 +2506,91 @@ process.on('unhandledRejection', (e) => {
2561
2506
  if (flushed.ok) {
2562
2507
  console.log(` ${c.green}✓${c.reset} profile published — ${c.cyan}${fmtNum(flushed.totals.tokens)}${c.reset} tokens on the board`);
2563
2508
  }
2564
- if (argv.includes('--wrapped')) await doWrappedPublish(['--yes']);
2565
- } else if (argv.includes('--wrapped')) {
2509
+ if (args.includes('--wrapped')) await doWrappedPublish(['--yes']);
2510
+ } else if (args.includes('--wrapped')) {
2566
2511
  console.log(` ${c.yellow}!${c.reset} --wrapped needs a profile — pair it with --link <code>, or run \`claude-rpc wrapped --publish\` after setup`);
2567
2512
  }
2568
2513
  // Optional GitHub connect — one explicit y/N, asked at most once ever.
2569
2514
  // The --link path above IS a connect, so it never double-asks.
2570
2515
  if (!linkCode) await setupGhConnect();
2516
+ if (changed) await setupCompletionOffer();
2571
2517
  }
2572
- setupOutro(target, changed);
2518
+ setupOutro(target, changed, cli);
2519
+ break;
2520
+ }
2521
+ case 'uninstall': {
2522
+ const { uninstall: completionOff } = await import('./completion.js');
2523
+ try { completionOff({ configDir: USER_CONFIG_DIR, profilePath: process.platform === 'win32' ? await (await import('./completion.js')).powershellProfile() : undefined }); } catch { /* best-effort */ }
2524
+ await (await import('./install.js')).uninstall();
2573
2525
  break;
2574
2526
  }
2575
- case 'uninstall': await runUninstall(); break;
2576
2527
  case 'upgrade-config':
2577
- if (!migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2528
+ if (!(await import('./install.js')).migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2578
2529
  break;
2579
2530
  case 'start': if (startDaemon()) await confirmDaemonUp(); break;
2580
2531
  case 'stop': stopDaemon(); break;
2581
- case 'restart': restartDaemon(); break;
2532
+ case 'restart': if (await restartDaemon()) await confirmDaemonUp(); break;
2582
2533
  case 'status': {
2583
- const dumpFlag = process.argv.slice(3).some((a) => a === '--dump' || a === '-d');
2584
- if (dumpFlag || !process.stdout.isTTY) showStatus();
2585
- else startTui();
2534
+ const dumpFlag = args.some((a) => a === '--dump' || a === '-d');
2535
+ if (dumpFlag || !process.stdout.isTTY) await showStatus();
2536
+ else (await import('./tui.js')).startTui();
2537
+ break;
2538
+ }
2539
+ case 'dump': await showStatus(); break;
2540
+ case 'today': await showToday(); break;
2541
+ case 'week': if (args.includes('--compare')) showCompare(); else await showWeek(); break;
2542
+ case 'projects': {
2543
+ // `projects <name>` drills into one project (was `project <name>`).
2544
+ const name = args.find((a, i) => !a.startsWith('-') && args[i - 1] !== '--limit');
2545
+ if (name) showProject(name); else showProjects(args);
2586
2546
  break;
2587
2547
  }
2588
- case 'dump': showStatus(); break;
2589
- case 'today': showToday(); break;
2590
- case 'week': showWeek(); break;
2591
- case 'projects': showProjects(process.argv.slice(3)); break;
2592
- case 'project': showProject(process.argv[3]); break;
2548
+ case 'project': showProject(args[0]); break;
2593
2549
  case 'compare': showCompare(); break;
2594
2550
  case 'usage': await showUsage(); break;
2595
2551
  case 'serve': await import('./server/index.js'); break;
2596
2552
  case 'preview': showPreview(); break;
2597
2553
  case 'vars': dumpVars(); break;
2598
- case 'scan': doScan(false); break;
2554
+ case 'scan': doScan(args.includes('--force') || args.includes('-f')); break;
2599
2555
  case 'rescan': doScan(true); break;
2600
- case 'backfill': doBackfill(process.argv.slice(3)); break;
2601
- case 'insights': showInsights(); break;
2602
- case 'recap': await doRecap(process.argv.slice(3)); break;
2603
- case 'badge': await doBadge(process.argv.slice(3)); break;
2604
- case 'card': await doCard(process.argv.slice(3)); break;
2605
- case 'github-stat': await doGithubStat(process.argv.slice(3)); break;
2606
- case 'statusline': doStatusline(process.argv.slice(3)); break;
2607
- case 'calendar': await doCalendar(process.argv.slice(3)); break;
2608
- case 'session-card': await doSessionCard(process.argv.slice(3)); break;
2609
- case 'readme': doReadme(process.argv.slice(3)); break;
2556
+ case 'backfill': doBackfill(args); break;
2557
+ case 'insights': await showInsights(); break;
2558
+ case 'recap': await doRecap(args); break;
2559
+ case 'badge': await doBadge(args); break;
2560
+ case 'card': await doCard(args); break;
2561
+ case 'github-stat': await doGithubStat(args); break;
2562
+ case 'statusline': doStatusline(args); break;
2563
+ case 'calendar': await doCalendar(args); break;
2564
+ case 'session-card': await doSessionCard(args); break;
2565
+ case 'readme': doReadme(args); break;
2610
2566
  case 'mcp': {
2611
- const sub = process.argv[3];
2612
- if (sub === 'install') { doMcpInstall(process.argv.slice(4)); break; }
2613
- if (sub === 'uninstall') { doMcpUninstall(process.argv.slice(4)); break; }
2567
+ const sub = args[0];
2568
+ if (sub === 'install') { await doMcpInstall(args.slice(1)); break; }
2569
+ if (sub === 'uninstall') { await doMcpUninstall(args.slice(1)); break; }
2614
2570
  await doMcp();
2615
2571
  break;
2616
2572
  }
2617
2573
  case 'wrapped':
2618
- if (process.argv.slice(3).includes('--publish')) { await doWrappedPublish(process.argv.slice(3)); break; }
2574
+ if (args.includes('--publish')) { await doWrappedPublish(args); break; }
2619
2575
  process.env.CLAUDE_RPC_OPEN_PATH = '/wrapped'; await import('./server/index.js'); break;
2620
- case 'pause': doPause(process.argv.slice(3)); break;
2576
+ case 'pause': await doPause(args); break;
2621
2577
  case 'resume':
2622
- case 'unpause': doResume(); break;
2623
- case 'export': await doExport(process.argv.slice(3)); break;
2624
- case 'private': doPrivate(); break;
2625
- case 'public': doPublic(); break;
2626
- case 'privacy': doPrivacy(); break;
2627
- case 'community': await doCommunity(process.argv.slice(3)); break;
2628
- case 'profile': await doProfile(process.argv.slice(3)); break;
2629
- case 'squad': await doSquadCmd(process.argv.slice(3)); break;
2630
- case 'link': await doLink(process.argv.slice(3)); break;
2578
+ case 'unpause': await doResume(); break;
2579
+ case 'export': await doExport(args); break;
2580
+ case 'private': {
2581
+ const sub = args[0] || 'on';
2582
+ if (sub === 'on') await doPrivate();
2583
+ else if (sub === 'off') await doPublic();
2584
+ else if (sub === 'status') await doPrivacy();
2585
+ else fail(`unknown option: ${sub}`, { hint: 'claude-rpc private [on|off|status]', code: EX_USER_ERROR });
2586
+ break;
2587
+ }
2588
+ case 'public': await doPublic(); break;
2589
+ case 'privacy': await doPrivacy(); break;
2590
+ case 'community': await doCommunity(args); break;
2591
+ case 'profile': await doProfile(args); break;
2592
+ case 'squad': await doSquadCmd(args); break;
2593
+ case 'link': await doLink(args); break;
2631
2594
  case 'doctor': {
2632
2595
  const { runDoctor, fixPlan } = await import('./doctor.js');
2633
2596
  const fix = process.argv.includes('--fix');
@@ -2647,13 +2610,13 @@ process.on('unhandledRejection', (e) => {
2647
2610
  for (const kind of plan) {
2648
2611
  try {
2649
2612
  if (kind === 'setup') {
2650
- await runInstall({ exePath: EXE_PATH || process.execPath });
2613
+ await (await import('./install.js')).install({ exePath: EXE_PATH || process.execPath });
2651
2614
  console.log(` ${c.green}✓${c.reset} config + hooks repaired`);
2652
2615
  } else if (kind === 'rescan') {
2653
2616
  doScan(true);
2654
2617
  console.log(` ${c.green}✓${c.reset} aggregate rebuilt from transcripts`);
2655
2618
  } else if (kind === 'daemon') {
2656
- restartDaemon();
2619
+ await restartDaemon();
2657
2620
  restarted = true;
2658
2621
  console.log(` ${c.green}✓${c.reset} daemon (re)starting`);
2659
2622
  } else if (kind === 'discord') {
@@ -2665,22 +2628,23 @@ process.on('unhandledRejection', (e) => {
2665
2628
  }
2666
2629
  // A 'setup' rewire only takes effect once the daemon reloads, so ensure a
2667
2630
  // restart even if the daemon wasn't itself flagged.
2668
- if (plan.includes('setup') && !restarted) restartDaemon();
2631
+ if (plan.includes('setup') && !restarted) await restartDaemon();
2669
2632
  console.log(` ${c.dim}run ${c.cyan}claude-rpc doctor${c.reset}${c.dim} again in a few seconds to confirm.${c.reset}`);
2670
- break; // let the restart timer fire before the process drains
2633
+ break;
2671
2634
  }
2672
2635
  case 'tail':
2673
2636
  case 'logs':
2674
2637
  case 'log': tailLog(); break;
2675
- case 'hook': runHookCli(process.argv[3] || 'unknown'); break;
2638
+ case 'hook': (await import('./hook.js')).runHookCli(args[0] || 'unknown'); break;
2676
2639
  case 'daemon': await import('./daemon.js'); break;
2677
2640
  case 'scan-worker': (await import('./scan-worker.js')).runScanWorker(process.argv.includes('--force')); break;
2678
2641
  default: {
2679
2642
  if (packagedDefault) {
2643
+ const { isInstalled, install: runInstall, setupOutro, ensureCanonicalExe, migrateConfig, installHooks } = await import('./install.js');
2680
2644
  if (!isInstalled()) {
2681
- const { target } = await runInstall({ exePath: EXE_PATH || process.execPath });
2645
+ const { target, cli } = await runInstall({ exePath: EXE_PATH || process.execPath });
2682
2646
  startDaemon();
2683
- setupOutro(target);
2647
+ setupOutro(target, true, cli);
2684
2648
  } else {
2685
2649
  // Self-heal an existing install. Two real failure modes this fixes:
2686
2650
  //
@@ -2725,10 +2689,17 @@ process.on('unhandledRejection', (e) => {
2725
2689
  // Version in the hint is deliberate: the #1 cause of "unknown
2726
2690
  // command" in the wild is a stale global install resolving instead of
2727
2691
  // the version the user read the docs for. Make the skew visible.
2692
+ // The update command depends on how this copy was installed.
2693
+ const update = IS_PACKAGED ? 'download the latest release from https://github.com/rar-file/claude-rpc/releases/latest'
2694
+ : IS_NPX ? `npx claude-rpc@latest ${cmd}`
2695
+ : /[\\/]Cellar[\\/]/.test(DAEMON_SCRIPT) ? 'brew upgrade claude-rpc'
2696
+ : 'npm install -g claude-rpc@latest';
2697
+ const { suggestCommand } = await import('./commands.js');
2698
+ const guess = suggestCommand(cmd);
2728
2699
  fail(`unknown command: ${cmd}`, {
2729
- hint: [
2730
- 'run `claude-rpc --help` for the full command list',
2731
- `this install is v${VERSION} — if the docs mention \`${cmd}\`, update first: npm install -g claude-rpc@latest`,
2700
+ hint: guess ? `did you mean \`claude-rpc ${guess}\`?` : [
2701
+ 'run `claude-rpc help` for the full command list',
2702
+ `this install is v${VERSION} — if the docs mention \`${cmd}\`, update first: ${update}`,
2732
2703
  ],
2733
2704
  code: EX_USER_ERROR,
2734
2705
  });