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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use anyhow::{bail, Context, Result};
use std::fs;
use std::path::{Path, PathBuf};

use crate::config::{ToolVersions, WhetstoneManifest};
use crate::memory::MemoryProvider;
use crate::{
    config, doctor, headroom, integrations, migrate, preflight, remote, rtk,
    shell, ui, update,
};

pub(crate) const DEFAULT_PROXY: &str = "http://127.0.0.1:8787";

pub fn resolve_assets_dir() -> Result<PathBuf> {
    if let Ok(dir) = std::env::var("WHETSTONE_ASSETS") {
        let p = PathBuf::from(dir);
        if p.is_dir() {
            return Ok(p);
        }
    }

    if let Ok(exe) = std::env::current_exe() {
        if let Some(bin_dir) = exe.parent() {
            for candidate in ["../assets", "../../assets"] {
                let relative = bin_dir.join(candidate);
                if relative.is_dir() {
                    return Ok(relative.canonicalize()?);
                }
            }
        }
    }

    let home =
        dirs::home_dir().context("could not determine home directory")?;
    let fallback = home.join(".whetstone").join("assets");
    if fallback.is_dir() {
        return Ok(fallback);
    }

    bail!(
        "could not locate whetstone assets — set WHETSTONE_ASSETS or install to ~/.whetstone/assets/"
    );
}

/// `whetstone setup --headroom-remote DEST [--remote-install]`.
#[derive(Debug, Default, Clone)]
pub struct RemoteArg {
    pub dest: Option<String>,
    pub install: bool,
}

pub fn run(
    full: bool,
    headroom_extras: &str,
    remote: &RemoteArg,
) -> Result<()> {
    maybe_self_update(full, headroom_extras, remote);

    let migrated = migrate::detect_and_offer(false)?;

    if ui::is_interactive() {
        return crate::wizard::run(full, headroom_extras, migrated, remote);
    }
    run_sequential(full, headroom_extras, migrated, remote)
}

/// Decide where the Headroom proxy runs, and make a chosen remote ready.
///
/// Returns the value to record as this *project's* `headroom_remote`:
/// `None` leaves the manifest alone (nothing asked, or the choice was saved
/// globally), `Some("")` clears it, `Some("local")` pins this project local
/// under a global remote, and anything else is the ssh destination.
pub(crate) fn configure_headroom_location(
    arg: &RemoteArg,
    headroom_extras: &str,
    full: bool,
) -> Result<Option<String>> {
    let mut global = config::GlobalSettings::load().unwrap_or_default();
    let project = WhetstoneManifest::load(&WhetstoneManifest::path_for(
        &std::env::current_dir()?,
    ))
    .ok()
    .flatten()
    .map(|m| m.settings)
    .unwrap_or_default();
    let current =
        config::ResolvedSettings::resolve(&global, &project).headroom_remote;

    let (dest, for_project, install) = match &arg.dest {
        Some(dest) => (dest.clone(), true, arg.install),
        // `--full` refreshes an existing install; it never re-asks.
        None if full || !ui::is_interactive() => return Ok(None),
        None => {
            let places = ["This machine", "A remote machine (over SSH)"];
            let default = usize::from(current.is_some());
            if ui::select(
                "Where should the Headroom proxy run?",
                &places,
                default,
            ) == 0
            {
                return Ok(local_choice(
                    global.headroom_remote.is_some(),
                    project.headroom_remote.is_some(),
                ));
            }

            let hint = current
                .as_deref()
                .map(|c| format!(" [{c}]"))
                .unwrap_or_default();
            let typed = ui::input(&format!(
                "SSH destination (user@host or an ssh-config alias){hint}:"
            ));
            let dest = if typed.is_empty() {
                current.context("no ssh destination given")?
            } else {
                typed
            };
            remote::validate_dest(&dest)?;

            let scopes = ["This project", "All projects (global default)"];
            let for_project =
                ui::select("Use the remote Headroom for:", &scopes, 0) == 0;
            ensure_reachable(&dest)?;
            let modes =
                ["Install and configure it now", "It is already set up"];
            let install =
                ui::select(&format!("Headroom on {dest}:"), &modes, 0) == 0;
            (dest, for_project, install)
        }
    };

    if arg.dest.is_some() {
        ensure_reachable(&dest)?;
    }
    if install {
        ui::info(&format!("installing headroom on {dest}"));
        remote::install(&dest, headroom_extras)?;
    }
    match remote::status(&dest)?.problem() {
        Some(problem) => ui::warn(&format!(
            "{dest}: {problem} — run `whetstone install-tools` to fix it"
        )),
        None => ui::ok(&format!("remote headroom ready on {dest}")),
    }

    if for_project {
        return Ok(Some(dest));
    }
    global.headroom_remote = Some(dest);
    global.save()?;
    ui::ok("saved remote headroom as the global default");
    // A stale project value would shadow the global one just chosen.
    Ok(project.headroom_remote.map(|_| String::new()))
}

/// What choosing "This machine" records for the project: pin it `local`
/// under a global remote, clear a project remote, else leave things alone.
fn local_choice(global_remote: bool, project_remote: bool) -> Option<String> {
    match (global_remote, project_remote) {
        (true, _) => Some(config::REMOTE_LOCAL.to_string()),
        (false, true) => Some(String::new()),
        (false, false) => None,
    }
}

/// Remote mode needs key/agent login: every launch runs ssh unattended.
fn ensure_reachable(dest: &str) -> Result<()> {
    let Err(e) = remote::reachable(dest) else {
        return Ok(());
    };
    ui::warn(&format!("cannot log in to {dest} without a prompt: {e:#}"));
    if ui::is_interactive()
        && ui::confirm(
            &format!("Run `ssh-copy-id {dest}` to set up key login?"),
            true,
        )
    {
        let _pause = ui::pause_wizard();
        remote::copy_id(dest)?;
        return remote::reachable(dest)
            .context("still cannot log in with a key");
    }
    Err(e).context(
        "a remote headroom needs key-based ssh login (no password prompt)",
    )
}

/// A project-scoped remote has nowhere to live when no manifest is written
/// (memory provider skipped), so it becomes the global default instead.
pub(crate) fn save_remote_globally(project_remote: Option<String>) {
    let Some(dest) = project_remote.filter(|d| !d.is_empty()) else {
        return;
    };
    let mut global = config::GlobalSettings::load().unwrap_or_default();
    global.headroom_remote = Some(dest).filter(|d| d != config::REMOTE_LOCAL);
    match global.save() {
        Ok(()) => ui::warn(
            "no project manifest is written without a memory provider — \
             saved the Headroom location globally instead",
        ),
        Err(e) => ui::warn(&format!("could not save Headroom location: {e:#}")),
    }
}

fn maybe_self_update(
    full: bool,
    headroom_extras: &str,
    remote_arg: &RemoteArg,
) {
    if std::env::var("WHETSTONE_SETUP_UPDATED").is_ok() {
        return;
    }

    let remote = match update::fetch_remote_version() {
        Ok(v) => v,
        Err(_) => return,
    };

    if let Ok(ui::ComponentStatus::Updated(from, to)) =
        update::self_update(&remote)
    {
        ui::ok(&format!(
            "updated whetstone {from} → {to}, restarting setup…"
        ));
        re_exec_setup(full, headroom_extras, remote_arg);
    }
}

fn re_exec_setup(full: bool, headroom_extras: &str, remote: &RemoteArg) -> ! {
    let exe = std::env::current_exe().expect("current exe path");
    let mut cmd = std::process::Command::new(&exe);
    cmd.arg("setup");
    if full {
        cmd.arg("--full");
    }
    cmd.args(["--headroom-extras", headroom_extras]);
    if let Some(dest) = &remote.dest {
        cmd.args(["--headroom-remote", dest]);
        if remote.install {
            cmd.arg("--remote-install");
        }
    }
    cmd.env("WHETSTONE_SETUP_UPDATED", "1");

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let err = cmd.exec();
        ui::fail(&format!("failed to restart setup: {err}"));
    }

    #[cfg(not(unix))]
    {
        match cmd.status() {
            Ok(status) => std::process::exit(status.code().unwrap_or(1)),
            Err(e) => ui::fail(&format!("failed to restart setup: {e}")),
        }
    }
}

fn run_sequential(
    full: bool,
    headroom_extras: &str,
    migrated: bool,
    remote: &RemoteArg,
) -> Result<()> {
    ui::info("whetstone setup");

    let assets = resolve_assets_dir()?;
    ui::ok(&format!("assets at {}", assets.display()));

    ui::info("checking dependencies");
    preflight::check_all()?;

    ui::info("step 1/7 — headroom");
    headroom::install(headroom_extras, full)?;
    let project_remote =
        configure_headroom_location(remote, headroom_extras, full)?;

    ui::info("step 2/7 — rtk");
    rtk::install(full)?;

    ui::info("step 3/7 — shell profile");
    shell::set_anthropic_base_url(DEFAULT_PROXY)?;
    shell::ensure_path_contains_local_bin()?;

    ui::info("step 4/7 — install whetstone binary");
    self_install()?;

    let provider = if migrated {
        ui::info("step 5/7 — memory provider (configured during migration)");
        detect_installed_provider()?
    } else {
        prompt_memory_provider(full)?
    };

    if provider != MemoryProvider::Skip {
        complete_setup(provider, &assets, full, project_remote)?;
    } else {
        save_remote_globally(project_remote);
        ui::info("skipped memory provider, skills, integrations, manifest");
    }

    ui::ok("whetstone setup complete");
    Ok(())
}

/// Shared finishing sequence used by both the headless `setup::run` path and
/// the interactive `wizard::run` path. Assumes binaries (headroom, rtk,
/// whetstone) are already installed.
pub(crate) fn complete_setup(
    provider: MemoryProvider,
    assets: &Path,
    full: bool,
    project_remote: Option<String>,
) -> Result<()> {
    install_general_assets(assets, full)?;
    install_provider_binary(provider)?;
    integrations::run_all(provider)?;
    // Before doctor, so its remote checks see the location just chosen.
    write_manifest(provider, project_remote)?;
    let _report = doctor::run()?;
    generate_stack_setup(provider)?;
    Ok(())
}

pub(crate) fn prompt_memory_provider(full: bool) -> Result<MemoryProvider> {
    let project_dir = std::env::current_dir()?;
    let has_existing = project_dir.join(".claude/whetstone.json").exists()
        || project_dir.join(".claude/commands").is_dir()
        || project_dir.join(".claude/skills").is_dir()
        || project_dir.join(".claude/MEMSTACK.md").exists();

    if full {
        if has_existing {
            ui::info("full update: refreshing existing install");
            return detect_installed_provider();
        }
        ui::info("full update: no existing install found — skipping");
        return Ok(MemoryProvider::Skip);
    }

    let choices = MemoryProvider::CHOICES;
    let idx = ui::select("Choose a memory provider:", &choices, 0);
    Ok(choices[idx])
}

pub(crate) fn detect_installed_provider() -> Result<MemoryProvider> {
    // Prefer the v3 manifest if present.
    let project_dir = std::env::current_dir()?;
    let manifest_path = WhetstoneManifest::path_for(&project_dir);
    if let Some(manifest) = WhetstoneManifest::load(&manifest_path)? {
        return Ok(manifest.provider.into());
    }

    // No manifest yet: default to ICM.
    Ok(MemoryProvider::Icm)
}

pub(crate) fn install_general_assets(assets: &Path, full: bool) -> Result<()> {
    let project_dir = std::env::current_dir()?;
    let claude_dir = project_dir.join(".claude");

    copy_subdirs(assets, &claude_dir, full)?;

    Ok(())
}

/// Force-refresh the project's slash commands from bundled assets.
///
/// Used by `whetstone update` (Phase 4.1) when the project's recorded
/// integration-version is behind the binary's bundled
/// [`crate::config::INTEGRATION_VERSION`].
pub(crate) fn refresh_managed_subdirs(assets: &Path) -> Result<()> {
    let project_dir = std::env::current_dir()?;
    let claude_dir = project_dir.join(".claude");
    copy_subdirs(assets, &claude_dir, true)
}

/// Force-refresh all bundled project assets.
///
/// Triggered by `whetstone update --full`. v3 only ships slash commands,
/// so this is the same as [`refresh_managed_subdirs`] today.
pub(crate) fn refresh_all_assets(assets: &Path) -> Result<()> {
    refresh_managed_subdirs(assets)
}

/// Expose `icm --version` parsing so callers outside `setup.rs`
/// (e.g. `whetstone update`'s per-project refresh) can update
/// [`crate::config::ToolVersions`] without duplicating the spawn.
pub(crate) fn current_icm_version() -> Option<String> {
    crate::icm::installed_version()
}

/// Install the memory provider's binary only. Integration (init) happens in
/// `integrations::run_all` after this returns.
pub(crate) fn install_provider_binary(provider: MemoryProvider) -> Result<()> {
    match provider {
        MemoryProvider::Icm => crate::icm::install(false),
        MemoryProvider::Skip => Ok(()),
    }
}

/// A fresh manifest that keeps what a rerun of setup must not lose: the
/// project's settings, dismissed models, migration id, and creation time.
fn build_manifest(
    provider: MemoryProvider,
    tools: ToolVersions,
    existing: Option<WhetstoneManifest>,
    project_remote: Option<String>,
) -> WhetstoneManifest {
    let mut manifest = config::WhetstoneManifest::new(provider, tools);
    if let Some(existing) = existing {
        manifest.migration_id = existing.migration_id;
        manifest.settings = existing.settings;
        manifest.dismissed_models = existing.dismissed_models;
        manifest.created_at = existing.created_at;
    }
    if let Some(remote) = project_remote {
        manifest.settings.headroom_remote =
            Some(remote).filter(|r| !r.is_empty());
    }
    manifest
}

fn write_manifest(
    provider: MemoryProvider,
    project_remote: Option<String>,
) -> Result<()> {
    let project_dir = std::env::current_dir()?;
    let manifest_path = WhetstoneManifest::path_for(&project_dir);
    let tools = ToolVersions {
        rtk: rtk::installed_version(),
        icm: crate::icm::installed_version(),
        headroom: headroom::installed_version(),
    };
    let existing = WhetstoneManifest::load(&manifest_path).ok().flatten();
    let manifest = build_manifest(provider, tools, existing, project_remote);

    manifest.save(&manifest_path)?;
    ui::ok(&format!("wrote manifest to {}", manifest_path.display()));
    Ok(())
}

fn copy_subdirs(assets: &Path, claude_dir: &Path, force: bool) -> Result<()> {
    let src = assets.join("commands");
    if !src.is_dir() {
        return Ok(());
    }
    let dest = claude_dir.join("commands");
    if force || !dest.is_dir() {
        copy_dir_recursive(&src, &dest)?;
    }
    Ok(())
}

pub(crate) fn generate_stack_setup(provider: MemoryProvider) -> Result<()> {
    let project_dir = std::env::current_dir()?;
    let dest = project_dir.join("STACK-SETUP.md");
    let content = stack_setup_content(provider);
    fs::write(&dest, content)?;
    ui::ok("generated STACK-SETUP.md");
    Ok(())
}

fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> {
    fs::create_dir_all(dest)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dest_path = dest.join(entry.file_name());
        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dest_path)?;
        } else {
            fs::copy(&src_path, &dest_path)?;
        }
    }
    Ok(())
}

fn stack_setup_content(provider: MemoryProvider) -> String {
    let provider_row = match provider {
        MemoryProvider::Icm => {
            "| ICM | Embedded SQLite memory, zero dependencies | persistent context |"
        }
        MemoryProvider::Skip => "| — | No memory provider installed | — |",
    };

    format!(
        r#"# Whetstone (Claude Code stack)

This project was set up with Whetstone: Headroom, RTK, and {provider} for
token-efficient Claude Code sessions.

## Quick Start

```bash
whetstone              # Start Claude with Headroom proxy
whetstone claude       # Same as above
whetstone doctor       # Inspect ~/.claude/settings.json
```

## Tools

| Tool | Purpose | Savings |
|------|---------|---------|
| Headroom | HTTP proxy compresses context before API | 50-90% |
| RTK | Hook rewrites CLI output before entering context | 60-90% |
{provider_row}

## Configuration

| File | Purpose |
|------|---------|
| `~/.claude/settings.json` | Hook registrations (written by rtk init / icm init) |
| `.claude/whetstone.json` | Project manifest (whetstone, integration, tool versions) |

## Uninstall

Per-project: `whetstone uninstall`
"#,
        provider = provider.name(),
        provider_row = provider_row,
    )
}

pub(crate) fn self_install() -> Result<()> {
    let current_exe = std::env::current_exe()
        .context("could not determine current executable path")?;

    let home =
        dirs::home_dir().context("could not determine home directory")?;
    let bin_dir = home.join(".local").join("bin");
    fs::create_dir_all(&bin_dir)?;

    let dest = bin_dir.join("whetstone");

    if dest.exists() && same_file(&current_exe, &dest) {
        ui::ok("whetstone binary already in place");
        return Ok(());
    }

    if dest.exists() || dest.symlink_metadata().is_ok() {
        fs::remove_file(&dest)
            .with_context(|| format!("removing old {}", dest.display()))?;
    }

    install_link_or_copy(&current_exe, &dest)?;

    Ok(())
}

#[cfg(unix)]
fn install_link_or_copy(
    src: &std::path::Path,
    dest: &std::path::Path,
) -> Result<()> {
    std::os::unix::fs::symlink(src, dest).with_context(|| {
        format!("symlinking {} → {}", dest.display(), src.display())
    })?;
    ui::ok(&format!("symlinked to {}", dest.display()));
    Ok(())
}

#[cfg(not(unix))]
fn install_link_or_copy(
    src: &std::path::Path,
    dest: &std::path::Path,
) -> Result<()> {
    fs::copy(src, dest)
        .with_context(|| format!("copying binary to {}", dest.display()))?;
    ui::ok(&format!("installed to {}", dest.display()));
    Ok(())
}

fn same_file(a: &PathBuf, b: &PathBuf) -> bool {
    let Ok(a_canon) = fs::canonicalize(a) else {
        return false;
    };
    let Ok(b_canon) = fs::canonicalize(b) else {
        return false;
    };
    a_canon == b_canon
}

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

    #[test]
    fn rerunning_setup_keeps_project_settings() {
        let mut existing = WhetstoneManifest::new(
            MemoryProvider::Icm,
            ToolVersions::default(),
        );
        existing.settings.api_model = Some("claude-opus-5-5".into());
        existing.settings.headroom_remote = Some("me@box".into());
        existing.dismissed_models.push("claude-opus-5".into());
        existing.set_migration_id("20260607-153012");
        let created = existing.created_at;

        let rebuilt = build_manifest(
            MemoryProvider::Icm,
            ToolVersions::default(),
            Some(existing),
            None,
        );

        assert_eq!(
            rebuilt.settings.api_model.as_deref(),
            Some("claude-opus-5-5")
        );
        assert_eq!(rebuilt.settings.headroom_remote.as_deref(), Some("me@box"));
        assert_eq!(rebuilt.dismissed_models, vec!["claude-opus-5".to_string()]);
        assert_eq!(rebuilt.migration_id(), Some("20260607-153012"));
        assert_eq!(rebuilt.created_at, created);
    }

    #[test]
    fn choosing_this_machine_overrides_clears_or_does_nothing() {
        assert_eq!(local_choice(true, false).as_deref(), Some("local"));
        assert_eq!(local_choice(true, true).as_deref(), Some("local"));
        assert_eq!(local_choice(false, true).as_deref(), Some(""));
        assert_eq!(local_choice(false, false), None);
    }

    #[test]
    fn chosen_location_is_set_overridden_or_cleared() {
        let build = |existing: Option<&str>, chosen: Option<&str>| {
            let mut m = WhetstoneManifest::new(
                MemoryProvider::Icm,
                ToolVersions::default(),
            );
            m.settings.headroom_remote = existing.map(str::to_string);
            build_manifest(
                MemoryProvider::Icm,
                ToolVersions::default(),
                Some(m),
                chosen.map(str::to_string),
            )
            .settings
            .headroom_remote
        };
        assert_eq!(build(None, Some("me@box")).as_deref(), Some("me@box"));
        assert_eq!(build(Some("old"), Some("local")).as_deref(), Some("local"));
        assert_eq!(build(Some("old"), Some("")), None);
        assert_eq!(build(Some("old"), None).as_deref(), Some("old"));
    }
}