claude-rpc 1.5.4 → 1.7.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.
package/src/cli.js CHANGED
@@ -5,7 +5,7 @@ import './safe-stdio.js';
5
5
  import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync } from 'node:fs';
6
6
  import process from 'node:process';
7
7
  import { basename, join } from 'node:path';
8
- import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
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
9
  import { VERSION } from './version.js';
10
10
  import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
11
11
  import * as lb from './leaderboard.js';
@@ -693,14 +693,14 @@ function showProjects(argv = []) {
693
693
  });
694
694
  if (ranked.length > limit) lines.push(`${c.dim}… ${ranked.length - limit} more — --limit ${ranked.length} to see all${c.reset}`);
695
695
  box('projects', lines, 76);
696
- 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`);
697
697
  }
698
698
 
699
699
  // `project <name>` — one project's full record + its recent daily rhythm
700
700
  // (attributed per-day since scan cache v5).
701
701
  function showProject(rawName) {
702
702
  if (!rawName) {
703
- 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`);
704
704
  process.exitCode = EX_USER_ERROR;
705
705
  return;
706
706
  }
@@ -1238,13 +1238,7 @@ function doReadme(argv) {
1238
1238
  }
1239
1239
 
1240
1240
  console.log('');
1241
- console.log(` ${c.dim}── self-host on a GitHub gist instead (works without a profile) ──${c.reset}`);
1242
- console.log(` ${c.cyan}claude-rpc badge --metric hours --gist${c.reset} ${c.dim}# prints README markdown${c.reset}`);
1243
- console.log('');
1244
- console.log(` ${c.dim}Shareable cards:${c.reset}`);
1245
- console.log(` ${c.cyan}claude-rpc card --range year --out year.svg${c.reset} ${c.dim}# poster${c.reset}`);
1246
- console.log(` ${c.cyan}claude-rpc calendar --gist${c.reset} ${c.dim}# live year heatmap${c.reset}`);
1247
- 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}`);
1248
1242
  console.log('');
1249
1243
  }
1250
1244
 
@@ -1335,7 +1329,7 @@ async function doPrivacy() {
1335
1329
  for (const p of list) console.log(` ${p === cwd ? c.cyan + '●' + c.reset : ' '} ${p}`);
1336
1330
  }
1337
1331
  console.log('');
1338
- 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}`);
1339
1333
  console.log(` ${c.dim}per-proj: drop a {"private": true} into .claude-rpc.json at the repo root${c.reset}`);
1340
1334
  console.log('');
1341
1335
  }
@@ -1369,7 +1363,7 @@ async function doPause(argv) {
1369
1363
  }
1370
1364
  const until = setPause(ms);
1371
1365
  console.log(` ${c.green}✓${c.reset} presence paused until ${c.cyan}${fmtClock(until)}${c.reset}`);
1372
- 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}`);
1373
1367
  }
1374
1368
 
1375
1369
  async function doResume() {
@@ -2196,6 +2190,47 @@ async function doCommunity(argv) {
2196
2190
  });
2197
2191
  }
2198
2192
 
2193
+ async function doUpdate(argv) {
2194
+ const sub = (argv[0] || 'check').toLowerCase();
2195
+ const { installKind, updateCommand, fetchLatest, isNewer, sameMajor, installVersion, readUpdateState, writeUpdateState } = await import('./updater.js');
2196
+ const kind = installKind();
2197
+ const userCfg = readJson(CONFIG_PATH, {});
2198
+ const auto = loadConfig().update?.auto !== false;
2199
+ if (sub === 'on' || sub === 'off') {
2200
+ userCfg.update = { ...userCfg.update, auto: sub === 'on' };
2201
+ writeUserConfig(userCfg);
2202
+ console.log(` ${c.green}✓${c.reset} auto-update ${sub === 'on' ? 'on' : 'off'}`);
2203
+ return;
2204
+ }
2205
+ if (sub === 'status') {
2206
+ const st = readUpdateState();
2207
+ console.log(` ${c.cyan}·${c.reset} v${VERSION} · installed via ${kind} · auto-update ${auto && kind === 'npm-global' ? 'on' : kind === 'npm-global' ? 'off' : 'n/a'}`);
2208
+ if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${c.reset}`);
2209
+ return;
2210
+ }
2211
+ if (sub !== 'check' && sub !== 'now') {
2212
+ fail(`unknown update subcommand: ${sub}`, { hint: 'try: update [check|now|on|off|status]', code: EX_USER_ERROR });
2213
+ }
2214
+ const latest = await fetchLatest();
2215
+ if (!latest) fail('could not reach the npm registry', { hint: 'check your connection and try again', code: EX_BAD_STATE });
2216
+ if (!isNewer(latest, VERSION)) {
2217
+ console.log(` ${c.green}✓${c.reset} up to date ${c.dim}(v${VERSION})${c.reset}`);
2218
+ return;
2219
+ }
2220
+ console.log(` ${c.yellow}!${c.reset} v${latest} is available ${c.dim}(you have v${VERSION})${c.reset}`);
2221
+ if (kind !== 'npm-global' || sub === 'check') {
2222
+ console.log(` ${c.gray}↳ ${c.reset}${c.cyan}${kind === 'npm-global' ? 'claude-rpc update now' : updateCommand(kind)}${c.reset}`);
2223
+ return;
2224
+ }
2225
+ if (!sameMajor(latest, VERSION)) console.log(` ${c.dim}new major version — check the changelog first${c.reset}`);
2226
+ console.log(` ${c.dim}installing…${c.reset}`);
2227
+ const res = await installVersion(latest);
2228
+ if (!res.ok) fail('install failed', { hint: [res.output.slice(-300) || 'npm exited non-zero', `try: ${updateCommand(kind)}`], code: EX_BAD_STATE });
2229
+ writeUpdateState({ updatedFrom: VERSION, updatedTo: latest, updatedAt: Date.now(), failed: null });
2230
+ console.log(` ${c.green}✓${c.reset} updated to v${latest}`);
2231
+ await restartDaemon();
2232
+ }
2233
+
2199
2234
  function tailLog() {
2200
2235
  if (!existsSync(LOG_PATH)) {
2201
2236
  console.log(` ${c.yellow}!${c.reset} no log yet ${c.dim}${LOG_PATH}${c.reset}`);
@@ -2292,81 +2327,103 @@ function overview() {
2292
2327
  console.log('');
2293
2328
  }
2294
2329
 
2295
- function help() {
2296
- const cmds = [
2297
- ['setup', 'Install Claude Code hooks + login autostart (Run key / LaunchAgent / systemd --user)'],
2298
- ['install', 'Same as setup'],
2299
- ['setup --link <code>', 'One-liner onboarding: install + verify via a claude-rpc.com code (+ --wrapped publishes your year)'],
2300
- ['uninstall', 'Remove Claude Code hooks + the login autostart entry'],
2301
- ['upgrade-config', 'Re-run idempotent migrations on an existing config.json'],
2302
- ['start', 'Start the Discord RPC daemon (detached)'],
2303
- ['stop', 'Stop the daemon'],
2304
- ['restart', 'Stop then start the daemon'],
2305
- ['status', 'Interactive stats TUI; --dump (or piped) prints static text'],
2306
- ['dump', 'Same as status --dump'],
2307
- ['today', 'Focus view: today\'s stats + 24h activity histogram'],
2308
- ['week', 'Focus view: this week, daily breakdown'],
2309
- ['compare', 'This week vs last week — the full side-by-side diff'],
2310
- ['projects', 'Every project ranked by active time (--limit N)'],
2311
- ['project', 'One project\'s full record + recent daily rhythm'],
2312
- ['usage', 'Subscription limits — session + weekly % (what /usage shows)'],
2313
- ['serve', 'Open a live web dashboard in your browser'],
2314
- ['preview', 'Show how each rotation frame renders right now'],
2315
- ['vars', 'Print every template variable and its live value (JSON)'],
2316
- ['scan', 'Incrementally scan ~/.claude/projects for all-time totals'],
2317
- ['rescan', 'Force re-parse every transcript (ignores cache)'],
2318
- ['backfill', 'Import transcripts from any folder (e.g. a backup)'],
2319
- ['insights', 'Auto-generated insights from your history'],
2320
- ['recap', 'Standup summary (yesterday by default; today|week|date, --md for markdown)'],
2321
- ['badge', 'Render a Shields-style SVG (--metric --range --out --gist)'],
2322
- ['card', 'Render a poster-style SVG summary (--range year|month|week|all)'],
2323
- ['github-stat', 'Render an embeddable profile stat card (--handle --out --gist)'],
2324
- ['statusline', 'One-line status for tmux/shell prompts (--template)'],
2325
- ['calendar', 'Year activity heatmap SVG (--metric hours|tokens --card --out --gist)'],
2326
- ['session-card', 'Recap card for the current session (--out)'],
2327
- ['readme', 'Paste-ready README card + badges for your profile (--raw to pipe)'],
2328
- ['mcp install', 'Wire the stats MCP server into Claude Code (one command)'],
2329
- ['mcp uninstall', 'Remove the stats MCP server from Claude Code'],
2330
- ['mcp', 'Run the MCP server (stdio) — exposes your stats to Claude'],
2331
- ['wrapped', 'Open your animated year-in-review (Claude Wrapped)'],
2332
- ['wrapped --publish', 'Put your Wrapped on the web at claude-rpc.com/wrapped/<handle>'],
2333
- ['pause', 'Snooze the Discord card globally (pause [30m|2h], default 1h)'],
2334
- ['pause status|off', 'Show whether presence is paused / lift a pause early'],
2335
- ['resume', 'Lift a pause early'],
2336
- ['unpause', 'Same as resume'],
2337
- ['export', 'Dump the aggregate as JSON, or daily rows as CSV (--csv --out)'],
2338
- ['private', 'Mark the current directory as private (hide from Discord)'],
2339
- ['public', 'Un-mark the current directory'],
2340
- ['privacy', 'Show resolved visibility for the current directory'],
2341
- ['community', 'Opt in/out of anonymous community totals (on|off|status|report)'],
2342
- ['profile', 'Public leaderboard identity (status|set|on|off|publish|verify)'],
2343
- ['squad', 'Private mini-leaderboards with friends (create|join|leave|status)'],
2344
- ['link', 'Link machines into one profile (mints a code; `link <code>` claims it)'],
2345
- ['doctor', 'Run a diagnostic checklist — common-failure triage (--fix to auto-repair)'],
2346
- ['tail', 'Tail the daemon log file'],
2347
- ['logs', 'Same as tail (also: log)'],
2348
- ['daemon', 'Run daemon in foreground (debug)'],
2349
- ];
2350
- const colW = cmds.reduce((m, [name]) => Math.max(m, name.length), 0);
2351
- console.log('');
2352
- console.log(` ${c.bold}${c.magenta}◆ claude-rpc${c.reset} ${c.dim}— Discord Rich Presence for Claude Code${c.reset}`);
2353
- console.log('');
2354
- console.log(` ${c.dim}Commands:${c.reset}`);
2355
- for (const [name, desc] of cmds) {
2356
- console.log(` ${c.cyan}${name.padEnd(colW)}${c.reset} ${desc}`);
2330
+ async function help(name) {
2331
+ const { renderHelp, renderCommandHelp } = await import('./help.js');
2332
+ if (!name) { console.log(renderHelp()); return; }
2333
+ const page = renderCommandHelp(name);
2334
+ if (page) { console.log(page); return; }
2335
+ const { suggestCommand } = await import('./commands.js');
2336
+ const guess = suggestCommand(name);
2337
+ fail(`no command called \`${name}\``, {
2338
+ hint: guess ? `did you mean \`claude-rpc help ${guess}\`?` : 'claude-rpc help lists them all',
2339
+ code: EX_USER_ERROR,
2340
+ });
2341
+ }
2342
+
2343
+ // `__complete <words…>` — candidates for the shell scripts in completion.js,
2344
+ // one per line. Never prints errors: a broken <Tab> must stay silent.
2345
+ async function doComplete(words) {
2346
+ const { complete } = await import('./commands.js');
2347
+ if (process.env.CLAUDE_RPC_COMP_CUR !== undefined) words = [...words, process.env.CLAUDE_RPC_COMP_CUR];
2348
+ const projects = () => {
2349
+ try { return Object.keys(JSON.parse(readFileSync(AGGREGATE_PATH, 'utf8')).projects || {}); } catch { return []; }
2350
+ };
2351
+ try {
2352
+ const out = complete(words, { projects });
2353
+ if (out.length) process.stdout.write(out.join('\n') + '\n');
2354
+ } catch { /* stay silent */ }
2355
+ }
2356
+
2357
+ // `completion [install|uninstall|<shell>]`
2358
+ async function doCompletion(argv) {
2359
+ const comp = await import('./completion.js');
2360
+ const { SHELLS } = await import('./commands.js');
2361
+ const sub = argv[0] || '';
2362
+ if (SHELLS.includes(sub)) { process.stdout.write(comp.scriptFor(sub)); return; }
2363
+ const shell = (sub === 'install' && argv[1]) || comp.detectShell();
2364
+ if (sub === 'install' && !SHELLS.includes(shell)) {
2365
+ return fail(`unknown shell: ${shell}`, { hint: `one of: ${SHELLS.join(', ')}`, code: EX_USER_ERROR });
2366
+ }
2367
+ const opts = { configDir: USER_CONFIG_DIR, profilePath: shell === 'powershell' ? await comp.powershellProfile() : undefined };
2368
+ if (sub === 'install') {
2369
+ let r;
2370
+ try { r = comp.install(shell, opts); } catch (e) { return fail(e.message, { code: EX_SYS_ERROR }); }
2371
+ if (!r.changed) { console.log(` ${c.green}✓${c.reset} tab completion already on for ${c.bold}${shell}${c.reset}`); return; }
2372
+ console.log(` ${c.green}✓${c.reset} tab completion on for ${c.bold}${shell}${c.reset} ${c.dim}${shortPath(r.rc || r.script)}${c.reset}`);
2373
+ const reload = shell === 'fish' ? 'works in new fish sessions'
2374
+ : shell === 'powershell' ? 'open a new PowerShell window'
2375
+ : `open a new terminal, or: ${c.reset}${c.cyan}source ${shortPath(r.rc)}${c.reset}${c.dim}`;
2376
+ console.log(` ${c.dim}${reload} — then try ${c.reset}${c.cyan}claude-rpc st<Tab>${c.reset}`);
2377
+ return;
2357
2378
  }
2379
+ if (sub === 'uninstall') {
2380
+ const touched = comp.uninstall(opts);
2381
+ console.log(touched.length
2382
+ ? ` ${c.green}✓${c.reset} tab completion removed ${c.dim}${touched.map(shortPath).join(', ')}${c.reset}`
2383
+ : ` ${c.cyan}·${c.reset} tab completion wasn't installed`);
2384
+ return;
2385
+ }
2386
+ if (sub) return fail(`unknown option: ${sub}`, { hint: 'claude-rpc completion [install|uninstall|bash|zsh|fish|powershell]', code: EX_USER_ERROR });
2387
+ const on = comp.isInstalled(shell, opts);
2358
2388
  console.log('');
2359
- console.log(` ${c.dim}First-time setup:${c.reset}`);
2360
- console.log(` 1. ${c.cyan}claude-rpc setup${c.reset} — wires hooks, seeds config, starts the daemon.`);
2361
- console.log(` 2. Open Claude Code and send a prompt — the card appears in Discord.`);
2362
- 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}.`);
2363
- console.log('');
2364
- 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.`);
2389
+ 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}`}`);
2365
2390
  console.log('');
2366
- console.log(` ${c.dim}Exit codes:${c.reset} ${c.dim}0 ok · 1 user error · 2 system error · 3 wrong state${c.reset}`);
2391
+ if (!on) console.log(` ${c.cyan}claude-rpc completion install${c.reset} ${c.dim}turn it on for ${shell}${c.reset}`);
2392
+ else console.log(` ${c.cyan}claude-rpc completion uninstall${c.reset} ${c.dim}turn it off${c.reset}`);
2393
+ console.log(` ${c.cyan}claude-rpc completion <shell>${c.reset} ${c.dim}print the script (${SHELLS.join(', ')})${c.reset}`);
2367
2394
  console.log('');
2368
2395
  }
2369
2396
 
2397
+ // Offer tab completion once during a first setup, on a terminal only.
2398
+ async function setupCompletionOffer() {
2399
+ if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CLAUDE_RPC_NO_COMPLETION) return;
2400
+ const comp = await import('./completion.js');
2401
+ const shell = comp.detectShell();
2402
+ const profilePath = shell === 'powershell' ? await comp.powershellProfile() : undefined;
2403
+ const opts = { configDir: USER_CONFIG_DIR, profilePath };
2404
+ if (shell === 'powershell' && !profilePath) return;
2405
+ if (comp.isInstalled(shell, opts)) return;
2406
+ const answer = (await prompt(` tab completion for ${shell}? ${c.dim}[Y/n]${c.reset} `)).trim().toLowerCase();
2407
+ if (answer && answer !== 'y' && answer !== 'yes') return;
2408
+ try {
2409
+ const r = comp.install(shell, opts);
2410
+ console.log(` ${c.green}✓${c.reset} ${'tab completion'.padEnd(16)}${c.dim}${shell} · ${shortPath(r.rc || r.script)} (new terminals)${c.reset}`);
2411
+ } catch (e) {
2412
+ console.log(` ${c.yellow}!${c.reset} ${'tab completion'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
2413
+ }
2414
+ }
2415
+
2416
+ async function doStatcards(argv) {
2417
+ const { runStatcards } = await import('./statcards.js');
2418
+ await runStatcards(argv, {
2419
+ config: loadConfig(),
2420
+ aggregate: () => aggregateOr('render'),
2421
+ liveVars: () => liveVars().vars,
2422
+ prompt,
2423
+ enableProfile: () => profileEnable(true),
2424
+ });
2425
+ }
2426
+
2370
2427
  // Packaged exe: `claude-rpc.exe` with no args → first-run install + start.
2371
2428
  // `claude-rpc.exe hook PreToolUse` → handle hook.
2372
2429
  // Dev mode keeps the original `help` fallback so behavior is unchanged.
@@ -2395,7 +2452,12 @@ process.on('unhandledRejection', (e) => {
2395
2452
  // Fast-exit commands touch none of the core graph (they import their own
2396
2453
  // module, if any); daemon control needs only ensure-daemon. Everything else
2397
2454
  // loads the core once up front, so its bindings are set for every handler.
2398
- const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', 'hook', 'mcp', 'daemon', 'serve', 'wrapped', 'scan-worker', 'tail', 'logs', 'log', 'pause', 'resume', 'unpause']);
2455
+ 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']);
2456
+ // `<command> --help` → that command's page (before it runs at all).
2457
+ if (cmd && (args.includes('--help') || args.includes('-h')) && !['hook', 'scan-worker', '__complete'].includes(cmd)) {
2458
+ const { findCommand } = await import('./commands.js');
2459
+ if (findCommand(cmd)) { await help(cmd); return; }
2460
+ }
2399
2461
  if (['start', 'stop', 'restart'].includes(cmd)) await loadDaemonCtl();
2400
2462
  else if (!FAST_PATHS.has(cmd)) await loadCore();
2401
2463
  switch (cmd) {
@@ -2404,7 +2466,10 @@ process.on('unhandledRejection', (e) => {
2404
2466
  case '-v': console.log(`claude-rpc ${VERSION}`); break;
2405
2467
  case '--help':
2406
2468
  case '-h':
2407
- case 'help': help(); break;
2469
+ case 'help': await help(cmd === 'help' ? args[0] : undefined); break;
2470
+ case '__complete': await doComplete(args); break;
2471
+ case 'completion': await doCompletion(args); break;
2472
+ case 'statcards': await doStatcards(args); break;
2408
2473
  // `setup` and `install` are aliases as of v0.7: both register hooks AND
2409
2474
  // the login autostart entry (Windows Run key, macOS LaunchAgent, Linux
2410
2475
  // systemd --user unit). Older behavior split them (setup = no startup,
@@ -2489,11 +2554,17 @@ process.on('unhandledRejection', (e) => {
2489
2554
  // Optional GitHub connect — one explicit y/N, asked at most once ever.
2490
2555
  // The --link path above IS a connect, so it never double-asks.
2491
2556
  if (!linkCode) await setupGhConnect();
2557
+ if (changed) await setupCompletionOffer();
2492
2558
  }
2493
2559
  setupOutro(target, changed, cli);
2494
2560
  break;
2495
2561
  }
2496
- case 'uninstall': await (await import('./install.js')).uninstall(); break;
2562
+ case 'uninstall': {
2563
+ const { uninstall: completionOff } = await import('./completion.js');
2564
+ try { completionOff({ configDir: USER_CONFIG_DIR, profilePath: process.platform === 'win32' ? await (await import('./completion.js')).powershellProfile() : undefined }); } catch { /* best-effort */ }
2565
+ await (await import('./install.js')).uninstall();
2566
+ break;
2567
+ }
2497
2568
  case 'upgrade-config':
2498
2569
  if (!(await import('./install.js')).migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2499
2570
  break;
@@ -2508,15 +2579,20 @@ process.on('unhandledRejection', (e) => {
2508
2579
  }
2509
2580
  case 'dump': await showStatus(); break;
2510
2581
  case 'today': await showToday(); break;
2511
- case 'week': await showWeek(); break;
2512
- case 'projects': showProjects(args); break;
2582
+ case 'week': if (args.includes('--compare')) showCompare(); else await showWeek(); break;
2583
+ case 'projects': {
2584
+ // `projects <name>` drills into one project (was `project <name>`).
2585
+ const name = args.find((a, i) => !a.startsWith('-') && args[i - 1] !== '--limit');
2586
+ if (name) showProject(name); else showProjects(args);
2587
+ break;
2588
+ }
2513
2589
  case 'project': showProject(args[0]); break;
2514
2590
  case 'compare': showCompare(); break;
2515
2591
  case 'usage': await showUsage(); break;
2516
2592
  case 'serve': await import('./server/index.js'); break;
2517
2593
  case 'preview': showPreview(); break;
2518
2594
  case 'vars': dumpVars(); break;
2519
- case 'scan': doScan(false); break;
2595
+ case 'scan': doScan(args.includes('--force') || args.includes('-f')); break;
2520
2596
  case 'rescan': doScan(true); break;
2521
2597
  case 'backfill': doBackfill(args); break;
2522
2598
  case 'insights': await showInsights(); break;
@@ -2542,10 +2618,18 @@ process.on('unhandledRejection', (e) => {
2542
2618
  case 'resume':
2543
2619
  case 'unpause': await doResume(); break;
2544
2620
  case 'export': await doExport(args); break;
2545
- case 'private': await doPrivate(); break;
2621
+ case 'private': {
2622
+ const sub = args[0] || 'on';
2623
+ if (sub === 'on') await doPrivate();
2624
+ else if (sub === 'off') await doPublic();
2625
+ else if (sub === 'status') await doPrivacy();
2626
+ else fail(`unknown option: ${sub}`, { hint: 'claude-rpc private [on|off|status]', code: EX_USER_ERROR });
2627
+ break;
2628
+ }
2546
2629
  case 'public': await doPublic(); break;
2547
2630
  case 'privacy': await doPrivacy(); break;
2548
2631
  case 'community': await doCommunity(args); break;
2632
+ case 'update': await doUpdate(args); break;
2549
2633
  case 'profile': await doProfile(args); break;
2550
2634
  case 'squad': await doSquadCmd(args); break;
2551
2635
  case 'link': await doLink(args); break;
@@ -2652,9 +2736,11 @@ process.on('unhandledRejection', (e) => {
2652
2736
  : IS_NPX ? `npx claude-rpc@latest ${cmd}`
2653
2737
  : /[\\/]Cellar[\\/]/.test(DAEMON_SCRIPT) ? 'brew upgrade claude-rpc'
2654
2738
  : 'npm install -g claude-rpc@latest';
2739
+ const { suggestCommand } = await import('./commands.js');
2740
+ const guess = suggestCommand(cmd);
2655
2741
  fail(`unknown command: ${cmd}`, {
2656
- hint: [
2657
- 'run `claude-rpc --help` for the full command list',
2742
+ hint: guess ? `did you mean \`claude-rpc ${guess}\`?` : [
2743
+ 'run `claude-rpc help` for the full command list',
2658
2744
  `this install is v${VERSION} — if the docs mention \`${cmd}\`, update first: ${update}`,
2659
2745
  ],
2660
2746
  code: EX_USER_ERROR,
@@ -0,0 +1,248 @@
1
+ // The one table of CLI commands. `help`, `help <command>`, tab completion
2
+ // (`__complete`) and the "did you mean" hint all read it, so a command, flag
3
+ // or sub-command added here shows up in all four at once. Dispatch itself
4
+ // stays in cli.js's switch; test/commands.test.js fails when the two drift.
5
+ //
6
+ // Shape of an entry:
7
+ // name what you type
8
+ // group help section (GROUPS order); omitted → hidden from help + completion
9
+ // summary one line for the list
10
+ // usage argument synopsis after the name ('' when none)
11
+ // subs [name, summary] positional choices for the first argument
12
+ // flags [flag, summary, values?] — values: an array, 'file', 'project' or
13
+ // 'any' (takes a free-form value); no values → boolean switch
14
+ // aliases older names that still work (stable per VERSIONING.md), not listed
15
+ // examples shown by `help <command>`
16
+ //
17
+ // Pure data + pure helpers: no fs, no imports from the core graph — the
18
+ // completion path loads this on every <Tab>.
19
+
20
+ export const GROUPS = [
21
+ ['start', 'Get started'],
22
+ ['stats', 'Your stats'],
23
+ ['share', 'Share'],
24
+ ['privacy', 'Privacy'],
25
+ ['online', 'Online'],
26
+ ['daemon', 'Daemon'],
27
+ ['fix', 'Troubleshoot'],
28
+ ];
29
+
30
+ const METRICS = ['hours', 'tokens', 'streak', 'sessions'];
31
+ const RANGES = ['week', 'month', 'year', 'all'];
32
+ export const SHELLS = ['bash', 'zsh', 'fish', 'powershell'];
33
+
34
+ export const COMMANDS = [
35
+ // ── Get started ──
36
+ { name: 'setup', group: 'start', summary: 'Hook into Claude Code and start the card — run once',
37
+ flags: [['--link', 'Also verify this machine with a claude-rpc.com code', 'any'],
38
+ ['--wrapped', 'With --link: publish your year-in-review too']],
39
+ aliases: ['install'],
40
+ examples: ['claude-rpc setup', 'claude-rpc setup --link ABCD-1234 --wrapped'] },
41
+ { name: 'completion', group: 'start', summary: 'Tab completion for your shell', usage: '[install|uninstall|<shell>]',
42
+ subs: [['install', 'Turn it on for your shell (asks nothing else)'], ['uninstall', 'Turn it off'],
43
+ ...SHELLS.map((s) => [s, `Print the ${s} script`])],
44
+ examples: ['claude-rpc completion install', 'claude-rpc completion zsh > ~/.zfunc/_claude-rpc'] },
45
+ { name: 'uninstall', group: 'start', summary: 'Undo setup (keeps your config and stats)' },
46
+
47
+ // ── Your stats ──
48
+ { name: 'status', group: 'stats', summary: 'Live stats dashboard in the terminal',
49
+ flags: [['--dump', 'Print once as plain text (also when piped)']], aliases: ['dump'] },
50
+ { name: 'today', group: 'stats', summary: 'Today, plus when in the day you code' },
51
+ { name: 'week', group: 'stats', summary: 'This week day by day',
52
+ flags: [['--compare', 'Side by side with last week']], aliases: ['compare'],
53
+ examples: ['claude-rpc week', 'claude-rpc week --compare'] },
54
+ { name: 'projects', group: 'stats', summary: 'Projects ranked by time — or one project in detail', usage: '[name]',
55
+ args: 'project', flags: [['--limit', 'How many to list (default 12)', 'any']], aliases: ['project'],
56
+ examples: ['claude-rpc projects', 'claude-rpc projects claude-rpc'] },
57
+ { name: 'usage', group: 'stats', summary: 'Plan limits: session and weekly % used' },
58
+ { name: 'recap', group: 'stats', summary: 'Standup summary (yesterday by default)', usage: '[today|yesterday|week|YYYY-MM-DD]',
59
+ subs: [['yesterday', 'Default — Monday covers Friday'], ['today', 'So far today'], ['week', 'This week']],
60
+ flags: [['--md', 'Paste-ready markdown'], ['--json', 'Raw numbers']],
61
+ examples: ['claude-rpc recap', 'claude-rpc recap week --md'] },
62
+ { name: 'insights', group: 'stats', summary: 'Patterns spotted in your history' },
63
+ { name: 'wrapped', group: 'stats', summary: 'Your animated year in review',
64
+ flags: [['--publish', 'Put it on claude-rpc.com/wrapped/<handle>'], ['--year', 'Which year', 'any'], ['--yes', 'Skip the confirm']] },
65
+ { name: 'serve', group: 'stats', summary: 'Open the live web dashboard' },
66
+ { name: 'export', group: 'stats', summary: 'Everything as JSON, or daily rows as CSV',
67
+ flags: [['--csv', 'Daily rows as CSV'], ['--out', 'Write to a file', 'file']] },
68
+
69
+ // ── Share ──
70
+ { name: 'statcards', group: 'share', summary: 'Cards and badges as a live link, PNG or SVG', usage: '[card]',
71
+ subs: [['stats', 'Stats + year heatmap'], ['profile', 'Profile card'], ['badge', 'Small badge'],
72
+ ['heatmap', 'Year heatmap'], ['poster', 'Poster summary'], ['session', 'This session'],
73
+ ['wrapped', 'Year-in-review card'], ['list', 'What each card is and where it can go']],
74
+ flags: [['--link', 'Live, self-updating URL (needs a public profile)'], ['--png', 'Save a PNG (optional path)', 'file'],
75
+ ['--svg', 'Save an SVG (optional path)', 'file'], ['--md', 'With --link: print Markdown'],
76
+ ['--html', 'With --link: print an <img> tag'], ['--metric', 'What a badge/heatmap counts', METRICS],
77
+ ['--range', 'Window for badge/poster', RANGES], ['--copy', 'Copy the snippet to the clipboard']],
78
+ aliases: ['badge', 'card', 'github-stat', 'calendar', 'session-card', 'readme'],
79
+ examples: ['claude-rpc statcards', 'claude-rpc statcards stats --link --md', 'claude-rpc statcards poster --png', 'claude-rpc statcards badge --metric streak --svg streak.svg'] },
80
+ { name: 'statusline', group: 'share', summary: 'One-line status for tmux and shell prompts',
81
+ flags: [['--template', 'Template using any `claude-rpc vars` name', 'any']] },
82
+ { name: 'mcp', group: 'share', summary: 'Let Claude read your stats (MCP server)', usage: '[install|uninstall]',
83
+ subs: [['install', 'Wire it into Claude Code'], ['uninstall', 'Remove it']] },
84
+
85
+ // ── Privacy ──
86
+ { name: 'private', group: 'privacy', summary: 'Hide this folder from Discord — or show it again', usage: '[on|off|status]',
87
+ subs: [['on', 'Hide this folder (default)'], ['off', 'Show it again'], ['status', 'What Discord sees for this folder']],
88
+ aliases: ['public', 'privacy'],
89
+ examples: ['claude-rpc private', 'claude-rpc private off', 'claude-rpc private status'] },
90
+ { name: 'pause', group: 'privacy', summary: 'Hide the card everywhere for a while (default 1h)', usage: '[30m|2h|off|status]',
91
+ subs: [['30m', '30 minutes'], ['1h', 'An hour'], ['2h', 'Two hours'], ['off', 'Show the card again'], ['status', 'Paused?']],
92
+ aliases: ['resume', 'unpause'],
93
+ examples: ['claude-rpc pause 2h', 'claude-rpc pause off'] },
94
+
95
+ // ── Online ──
96
+ { name: 'profile', group: 'online', summary: 'Your public leaderboard profile', usage: '[status|set|on|off|publish|verify]',
97
+ subs: [['status', 'Show it'], ['set', 'Change handle / name / github'], ['on', 'Go public'], ['off', 'Go private'],
98
+ ['publish', 'Push your numbers now'], ['verify', 'Prove the GitHub account is yours']],
99
+ flags: [['--handle', 'With set: your handle', 'any'], ['--name', 'With set: display name', 'any'], ['--github', 'With set: GitHub login', 'any']] },
100
+ { name: 'squad', group: 'online', summary: 'Private leaderboards with friends', usage: '[status|create|join|leave]',
101
+ subs: [['status', 'Your squads'], ['create', 'Start one'], ['join', 'Join with a code'], ['leave', 'Leave one']] },
102
+ { name: 'link', group: 'online', summary: 'Join machines into one profile', usage: '[code]' },
103
+ { name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
104
+ subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
105
+
106
+ { name: 'update', group: 'daemon', summary: 'Check for a new version (and auto-update)', usage: '[check|now|on|off|status]',
107
+ subs: [['check', 'Look for a newer release'], ['now', 'Install it now'], ['on', 'Auto-update (default)'], ['off', 'Never update unattended'], ['status', 'Show settings']] },
108
+
109
+ // ── Daemon ──
110
+ { name: 'start', group: 'daemon', summary: 'Start the Discord daemon' },
111
+ { name: 'stop', group: 'daemon', summary: 'Stop it' },
112
+ { name: 'restart', group: 'daemon', summary: 'Restart it and wait until it is up' },
113
+ { name: 'logs', group: 'daemon', summary: 'Follow the daemon log', aliases: ['tail', 'log'] },
114
+
115
+ // ── Troubleshoot ──
116
+ { name: 'doctor', group: 'fix', summary: 'Check everything; --fix repairs what it can',
117
+ flags: [['--fix', 'Apply the repairs']] },
118
+ { name: 'scan', group: 'fix', summary: 'Re-count your history from transcripts',
119
+ flags: [['--force', 'Re-parse everything, ignore the cache']], aliases: ['rescan'] },
120
+ { name: 'backfill', group: 'fix', summary: 'Import transcripts from a backup or another machine', usage: '<dir>', args: 'file' },
121
+ { name: 'preview', group: 'fix', summary: 'How every card frame renders right now' },
122
+ { name: 'vars', group: 'fix', summary: 'Every template variable and its live value (JSON)' },
123
+ { name: 'upgrade-config', summary: 'Re-run config migrations' },
124
+ { name: 'daemon', summary: 'Run the daemon in the foreground (debug)' },
125
+ { name: 'help', summary: 'This screen, or one command in detail', usage: '[command]', args: 'command' },
126
+ ];
127
+
128
+ // Internal entry points the dispatcher knows but nobody types.
129
+ export const INTERNAL = ['hook', 'scan-worker', '__complete', '--version', '-V', '-v', '--help', '-h'];
130
+
131
+ const BY_NAME = new Map();
132
+ for (const cmd of COMMANDS) {
133
+ BY_NAME.set(cmd.name, cmd);
134
+ for (const a of cmd.aliases || []) BY_NAME.set(a, cmd);
135
+ }
136
+
137
+ // The command entry for a name or any alias, or null.
138
+ export function findCommand(name) {
139
+ return BY_NAME.get(name) || null;
140
+ }
141
+
142
+ // Every name the dispatcher must accept: commands, aliases, internals.
143
+ export function allNames() {
144
+ return [...BY_NAME.keys(), ...INTERNAL];
145
+ }
146
+
147
+ export function visibleCommands() {
148
+ return COMMANDS.filter((c) => c.group);
149
+ }
150
+
151
+ // Damerau-free Levenshtein, small strings only.
152
+ function distance(a, b) {
153
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
154
+ for (let i = 1; i <= a.length; i++) {
155
+ let prev = row[0];
156
+ row[0] = i;
157
+ for (let j = 1; j <= b.length; j++) {
158
+ const tmp = row[j];
159
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
160
+ prev = tmp;
161
+ }
162
+ }
163
+ return row[b.length];
164
+ }
165
+
166
+ // What each older name now spells, for `help <old>` and typo hints.
167
+ export const ALIAS_HINT = {
168
+ install: 'setup', dump: 'status --dump', compare: 'week --compare', project: 'projects <name>',
169
+ rescan: 'scan --force', resume: 'pause off', unpause: 'pause off', public: 'private off',
170
+ privacy: 'private status', tail: 'logs', log: 'logs', badge: 'statcards badge', card: 'statcards poster',
171
+ 'github-stat': 'statcards profile', calendar: 'statcards heatmap', 'session-card': 'statcards session',
172
+ readme: 'statcards stats --link',
173
+ };
174
+
175
+ // "did you mean" for an unknown command: a unique prefix match first
176
+ // (`stat` is ambiguous, `statc` → statcards), else the closest name within 2
177
+ // edits. Older names count too, so muscle memory still gets a hint — the hint
178
+ // is the name that matched, which still works.
179
+ export function suggestCommand(input) {
180
+ const s = String(input || '').toLowerCase();
181
+ if (!s) return null;
182
+ const names = [...BY_NAME.keys()];
183
+ const prefixed = names.filter((n) => n.startsWith(s));
184
+ if (prefixed.length && new Set(prefixed.map((n) => BY_NAME.get(n).name)).size === 1) {
185
+ return prefixed.sort((a, b) => a.length - b.length)[0];
186
+ }
187
+ let best = null;
188
+ let bestD = 3;
189
+ for (const n of names) {
190
+ const d = distance(s, n);
191
+ if (d < bestD) { bestD = d; best = n; }
192
+ }
193
+ return best;
194
+ }
195
+
196
+ // ── completion ───────────────────────────────────────────────────────────
197
+ //
198
+ // complete(words, ctx) → candidate lines, each "value" or "value\tdescription".
199
+ // `words` are the args after `claude-rpc`, the last one being the word under
200
+ // the cursor (possibly ''). A lone '__files__' line asks the shell to fall back
201
+ // to file-name completion. ctx.projects() lazily supplies project names.
202
+
203
+ export const FILES = '__files__';
204
+
205
+ function matching(pairs, cur) {
206
+ return pairs.filter(([v]) => v.startsWith(cur)).map(([v, d]) => (d ? `${v}\t${d}` : v));
207
+ }
208
+
209
+ function valueCandidates(kind, cur, ctx) {
210
+ if (kind === 'file') return [FILES];
211
+ if (kind === 'project') return matching((ctx.projects?.() || []).map((p) => [p, '']), cur);
212
+ if (kind === 'command') return matching(visibleCommands().map((c) => [c.name, c.summary]), cur);
213
+ if (Array.isArray(kind)) return matching(kind.map((v) => [v, '']), cur);
214
+ return [];
215
+ }
216
+
217
+ export function complete(words, ctx = {}) {
218
+ const w = words.length ? words : [''];
219
+ const cur = w[w.length - 1];
220
+ if (w.length === 1) return matching(visibleCommands().map((c) => [c.name, c.summary]), cur);
221
+
222
+ const cmd = findCommand(w[0]);
223
+ if (!cmd) return [];
224
+ const flags = cmd.flags || [];
225
+ const prev = w[w.length - 2];
226
+
227
+ // Value for the flag just typed (`--metric <Tab>`).
228
+ const flag = flags.find(([f]) => f === prev);
229
+ if (flag && flag[2] && !cur.startsWith('-')) return valueCandidates(flag[2], cur, ctx);
230
+
231
+ if (cur.startsWith('-')) {
232
+ const used = new Set(w.slice(1, -1));
233
+ return matching(flags.filter(([f]) => !used.has(f)).map(([f, d]) => [f, d]), cur);
234
+ }
235
+
236
+ // First positional → the command's sub-commands or argument values.
237
+ const positionals = w.slice(1, -1).filter((x, i, arr) => {
238
+ if (x.startsWith('-')) return false;
239
+ const before = i > 0 ? arr[i - 1] : w[0];
240
+ const f = flags.find(([name]) => name === before);
241
+ return !(f && f[2]);
242
+ });
243
+ if (positionals.length === 0) {
244
+ if (cmd.subs) return matching(cmd.subs, cur);
245
+ if (cmd.args) return valueCandidates(cmd.args, cur, ctx);
246
+ }
247
+ return [];
248
+ }