claude-rpc 1.8.0 → 1.10.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/commands.js CHANGED
@@ -102,8 +102,6 @@ export const COMMANDS = [
102
102
  subs: [['status', 'Show it'], ['set', 'Change handle / name / github'], ['on', 'Go public'], ['off', 'Go private'],
103
103
  ['publish', 'Push your numbers now'], ['verify', 'Prove the GitHub account is yours']],
104
104
  flags: [['--handle', 'With set: your handle', 'any'], ['--name', 'With set: display name', 'any'], ['--github', 'With set: GitHub login', 'any']] },
105
- { name: 'squad', group: 'online', summary: 'Private leaderboards with friends', usage: '[status|create|join|leave]',
106
- subs: [['status', 'Your squads'], ['create', 'Start one'], ['join', 'Join with a code'], ['leave', 'Leave one']] },
107
105
  { name: 'link', group: 'online', summary: 'Join machines into one profile', usage: '[code]' },
108
106
  { name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
109
107
  subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
package/src/community.js CHANGED
@@ -15,7 +15,8 @@
15
15
  // 2. Never sends anything beyond the documented payloads. Each build*Payload
16
16
  // function is the complete schema for its endpoint, mirrored by the
17
17
  // worker's validators. The anonymous /report carries only counter
18
- // deltas, version and OS family. The opt-in /profile adds the chosen
18
+ // deltas, version, OS family, install kind, last auto-update outcome
19
+ // and the names of commands used in the last 7 days. The opt-in /profile adds the chosen
19
20
  // identity, lifetime totals and a per-day token/active-time series.
20
21
  // /wrapped (sent only by `wrapped --publish`, after showing the user the
21
22
  // payload) adds that year's stats, including privacy-filtered project
@@ -37,6 +38,8 @@ import { cleanProjectName, dayKey } from './scanner.js';
37
38
  import { HEATMAP_DAYS } from './heatmap.js';
38
39
  import { humanModel } from './format.js';
39
40
  import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
41
+ import { recentFeatures, updateOutcome } from './feature-usage.js';
42
+ import { installKind, readUpdateState } from './updater.js';
40
43
 
41
44
  // How much of this install's lifetime has already been reported. It must
42
45
  // survive reboots: the worker adds every delta blindly, so a lost cursor
@@ -45,6 +48,10 @@ import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
45
48
  // wipes; ensureCursor / markCursorFresh move it here once.
46
49
  export const CURSOR_PATH = join(DATA_DIR, 'community-cursor.json');
47
50
  export const LEGACY_CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
51
+ // Last profile publish result — what `claude-rpc profile` shows, so a machine
52
+ // whose publishes are rejected (unlinked → "handle taken"), or a linked machine
53
+ // that went quiet, is visible instead of a silently low site total.
54
+ export const PROFILE_STATUS_PATH = join(DATA_DIR, 'profile-status.json');
48
55
 
49
56
  export function readCursor(path = CURSOR_PATH) {
50
57
  if (!existsSync(path)) return { sessions: 0, tokens: 0, ts: 0 };
@@ -122,7 +129,7 @@ const MAX_REPORT_TOKENS = 5_000_000_000;
122
129
  // Pure: given an aggregate and a cursor, produce the next payload. The
123
130
  // worker's validateReport must accept this shape; if you add a field
124
131
  // here, add it there too.
125
- export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }) {
132
+ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now(), usage = usageFacts(now) }) {
126
133
  const sessions = aggregate?.sessions || 0;
127
134
  const tokens = totalTokens(aggregate);
128
135
  return {
@@ -131,10 +138,19 @@ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }
131
138
  tokensDelta: Math.min(MAX_REPORT_TOKENS, Math.max(0, tokens - (cursor.tokens || 0))),
132
139
  version: VERSION,
133
140
  osFamily: osFamily(),
141
+ ...usage,
134
142
  ts: now,
135
143
  };
136
144
  }
137
145
 
146
+ // How this copy is installed, how its last auto-update went, and which
147
+ // commands were used in the last 7 days (names only — feature-usage.js).
148
+ export function usageFacts(now = Date.now()) {
149
+ try {
150
+ return { install: installKind(), upd: updateOutcome(readUpdateState()), feat: recentFeatures({ now }) };
151
+ } catch { return {}; }
152
+ }
153
+
138
154
  function totalTokens(aggregate) {
139
155
  return (aggregate?.inputTokens || 0)
140
156
  + (aggregate?.outputTokens || 0)
@@ -368,11 +384,41 @@ export async function flushProfile(cfg, {
368
384
  const payload = buildProfilePayload(aggregate, profile, { instanceId });
369
385
  const { res, fail } = await postJson(fetchImpl, community.endpoint, '/profile', payload);
370
386
  if (fail) return fail;
387
+ let body = null;
388
+ try { body = await res.json(); } catch { /* non-JSON body */ }
371
389
  if (!res.ok) {
372
390
  if (res.status === 429) return { ok: false, reason: 'rate-limited' };
373
- return { ok: false, reason: `http-${res.status}` };
391
+ return { ok: false, reason: `http-${res.status}`, ...(body?.error ? { error: String(body.error).slice(0, 200) } : {}) };
374
392
  }
375
- return { ok: true, totals: { tokens: payload.tokens, sessions: payload.sessions, activeMs: payload.activeMs } };
393
+ return {
394
+ ok: true,
395
+ totals: { tokens: payload.tokens, sessions: payload.sessions, activeMs: payload.activeMs },
396
+ // What the board shows for the whole identity, and per linked machine
397
+ // (no ids — just "this one" and when each last reported). Older workers
398
+ // don't send `machines`.
399
+ site: body?.profile ? {
400
+ tokens: body.profile.tokens || 0,
401
+ machines: Array.isArray(body.machines) ? body.machines.map((m) => ({
402
+ self: !!m.self, tokens: Number(m.tokens) || 0, updatedAt: Number(m.updatedAt) || null,
403
+ })) : null,
404
+ } : null,
405
+ };
406
+ }
407
+
408
+ // Persist a flushProfile result for `claude-rpc profile`. Rate-limited results
409
+ // carry no news and are skipped; a failure keeps the last success alongside it.
410
+ export function recordProfileResult(result, { path = PROFILE_STATUS_PATH, now = Date.now() } = {}) {
411
+ if (!result || result.reason === 'rate-limited' || result.reason === 'disabled') return;
412
+ let prev = {};
413
+ try { prev = JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { /* first write */ }
414
+ const next = result.ok
415
+ ? { ok: true, at: now, totals: result.totals, site: result.site || null }
416
+ : { ...prev, ok: false, failedAt: now, reason: result.reason, error: result.error || null };
417
+ try { writeFileAtomic(path, JSON.stringify(next)); } catch { /* advisory */ }
418
+ }
419
+
420
+ export function readProfileResult(path = PROFILE_STATUS_PATH) {
421
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
376
422
  }
377
423
 
378
424
  // Single best-effort flush. Returns { ok, reason, delta? } — never throws.
package/src/daemon.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import './safe-stdio.js';
3
- import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, renameSync, readdirSync } from 'node:fs';
3
+ import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, renameSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { basename, dirname, join } from 'node:path';
5
5
  import { Client, isBridgeUser } from './discord-ipc.js';
6
6
  import { readState, sweepStaleStateTmp, listSessionStates, sweepStaleSessionStates } from './state.js';
@@ -15,10 +15,10 @@ import { loadConfig } from './config.js';
15
15
  import { selfHealOnUpdate } from './install.js';
16
16
  import { VERSION } from './version.js';
17
17
  import { desktopNotify, postWebhook, shouldWebhook, shouldNotify, sanitizeLabel } from './notify.js';
18
- import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
18
+ import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH, DAEMON_INFO_PATH, ROOT, IS_PACKAGED, CANONICAL_EXE } from './paths.js';
19
19
  import { readUsageCache, pollUsage } from './usage.js';
20
20
  import { pollDecision, pollIntervalMs } from './watch-poll.js';
21
- import { claimSingleInstance, spawnDaemonDetached } from './ensure-daemon.js';
21
+ import { claimSingleInstance, spawnDaemonDetached, isStopped, readPid, isAlive, readDaemonInfo, writeDaemonInfo, BEAT_EVERY_MS, BEAT_STALE_MS } from './ensure-daemon.js';
22
22
  import { checkForUpdate } from './updater.js';
23
23
  import { scanInChild } from './scan-worker.js';
24
24
 
@@ -69,6 +69,42 @@ process.on('unhandledRejection', (e) => {
69
69
  try { log('unhandledRejection (continuing):', e?.stack || e?.message || String(e)); } catch { /* see above */ }
70
70
  });
71
71
 
72
+ // Signal handlers go in before the pid-file claim below: a SIGTERM that lands
73
+ // between the claim and a late handler install killed the daemon the default
74
+ // way and stranded its pid file. (shutdown is hoisted; it tolerates the
75
+ // not-yet-initialised IPC client.)
76
+ process.on('SIGINT', shutdown);
77
+ process.on('SIGTERM', shutdown);
78
+ process.on('SIGHUP', shutdown);
79
+
80
+ // `claude-rpc stop` is durable — it holds across sessions and reboots. A login
81
+ // autostart entry (or anything else) that launches us while stopped exits
82
+ // cleanly (code 0, so systemd's Restart=on-failure leaves it be).
83
+ if (isStopped()) {
84
+ log('Stopped by `claude-rpc stop` — not starting. Run `claude-rpc start` to resume.');
85
+ process.exit(0);
86
+ }
87
+
88
+ // Single-instance guard — an ATOMIC claim (see ensure-daemon.claimSingleInstance).
89
+ // Many launchers can fire at once now that the SessionStart hook self-heals the
90
+ // daemon: a manual `start`, a Windows Run entry, and several concurrent sessions'
91
+ // hooks could all spawn a daemon in the same instant. A second daemon would
92
+ // fight over setActivity every ~4s and double-count the additive community
93
+ // total. The exclusive-create claim makes exactly one survive; a live owner →
94
+ // we exit; a stale pid (dead, or recycled with a stale heartbeat) → we reclaim.
95
+ // Claimed BEFORE the update self-heal below so a losing duplicate never
96
+ // re-wires hooks or touches the login autostart.
97
+ const ownerPid = claimSingleInstance();
98
+ if (ownerPid) {
99
+ log(`Another daemon (pid ${ownerPid}) is already running — exiting.`);
100
+ process.exit(0);
101
+ }
102
+ const STARTED_AT = Date.now();
103
+ function beat() {
104
+ writeDaemonInfo({ pid: process.pid, version: VERSION, startedAt: STARTED_AT, beatAt: Date.now() });
105
+ }
106
+ beat();
107
+
72
108
  // Wrap loadConfig so a parse/IO failure logs once and the daemon keeps
73
109
  // running on baked-in defaults. The Electron settings GUI saves the file
74
110
  // atomically but mid-edit hand-edits used to brick the daemon — this is
@@ -165,20 +201,6 @@ const sessionPathMemo = new Map();
165
201
  // either case would make startTimestamp jump on every rotation.
166
202
  let effectiveSessionStart = null;
167
203
 
168
- // Single-instance guard — an ATOMIC claim (see ensure-daemon.claimSingleInstance).
169
- // Many launchers can fire at once now that the SessionStart hook self-heals the
170
- // daemon: a manual `start`, a Windows Run entry, and several concurrent sessions'
171
- // hooks could all spawn a daemon in the same instant. A second daemon would
172
- // fight over setActivity every ~4s and double-count the additive community
173
- // total. The old read-then-write guard had a window where two starters both saw
174
- // "no live owner" and both wrote their pid; the exclusive-create claim closes it
175
- // so exactly one survives. A live owner → we exit; a stale pid → we reclaim it.
176
- const ownerPid = claimSingleInstance();
177
- if (ownerPid) {
178
- log(`Another daemon (pid ${ownerPid}) is already running — exiting.`);
179
- process.exit(0);
180
- }
181
-
182
204
  // Reclaim any per-pid state tmp files orphaned by a hard-killed writer, plus
183
205
  // per-session state files from sessions that ended long ago. The session-state
184
206
  // sweep repeats every 30 min — a daemon runs for weeks, and every file left
@@ -816,17 +838,85 @@ async function runBackgroundScan({ force = false } = {}) {
816
838
 
817
839
  function shutdown() {
818
840
  log('Shutting down…');
819
- // Both calls below are best-effort cleanup on the way out the door.
820
- // If the IPC client is already half-dead or the PID file was removed
821
- // by something else, we don't care — we're exiting anyway.
822
- try { client?.destroy(); } catch { /* IPC already gone */ }
823
- try { if (existsSync(PID_PATH)) unlinkSync(PID_PATH); } catch { /* race vs another shutdown */ }
841
+ // Best-effort cleanup on the way out the door. Only remove the pid/info
842
+ // files if they are still OURS: during an update handover the replacement
843
+ // daemon claims the pid file while we wind down, and deleting it blindly
844
+ // orphaned the replacement (`status` said "not running", the next hook
845
+ // spawned a second daemon, and `stop` could only ever kill one of them).
846
+ try { client?.destroy(); } catch { /* IPC already gone (or not created yet) */ }
847
+ try { if (readPid() === process.pid) unlinkSync(PID_PATH); } catch { /* race vs another shutdown */ }
848
+ try { if (readDaemonInfo()?.pid === process.pid) unlinkSync(DAEMON_INFO_PATH); } catch { /* gone */ }
824
849
  process.exit(0);
825
850
  }
826
851
 
827
- process.on('SIGINT', shutdown);
828
- process.on('SIGTERM', shutdown);
829
- process.on('SIGHUP', shutdown);
852
+ // ── Lifecycle watchdog ──────────────────────────────────────────────────────
853
+ // Every BEAT_EVERY_MS: honor a `stop` (any daemon still alive — a duplicate the
854
+ // signal missed, one a launcher started anyway — exits), reconcile the pid file
855
+ // (a tmp cleaner deleting it used to let every SessionStart add one more
856
+ // daemon), refresh the heartbeat, and hand over to new code once an update has
857
+ // replaced the files on disk.
858
+ function onDiskVersion() {
859
+ if (IS_PACKAGED) {
860
+ // The packaged exe can't be read for a version; its file changing under us
861
+ // (setup/the desktop app copying a new build over the canonical exe) is the
862
+ // signal. Only meaningful when we ARE the canonical exe.
863
+ const norm = (x) => (process.platform === 'win32' ? x.toLowerCase() : x);
864
+ if (norm(process.execPath) !== norm(CANONICAL_EXE)) return null;
865
+ try { const st = statSync(CANONICAL_EXE); return `${st.size}:${st.mtimeMs}`; } catch { return null; }
866
+ }
867
+ try { return JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version || null; } catch { return null; }
868
+ }
869
+ const BOOT_DISK_VERSION = onDiskVersion();
870
+ let diskChangeSeen = null; // needs two consecutive sightings — npm may be mid-extract
871
+ let handingOver = false;
872
+ let handoverBlockedUntil = 0;
873
+
874
+ // Spawn a fresh daemon from whatever is on disk and exit once it has claimed
875
+ // the pid file. If it never comes up, keep running (better old code than none)
876
+ // and don't try again for an hour.
877
+ function handOver(reason) {
878
+ if (handingOver || Date.now() < handoverBlockedUntil) return;
879
+ handingOver = true;
880
+ log(`${reason} — handing over to a fresh daemon`);
881
+ try { if (readPid() === process.pid) unlinkSync(PID_PATH); } catch { /* gone */ }
882
+ spawnDaemonDetached();
883
+ const deadline = Date.now() + 8000;
884
+ const poll = setInterval(() => {
885
+ const cur = readPid();
886
+ if (cur && cur !== process.pid && isAlive(cur)) { clearInterval(poll); shutdown(); return; }
887
+ if (Date.now() < deadline) return;
888
+ clearInterval(poll);
889
+ log('Handover failed: the new daemon never came up — staying on this one');
890
+ try { writeFileSync(PID_PATH, String(process.pid)); } catch { /* unwritable */ }
891
+ handingOver = false;
892
+ handoverBlockedUntil = Date.now() + 60 * 60_000;
893
+ }, 250);
894
+ }
895
+
896
+ function lifecycleTick() {
897
+ if (handingOver) return;
898
+ if (isStopped()) { log('Stop requested (`claude-rpc stop`)'); shutdown(); return; }
899
+ const cur = readPid();
900
+ if (cur !== process.pid) {
901
+ const info = readDaemonInfo();
902
+ if (cur && isAlive(cur) && info?.pid === cur && Date.now() - (info.beatAt || 0) < BEAT_STALE_MS) {
903
+ log(`Another daemon (pid ${cur}) owns the pid file — exiting as a duplicate`);
904
+ try { client?.destroy(); } catch { /* gone */ }
905
+ process.exit(0);
906
+ }
907
+ try { writeFileSync(PID_PATH, String(process.pid)); log(`Pid file ${cur ? `named pid ${cur}` : 'was missing'} — restored`); }
908
+ catch { /* unwritable — run lockless */ }
909
+ }
910
+ beat();
911
+ const disk = onDiskVersion();
912
+ if (disk && BOOT_DISK_VERSION && disk !== BOOT_DISK_VERSION) {
913
+ if (diskChangeSeen === disk) handOver(`Update on disk (${IS_PACKAGED ? 'new exe' : `${VERSION} → ${disk}`})`);
914
+ diskChangeSeen = disk;
915
+ } else {
916
+ diskChangeSeen = null;
917
+ }
918
+ }
919
+ setInterval(lifecycleTick, BEAT_EVERY_MS);
830
920
 
831
921
  log('Claude RPC daemon starting. clientId=', config.clientId);
832
922
  if (!config.clientId || config.clientId === '1234567890123456789') {
@@ -949,7 +1039,7 @@ async function runCommunityFlush() {
949
1039
  // independent of community totals but reuses the same anonymous instanceId.
950
1040
  if (!config.community?.enabled && !config.profile?.enabled) return;
951
1041
  try {
952
- const { flushCommunity, flushProfile } = await import('./community.js');
1042
+ const { flushCommunity, flushProfile, recordProfileResult } = await import('./community.js');
953
1043
  if (config.community?.enabled) {
954
1044
  const result = await flushCommunity(config);
955
1045
  if (result.ok && result.delta) {
@@ -960,6 +1050,7 @@ async function runCommunityFlush() {
960
1050
  }
961
1051
  if (config.profile?.enabled) {
962
1052
  const pr = await flushProfile(config);
1053
+ recordProfileResult(pr);
963
1054
  if (pr.ok && pr.totals) {
964
1055
  log(`profile: published @${config.profile.handle} (${pr.totals.tokens} tokens)`);
965
1056
  } else if (!pr.ok && pr.reason !== 'rate-limited' && pr.reason !== 'disabled') {
@@ -988,10 +1079,9 @@ async function runUpdateCheck() {
988
1079
  try {
989
1080
  const r = await checkForUpdate({ current: VERSION, auto: config.update?.auto !== false });
990
1081
  if (r.installed) {
991
- log(`auto-update: ${VERSION} → ${r.latest} installed; restarting`);
992
- try { if (existsSync(PID_PATH)) unlinkSync(PID_PATH); } catch { /* shutdown() retries */ }
993
- spawnDaemonDetached();
994
- setTimeout(shutdown, 500);
1082
+ handOver(`auto-update: ${VERSION} → ${r.latest} installed`);
1083
+ } else if (r.plan.reason === 'registry unreachable') {
1084
+ log('auto-update: could not reach the npm registry — will retry');
995
1085
  } else if (r.error) {
996
1086
  log(`auto-update: install of ${r.latest} failed: ${String(r.error).slice(-200)}`);
997
1087
  } else if (r.plan.action === 'notify') {
package/src/doctor.js CHANGED
@@ -17,8 +17,9 @@ import {
17
17
  } from './paths.js';
18
18
  import { findLiveSessions } from './scanner.js';
19
19
  import { listSessionStates, readActiveState } from './state.js';
20
- import { isAlive } from './ensure-daemon.js';
20
+ import { isAlive, isStopped, readDaemonInfo, BEAT_STALE_MS } from './ensure-daemon.js';
21
21
  import { detectGithubUrl } from './git.js';
22
+ import { VERSION } from './version.js';
22
23
  import { resolveVisibility, listPrivateCwds, detectGithubPrivate } from './privacy.js';
23
24
  import { readClaudeCredentials, readUsageCache } from './usage.js';
24
25
  import { EVENTS as HOOK_EVENTS, isOurHook } from './install.js';
@@ -295,6 +296,11 @@ function checkCliOnPath() {
295
296
  }
296
297
 
297
298
  function checkDaemon() {
299
+ if (isStopped()) {
300
+ // A deliberate `claude-rpc stop` is not a fault; --fix leaves it alone.
301
+ check('daemon running', 'warn', 'stopped (you ran `claude-rpc stop`)', 'run `claude-rpc start` to resume');
302
+ return false;
303
+ }
298
304
  if (!existsSync(PID_PATH)) {
299
305
  check('daemon running', 'warn', 'no pid file',
300
306
  'run `claude-rpc start` to launch the daemon', 'daemon');
@@ -306,6 +312,22 @@ function checkDaemon() {
306
312
  'run `claude-rpc start` — old daemon died without cleaning up', 'daemon');
307
313
  return false;
308
314
  }
315
+ const info = readDaemonInfo();
316
+ if (info && info.pid === pid && Date.now() - (info.beatAt || 0) > BEAT_STALE_MS) {
317
+ check('daemon running', 'fail', `pid ${pid} is alive but the daemon's heartbeat stopped — a recycled pid or a wedged daemon`,
318
+ 'run `claude-rpc restart`', 'daemon');
319
+ return false;
320
+ }
321
+ if (!info || info.pid !== pid) {
322
+ check('daemon running', 'warn', `pid ${pid} — started by an older claude-rpc, still running its code`,
323
+ 'run `claude-rpc restart` to run this version', 'daemon');
324
+ return true;
325
+ }
326
+ if (info.version !== VERSION) {
327
+ check('daemon running', 'warn', `pid ${pid} is running v${info.version}, installed is v${VERSION}`,
328
+ 'run `claude-rpc restart` to run this version', 'daemon');
329
+ return true;
330
+ }
309
331
  check('daemon running', 'pass', `pid ${pid}`);
310
332
  return true;
311
333
  }
@@ -12,8 +12,12 @@
12
12
  // daemon survives.
13
13
 
14
14
  import { createRequire } from 'node:module';
15
- import { join } from 'node:path';
16
- import { PID_PATH, STATE_DIR, DAEMON_SCRIPT, CANONICAL_EXE, IS_PACKAGED } from './paths.js';
15
+ import { dirname, join } from 'node:path';
16
+ import {
17
+ PID_PATH, STATE_DIR, DAEMON_SCRIPT, CANONICAL_EXE, IS_PACKAGED, DAEMON_INFO_PATH, STOPPED_PATH,
18
+ } from './paths.js';
19
+ import { renameSyncRetry, sleepSync } from './atomic-rename.js';
20
+ import { VERSION } from './version.js';
17
21
 
18
22
  // require()d, not imported — on the hook hot path; see hook.js.
19
23
  const require = createRequire(import.meta.url);
@@ -21,6 +25,17 @@ const {
21
25
  openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, mkdirSync,
22
26
  } = require('node:fs');
23
27
 
28
+ // The daemon rewrites its heartbeat (DAEMON_INFO_PATH.beatAt) this often (its
29
+ // lifecycle watchdog tick); a
30
+ // beat older than BEAT_STALE_MS means the pid in the pid file is not our daemon
31
+ // any more (it died without cleanup and the OS recycled the pid — common after a
32
+ // Windows/macOS reboot, where the tmp dir and its stale pid file survive) or the
33
+ // daemon is wedged. Generous on purpose: a laptop waking from sleep shows a stale
34
+ // beat for up to one interval, and the cost of a false "dead" is one duplicate
35
+ // spawn that the daemons' own pid-file check reaps within a watchdog tick.
36
+ export const BEAT_EVERY_MS = 30_000;
37
+ export const BEAT_STALE_MS = 5 * 60_000;
38
+
24
39
  // mtime of this marker = last time any launcher attempted a spawn. A short
25
40
  // cooldown stops concurrent SessionStart hooks (several sessions opening at
26
41
  // once) and any startup crash-loop from spawning a swarm of throwaway daemons —
@@ -42,10 +57,91 @@ export function readPid(pidPath = PID_PATH) {
42
57
  catch { return 0; }
43
58
  }
44
59
 
60
+ // { pid, version, startedAt, beatAt } written by daemons from 1.9.0 on, or null
61
+ // (missing, unreadable, or an older daemon that never wrote one).
62
+ export function readDaemonInfo(infoPath = DAEMON_INFO_PATH) {
63
+ try {
64
+ const j = JSON.parse(readFileSync(infoPath, 'utf8'));
65
+ return j && typeof j === 'object' && Number.isFinite(j.pid) ? j : null;
66
+ } catch { return null; }
67
+ }
68
+
69
+ export function writeDaemonInfo(info, infoPath = DAEMON_INFO_PATH) {
70
+ try {
71
+ mkdirSync(dirname(infoPath), { recursive: true });
72
+ const tmp = `${infoPath}.${process.pid}.tmp`;
73
+ writeFileSync(tmp, JSON.stringify(info));
74
+ renameSyncRetry(tmp, infoPath);
75
+ } catch { /* advisory — liveness falls back to the bare pid probe */ }
76
+ }
77
+
78
+ // Pure: is `pid` our live daemon? A live pid is only trusted when the heartbeat
79
+ // written for THAT pid is fresh; with no heartbeat for it (a pre-1.9 daemon, or
80
+ // the info file belongs to someone else) the bare probe is all we have.
81
+ export function pidIsDaemon(pid, { info = null, alive = isAlive, now = Date.now(), staleMs = BEAT_STALE_MS } = {}) {
82
+ if (!pid || !alive(pid)) return false;
83
+ if (info && info.pid === pid && Number.isFinite(info.beatAt) && now - info.beatAt > staleMs) return false;
84
+ return true;
85
+ }
86
+
45
87
  // The pid of the live daemon, or 0 if none is running.
46
- export function daemonAlive(pidPath = PID_PATH) {
88
+ export function daemonAlive(pidPath = PID_PATH, infoPath = DAEMON_INFO_PATH) {
47
89
  const pid = readPid(pidPath);
48
- return pid && isAlive(pid) ? pid : 0;
90
+ return pidIsDaemon(pid, { info: pid ? readDaemonInfo(infoPath) : null }) ? pid : 0;
91
+ }
92
+
93
+ // ── stop intent ──────────────────────────────────────────────────────────
94
+ // `stop` used to send one signal and record nothing, so the very next
95
+ // SessionStart hook (any new session, /clear, a `claude -p` run) spawned the
96
+ // daemon right back. The marker makes a stop stick: the hook, the login
97
+ // autostart (the daemon checks it at boot) and running daemons (their watchdog
98
+ // checks it) all honor it until start/restart/setup clears it.
99
+ export function isStopped(path = STOPPED_PATH) {
100
+ return existsSync(path);
101
+ }
102
+ export function markStopped(path = STOPPED_PATH) {
103
+ try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, String(Date.now())); return true; }
104
+ catch { return false; }
105
+ }
106
+ export function clearStopped(path = STOPPED_PATH) {
107
+ try { if (existsSync(path)) unlinkSync(path); } catch { /* best-effort */ }
108
+ }
109
+
110
+ // Stop the daemon and wait until it is really gone. SIGTERM, then SIGKILL if it
111
+ // ignored that for `graceMs` (on Windows process.kill is always a hard kill).
112
+ // A hard kill skips the daemon's own cleanup, so a pid file still naming the
113
+ // dead pid is removed here — otherwise a recycled pid reads as "running".
114
+ // Resolves true when no daemon is left. `kill`/`sleep` are injectable for tests.
115
+ export async function stopDaemonAndWait({
116
+ pidPath = PID_PATH, infoPath = DAEMON_INFO_PATH, graceMs = 3000, killMs = 1500,
117
+ kill = (pid, sig) => process.kill(pid, sig), sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
118
+ } = {}) {
119
+ const pid = daemonAlive(pidPath, infoPath);
120
+ if (!pid) { cleanupPidFile(0, pidPath); return true; }
121
+ const gone = async (ms) => {
122
+ const deadline = Date.now() + ms;
123
+ for (;;) {
124
+ if (!isAlive(pid)) return true;
125
+ if (Date.now() >= deadline) return false;
126
+ await sleep(50);
127
+ }
128
+ };
129
+ try { kill(pid, 'SIGTERM'); } catch { /* already gone / not ours */ }
130
+ let ok = await gone(graceMs);
131
+ if (!ok) {
132
+ try { kill(pid, 'SIGKILL'); } catch { /* already gone */ }
133
+ ok = await gone(killMs);
134
+ }
135
+ if (ok) cleanupPidFile(pid, pidPath);
136
+ return ok;
137
+ }
138
+
139
+ // Remove the pid file if it still names `pid` (or a dead process when pid=0).
140
+ function cleanupPidFile(pid, pidPath = PID_PATH) {
141
+ try {
142
+ const cur = readPid(pidPath);
143
+ if (cur && (cur === pid || (!pid && !isAlive(cur)))) unlinkSync(pidPath);
144
+ } catch { /* gone already */ }
49
145
  }
50
146
 
51
147
  // The single source of truth for HOW to launch the daemon, shared by every
@@ -79,8 +175,9 @@ export function spawnDaemonDetached() {
79
175
 
80
176
  // Pure decision for the hook's self-heal: should THIS SessionStart spawn a
81
177
  // daemon? Separated from the side effects so it's unit-testable.
82
- export function shouldSpawnDaemon({ autostart, daemonPid, lastAttemptMs, now, cooldownMs }) {
178
+ export function shouldSpawnDaemon({ autostart, stopped = false, daemonPid, lastAttemptMs, now, cooldownMs }) {
83
179
  if (autostart === false) return false; // explicit opt-out
180
+ if (stopped) return false; // `claude-rpc stop` sticks
84
181
  if (daemonPid) return false; // already running
85
182
  if (lastAttemptMs && now - lastAttemptMs < cooldownMs) return false; // within the cooldown
86
183
  return true;
@@ -94,10 +191,60 @@ export function shouldSpawnDaemon({ autostart, daemonPid, lastAttemptMs, now, co
94
191
  export function ensureDaemonRunning({ autostart = true, now = Date.now(), cooldownMs = SPAWN_COOLDOWN_MS } = {}) {
95
192
  let lastAttemptMs = 0;
96
193
  try { if (existsSync(SPAWN_MARKER)) lastAttemptMs = statSync(SPAWN_MARKER).mtimeMs; } catch { /* unreadable — treat as never */ }
97
- if (!shouldSpawnDaemon({ autostart, daemonPid: daemonAlive(), lastAttemptMs, now, cooldownMs })) return null;
194
+ const stopped = isStopped();
195
+ let daemonPid = daemonAlive();
196
+ // An update swaps the files on disk but the running daemon keeps executing
197
+ // the old code — forever, since nothing restarted it (`npm i -g`, the
198
+ // desktop app's updater, a re-downloaded exe). The hook is the newer code, so
199
+ // it replaces a daemon that is older than itself (or too old to say).
200
+ if (daemonPid && autostart !== false && !stopped
201
+ && shouldReplaceDaemon({ info: readDaemonInfo(), pid: daemonPid, version: VERSION, lastAttemptMs, now })) {
202
+ stampSpawn(now);
203
+ if (!replaceDaemonSync(daemonPid)) return null;
204
+ daemonPid = 0;
205
+ lastAttemptMs = 0;
206
+ }
207
+ if (!shouldSpawnDaemon({ autostart, stopped, daemonPid, lastAttemptMs, now, cooldownMs })) return null;
208
+ stampSpawn(now);
209
+ return spawnDaemonDetached();
210
+ }
211
+
212
+ function stampSpawn(now) {
98
213
  try { mkdirSync(STATE_DIR, { recursive: true }); } catch { /* exists / unwritable */ }
99
214
  try { writeFileSync(SPAWN_MARKER, String(now)); } catch { /* best-effort cooldown */ }
100
- return spawnDaemonDetached();
215
+ }
216
+
217
+ // Pure: should a launcher at `version` replace the running daemon? Yes when the
218
+ // daemon reports an older version, or reports nothing (pre-1.9 daemons never
219
+ // wrote daemon.json). The no-info case is rate-limited to one attempt per
220
+ // REPLACE_COOLDOWN_MS so an unwritable tmp dir can't restart it every session.
221
+ const REPLACE_COOLDOWN_MS = 30 * 60_000;
222
+ export function shouldReplaceDaemon({ info, pid, version, lastAttemptMs = 0, now = Date.now(), cooldownMs = REPLACE_COOLDOWN_MS }) {
223
+ if (info && info.pid === pid) return typeof info.version === 'string' && isNewerVersion(version, info.version);
224
+ return !(lastAttemptMs && now - lastAttemptMs < cooldownMs);
225
+ }
226
+
227
+ export function isNewerVersion(a, b) {
228
+ const p = (v) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(v || '')) || []).slice(1).map(Number);
229
+ const x = p(a), y = p(b);
230
+ if (x.length !== 3 || y.length !== 3) return false;
231
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
232
+ return false;
233
+ }
234
+
235
+ // Synchronous stop for the hook (it can't await): SIGTERM, wait ≤2s for the
236
+ // process to go, hard-kill if it didn't. True once it's gone.
237
+ function replaceDaemonSync(pid) {
238
+ const waitGone = (ms) => {
239
+ const deadline = Date.now() + ms;
240
+ while (Date.now() < deadline) { if (!isAlive(pid)) return true; sleepSync(50); }
241
+ return !isAlive(pid);
242
+ };
243
+ try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ }
244
+ let gone = waitGone(2000);
245
+ if (!gone) { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } gone = waitGone(1000); }
246
+ if (gone) cleanupPidFile(pid);
247
+ return gone;
101
248
  }
102
249
 
103
250
  // Atomic single-instance claim, called once by the daemon at startup. Returns
@@ -107,7 +254,7 @@ export function ensureDaemonRunning({ autostart = true, now = Date.now(), cooldo
107
254
  // losers read the winner's live pid and step aside. A stale file (dead owner,
108
255
  // empty, or our own recycled pid) is reclaimed and the create retried — so a
109
256
  // crashed daemon never blocks its successor.
110
- export function claimSingleInstance({ pidPath = PID_PATH, pid = process.pid, alive = isAlive } = {}) {
257
+ export function claimSingleInstance({ pidPath = PID_PATH, pid = process.pid, alive = (p) => pidIsDaemon(p, { info: readDaemonInfo() }) } = {}) {
111
258
  for (let attempt = 0; attempt < 4; attempt++) {
112
259
  let fd;
113
260
  try {
@@ -0,0 +1,78 @@
1
+ // Coarse, local feature-usage stamps for the anonymous community report.
2
+ //
3
+ // Each user-facing command records "last used at" in STATE_DIR (no args, no
4
+ // paths, no counts). The daemon's /report then sends the NAMES of commands
5
+ // used in the last 7 days (`feat`), alongside how this copy was installed and
6
+ // how its last auto-update went. That's the whole signal: it tells the author
7
+ // which features anyone actually uses, and why updates do or don't land.
8
+ // Turned off with everything else by `claude-rpc community off`.
9
+
10
+ import { readFileSync, mkdirSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { STATE_DIR } from './paths.js';
13
+ import { writeFileAtomic } from './atomic-rename.js';
14
+
15
+ export const FEATURE_USAGE_PATH = join(STATE_DIR, 'feature-usage.json');
16
+ export const FEATURE_WINDOW_MS = 7 * 86_400_000;
17
+ const RESTAMP_MS = 3_600_000; // statusline/mcp run constantly; one write an hour is plenty
18
+
19
+ // Command → reported feature name. Anything not listed is never recorded.
20
+ const ALIASES = { log: 'tail', logs: 'tail', unpause: 'resume', install: 'setup', 'upgrade-config': 'setup' };
21
+ export const FEATURES = new Set([
22
+ 'tui', 'desktop', 'setup', 'uninstall', 'start', 'stop', 'restart', 'status', 'dump', 'today', 'week',
23
+ 'projects', 'project', 'compare', 'usage', 'serve', 'settings', 'preview', 'vars', 'scan', 'rescan',
24
+ 'backfill', 'insights', 'recap', 'badge', 'card', 'github-stat', 'statusline', 'calendar',
25
+ 'session-card', 'readme', 'mcp', 'wrapped', 'share', 'statcards', 'completion', 'pause', 'resume',
26
+ 'export', 'private', 'public', 'privacy', 'community', 'update', 'profile', 'link', 'doctor', 'tail',
27
+ ]);
28
+
29
+ export function featureName(cmd) {
30
+ const name = ALIASES[cmd] || cmd;
31
+ return FEATURES.has(name) ? name : null;
32
+ }
33
+
34
+ function read(path) {
35
+ try { const j = JSON.parse(readFileSync(path, 'utf8')); return j && typeof j === 'object' ? j : {}; } catch { return {}; }
36
+ }
37
+
38
+ // Best-effort; never throws.
39
+ export function stampFeature(cmd, { now = Date.now(), path = FEATURE_USAGE_PATH } = {}) {
40
+ const name = featureName(cmd);
41
+ if (!name) return;
42
+ try {
43
+ const cur = read(path);
44
+ if (Number.isFinite(cur[name]) && now - cur[name] < RESTAMP_MS) return;
45
+ cur[name] = now;
46
+ mkdirSync(STATE_DIR, { recursive: true });
47
+ writeFileAtomic(path, JSON.stringify(cur));
48
+ } catch { /* advisory only */ }
49
+ }
50
+
51
+ // Sorted names used within the window.
52
+ export function recentFeatures({ now = Date.now(), path = FEATURE_USAGE_PATH, windowMs = FEATURE_WINDOW_MS } = {}) {
53
+ const cur = read(path);
54
+ return Object.keys(cur).filter((k) => FEATURES.has(k) && Number.isFinite(cur[k]) && now - cur[k] < windowMs).sort();
55
+ }
56
+
57
+ // Pure: update.json → a short outcome code for the report.
58
+ // ok last check found nothing newer / last install succeeded
59
+ // off auto-update disabled
60
+ // manual this install kind can't self-update (brew, npx, dev, packaged off-canonical)
61
+ // perm install folder not writable
62
+ // failed last install attempt failed
63
+ // pending newer release seen, inside the cooldown
64
+ // unknown never checked (pre-1.7 state, or the daemon hasn't run a check yet)
65
+ export function updateOutcome(state) {
66
+ const p = state?.lastPlan;
67
+ if (!p) return 'unknown';
68
+ if (state.failed?.version && state.failed.version === p.latest && state.updatedTo !== p.latest) return 'failed';
69
+ const r = String(p.reason || '');
70
+ if (p.action === 'none') return r === 'registry unreachable' ? 'unknown' : 'ok';
71
+ if (p.action === 'install') return 'ok';
72
+ if (/install failed|last install attempt failed/.test(r)) return 'failed';
73
+ if (/auto-update is off/.test(r)) return 'off';
74
+ if (/admin rights|not writable/.test(r)) return 'perm';
75
+ if (/settling|cooldown/.test(r)) return 'pending';
76
+ if (/installed via|new major/.test(r)) return 'manual';
77
+ return 'unknown';
78
+ }