whetstone-cli 3.19.1

Installer and CLI for Claude Code token optimization (Headroom + RTK + Memory)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

use crate::ui;
use crate::version;

const NPM_REGISTRY_URL: &str =
    "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";

#[derive(Debug, PartialEq, Eq)]
pub enum InstallMethod {
    NativeBinary,
    Npm,
    Mise,
    Unknown,
}

#[derive(Deserialize)]
struct NpmLatest {
    version: String,
}

pub fn installed_version() -> Option<String> {
    let output = Command::new("claude").arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_claude_version(&raw)
}

fn parse_claude_version(raw: &str) -> Option<String> {
    let first_token = raw.split_whitespace().next()?;
    version::extract_semver(first_token)
}

pub fn latest_npm_version() -> Option<String> {
    let resp = ureq::get(NPM_REGISTRY_URL)
        .header("Accept", "application/json")
        .call()
        .ok()?;
    let body = resp.into_body().read_to_string().ok()?;
    parse_npm_response(&body)
}

fn parse_npm_response(body: &str) -> Option<String> {
    let parsed: NpmLatest = serde_json::from_str(body).ok()?;
    version::extract_semver(&parsed.version)
}

pub fn install_method() -> InstallMethod {
    detect_install_method_from_path(resolve_claude_binary())
}

fn resolve_claude_binary() -> Option<PathBuf> {
    let output = Command::new("which").arg("claude").output().ok()?;
    if !output.status.success() {
        return None;
    }
    let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let path = PathBuf::from(&path_str);
    fs::canonicalize(&path).ok().or(Some(path))
}

fn detect_install_method_from_path(
    binary_path: Option<PathBuf>,
) -> InstallMethod {
    let Some(path) = binary_path else {
        return InstallMethod::Unknown;
    };
    let path_str = path.to_string_lossy();

    if path_str.contains(".local/share/claude/versions/") {
        return InstallMethod::NativeBinary;
    }

    // mise manages `claude` as its own tool (not via a mise-installed node),
    // so `npm install -g` is a no-op here: mise's install dir sits earlier on
    // PATH than npm's global bin, and `claude` keeps resolving to the
    // mise-pinned version regardless of what npm just installed.
    if path_str.contains("/mise/installs/claude/")
        || path_str.contains("/mise/shims/claude")
    {
        return InstallMethod::Mise;
    }

    if path_str.contains("node_modules")
        || path_str.contains("/node/")
        || path_str.contains("/nodejs/")
        || path_str.contains("/mise/installs/node/")
        || path_str.contains("/nvm/versions/node/")
        || path_str.contains("/fnm/node-versions/")
        || path_str.contains("/.volta/")
    {
        return InstallMethod::Npm;
    }

    InstallMethod::Unknown
}

/// Install Claude Code globally via npm.
///
/// Claude Code is the one managed dependency whetstone can't install without
/// a Node toolchain, so bail with an actionable message rather than letting
/// `npm` fail obscurely.
pub fn install() -> Result<()> {
    if which::which("npm").is_err() {
        bail!(
            "npm not found — install Node.js (https://nodejs.org) then rerun, \
             or install Claude Code yourself"
        );
    }

    ui::info(
        "installing claude code (npm install -g @anthropic-ai/claude-code)",
    );
    run_npm_install()?;
    ensure_config_install_method_is_npm();

    match installed_version() {
        Some(ver) => {
            ui::ok(&format!("claude code {ver}"));
            Ok(())
        }
        None => bail!(
            "claude code installed but `claude` is not on PATH — check your npm global bin dir"
        ),
    }
}

/// `target_version` is whetstone's own npm-registry lookup of the latest
/// release (see `latest_npm_version`). The mise `claude` backend resolves
/// its own "latest" via a separately cached GitHub releases lookup that can
/// get stuck stale (observed surviving even `mise cache clear`), so the mise
/// path pins to this known-good version directly instead of trusting mise's
/// own upgrade/latest resolution.
pub fn update(target_version: Option<&str>) -> Result<ui::ComponentStatus> {
    let Some(old_ver) = installed_version() else {
        return Ok(ui::ComponentStatus::NotInstalled);
    };

    let method = install_method();

    let result = match method {
        InstallMethod::NativeBinary => update_from_native(&old_ver),
        InstallMethod::Mise => update_via_mise(&old_ver, target_version),
        InstallMethod::Npm | InstallMethod::Unknown => update_via_npm(&old_ver),
    };

    // Only true for methods that actually installed via npm — forcing this
    // for a mise-managed install would mislabel it and has no bearing on
    // what `claude` resolves to.
    if method != InstallMethod::Mise {
        ensure_config_install_method_is_npm();
    }

    result
}

fn update_from_native(old_ver: &str) -> Result<ui::ComponentStatus> {
    ui::info("native binary detected — installing via npm to fix stale update channel");

    run_npm_install()?;
    // npm can succeed with its global bin dir missing from PATH; deleting the
    // native copy then would leave no `claude` at all.
    if another_claude_on_path() {
        cleanup_native_install();
    } else {
        ui::warn(
            "npm installed claude code, but its bin dir is not on PATH — \
             keeping the native binary. Add npm's global bin to PATH and \
             run `whetstone update` again.",
        );
    }

    let new_ver = installed_version().unwrap_or_else(|| old_ver.to_string());
    if new_ver != old_ver {
        Ok(ui::ComponentStatus::Updated(old_ver.to_string(), new_ver))
    } else {
        Ok(ui::ComponentStatus::UpToDate(old_ver.to_string()))
    }
}

fn update_via_npm(old_ver: &str) -> Result<ui::ComponentStatus> {
    run_npm_install()?;

    let new_ver = installed_version().unwrap_or_else(|| old_ver.to_string());
    if new_ver != old_ver {
        Ok(ui::ComponentStatus::Updated(old_ver.to_string(), new_ver))
    } else {
        Ok(ui::ComponentStatus::UpToDate(old_ver.to_string()))
    }
}

fn update_via_mise(
    old_ver: &str,
    target_version: Option<&str>,
) -> Result<ui::ComponentStatus> {
    match target_version {
        Some(version) => run_mise_use(version)?,
        None => run_mise_upgrade()?,
    }

    let new_ver = installed_version().unwrap_or_else(|| old_ver.to_string());
    if new_ver != old_ver {
        Ok(ui::ComponentStatus::Updated(old_ver.to_string(), new_ver))
    } else {
        Ok(ui::ComponentStatus::UpToDate(old_ver.to_string()))
    }
}

/// Pins mise's `claude` tool to an exact known-good version, bypassing
/// mise's own (unreliable) "latest" resolution entirely.
fn run_mise_use(version: &str) -> Result<()> {
    let output = Command::new("mise")
        .args(["use", "-g", &format!("claude@{version}")])
        .output()
        .context("failed to run mise use -g claude@<version>")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("mise use -g claude@{version} failed: {stderr}");
    }

    Ok(())
}

/// Fallback when whetstone couldn't determine the target version itself
/// (e.g. the npm registry lookup failed) — best effort via mise's own
/// resolution, which may itself be stale.
fn run_mise_upgrade() -> Result<()> {
    let output = Command::new("mise")
        .args(["upgrade", "claude"])
        .output()
        .context("failed to run mise upgrade claude")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("mise upgrade claude failed: {stderr}");
    }

    Ok(())
}

fn run_npm_install() -> Result<()> {
    let output = Command::new("npm")
        .args(["install", "-g", "@anthropic-ai/claude-code"])
        .output()
        .context("failed to run npm install")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("npm install -g @anthropic-ai/claude-code failed: {stderr}");
    }

    Ok(())
}

/// Is there a `claude` on PATH that is not the native install?
fn another_claude_on_path() -> bool {
    which::which_all("claude").is_ok_and(|paths| {
        paths
            .filter_map(|p| p.canonicalize().ok())
            .any(|p| !is_native_path(&p))
    })
}

fn is_native_path(path: &std::path::Path) -> bool {
    path.to_string_lossy().contains(".local/share/claude/")
}

fn cleanup_native_install() {
    let Some(home) = dirs::home_dir() else {
        return;
    };

    let symlink = home.join(".local/bin/claude");
    let versions_dir = home.join(".local/share/claude");

    if symlink.is_symlink() || symlink.exists() {
        if let Ok(target) = fs::read_link(&symlink) {
            if target
                .to_string_lossy()
                .contains(".local/share/claude/versions/")
            {
                ui::info("removing stale native binary symlink (~/.local/bin/claude)");
                let _ = fs::remove_file(&symlink);
            }
        }
    }

    if versions_dir.is_dir() {
        ui::info(
            "removing stale native versions directory (~/.local/share/claude/)",
        );
        let _ = fs::remove_dir_all(&versions_dir);
    }
}

fn ensure_config_install_method_is_npm() {
    let Some(home) = dirs::home_dir() else {
        return;
    };
    fix_install_method_in_config(&home);
}

fn fix_install_method_in_config(home: &std::path::Path) {
    let config_path = home.join(".claude.json");

    let content = match fs::read_to_string(&config_path) {
        Ok(c) => c,
        Err(_) => return,
    };

    let mut config: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(_) => return,
    };

    let obj = match config.as_object_mut() {
        Some(o) => o,
        None => return,
    };

    if obj.get("installMethod").and_then(|v| v.as_str()) == Some("npm") {
        return;
    }

    obj.insert(
        "installMethod".to_string(),
        serde_json::Value::String("npm".to_string()),
    );

    ui::info("fixing installMethod in ~/.claude.json (native → npm)");
    let _ = fs::write(
        &config_path,
        serde_json::to_string_pretty(&config).unwrap_or_default(),
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_claude_version_standard_format() {
        assert_eq!(
            parse_claude_version("2.1.153 (Claude Code)"),
            Some("2.1.153".into()),
        );
    }

    #[test]
    fn parse_claude_version_bare() {
        assert_eq!(parse_claude_version("2.1.172"), Some("2.1.172".into()));
    }

    #[test]
    fn parse_claude_version_empty() {
        assert_eq!(parse_claude_version(""), None);
    }

    #[test]
    fn parse_claude_version_garbage() {
        assert_eq!(parse_claude_version("not a version"), None);
    }

    #[test]
    fn parse_npm_response_valid() {
        let body =
            r#"{"name":"@anthropic-ai/claude-code","version":"2.1.172"}"#;
        assert_eq!(parse_npm_response(body), Some("2.1.172".into()));
    }

    #[test]
    fn parse_npm_response_invalid_json() {
        assert_eq!(parse_npm_response("{broken"), None);
    }

    #[test]
    fn parse_npm_response_missing_version() {
        assert_eq!(parse_npm_response(r#"{"name":"foo"}"#), None);
    }

    #[test]
    fn detect_native_binary_path() {
        let path = Some(PathBuf::from(
            "/home/user/.local/share/claude/versions/2.1.153",
        ));
        assert_eq!(
            detect_install_method_from_path(path),
            InstallMethod::NativeBinary,
        );
    }

    #[test]
    fn detect_npm_via_mise() {
        let path = Some(PathBuf::from(
            "/home/user/.local/share/mise/installs/node/24.11.1/bin/claude",
        ));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Npm);
    }

    #[test]
    fn detect_mise_native_tool_install() {
        let path = Some(PathBuf::from(
            "/home/user/.local/share/mise/installs/claude/latest/claude",
        ));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Mise);
    }

    #[test]
    fn detect_mise_shim() {
        let path =
            Some(PathBuf::from("/home/user/.local/share/mise/shims/claude"));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Mise);
    }

    #[test]
    fn detect_npm_via_nvm() {
        let path = Some(PathBuf::from(
            "/home/user/.nvm/versions/node/v22.0.0/bin/claude",
        ));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Npm);
    }

    #[test]
    fn detect_npm_via_node_modules() {
        let path = Some(PathBuf::from(
            "/usr/lib/node_modules/@anthropic-ai/claude-code/bin/claude",
        ));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Npm);
    }

    #[test]
    fn detect_npm_via_volta() {
        let path = Some(PathBuf::from("/home/user/.volta/bin/claude"));
        assert_eq!(detect_install_method_from_path(path), InstallMethod::Npm);
    }

    #[test]
    fn detect_unknown_when_no_binary() {
        assert_eq!(
            detect_install_method_from_path(None),
            InstallMethod::Unknown
        );
    }

    #[test]
    fn detect_unknown_for_unrecognized_path() {
        let path = Some(PathBuf::from("/opt/custom/bin/claude"));
        assert_eq!(
            detect_install_method_from_path(path),
            InstallMethod::Unknown,
        );
    }

    #[test]
    fn fix_install_method_rewrites_native_to_npm() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(".claude.json");
        fs::write(&config, r#"{"installMethod":"native","numStartups":10}"#)
            .unwrap();

        fix_install_method_in_config(dir.path());

        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&config).unwrap())
                .unwrap();
        assert_eq!(result["installMethod"], "npm");
        assert_eq!(result["numStartups"], 10);
    }

    #[test]
    fn fix_install_method_noop_when_already_npm() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(".claude.json");
        let original = r#"{"installMethod":"npm","numStartups":5}"#;
        fs::write(&config, original).unwrap();

        fix_install_method_in_config(dir.path());

        let after = fs::read_to_string(&config).unwrap();
        assert_eq!(after, original, "file should not be rewritten");
    }

    #[test]
    fn fix_install_method_adds_field_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(".claude.json");
        fs::write(&config, r#"{"numStartups":1}"#).unwrap();

        fix_install_method_in_config(dir.path());

        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&config).unwrap())
                .unwrap();
        assert_eq!(result["installMethod"], "npm");
    }

    #[test]
    fn fix_install_method_noop_when_no_config_file() {
        let dir = tempfile::tempdir().unwrap();
        fix_install_method_in_config(dir.path());
        assert!(!dir.path().join(".claude.json").exists());
    }

    #[test]
    fn fix_install_method_noop_for_invalid_json() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join(".claude.json");
        let garbage = "not json {{{";
        fs::write(&config, garbage).unwrap();

        fix_install_method_in_config(dir.path());

        assert_eq!(fs::read_to_string(&config).unwrap(), garbage);
    }

    #[test]
    fn native_install_paths_are_recognised() {
        assert!(is_native_path(std::path::Path::new(
            "/home/u/.local/share/claude/versions/2.1.0"
        )));
        assert!(!is_native_path(std::path::Path::new(
            "/home/u/.npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js"
        )));
    }
}