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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//! Versioned per-project manifest, written to `.claude/whetstone.json`.
//!
//! Replaces v2's `config.local.json` (which mixed project-list metadata,
//! per-author state, and headroom config). v3's manifest is intentionally
//! minimal: just enough state for `whetstone doctor`, `whetstone update`, and
//! Phase 3's migration layer to know what's installed and when it last ran.
//!
//! Phase 1 task 1.5.

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::memory::MemoryProvider;

/// Bump this whenever the manifest schema gains/changes a required field.
/// `whetstone update` uses it to decide when to rewrite the manifest in place.
pub const SCHEMA_VERSION: u32 = 2;

/// Bump this whenever whetstone's *integration contract* changes — e.g. the
/// expected hook layout shifts because we now delegate to a tool's init that
/// emits a different shape. Phase 3 migration consults this to decide whether
/// a fresh `whetstone setup` is needed.
pub const INTEGRATION_VERSION: u32 = 1;

const MANIFEST_FILENAME: &str = "whetstone.json";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProviderTag {
    Icm,
    Skip,
}

impl From<MemoryProvider> for ProviderTag {
    fn from(p: MemoryProvider) -> Self {
        match p {
            MemoryProvider::Icm => Self::Icm,
            MemoryProvider::Skip => Self::Skip,
        }
    }
}

impl From<ProviderTag> for MemoryProvider {
    fn from(t: ProviderTag) -> Self {
        match t {
            ProviderTag::Icm => Self::Icm,
            ProviderTag::Skip => Self::Skip,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolVersions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rtk: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icm: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom: Option<String>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_telemetry: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_memory: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anthropic_api_url: Option<String>,
    /// Claude Code edit/permission mode passed as `--permission-mode` when set
    /// (see [`PERMISSION_MODES`]). `None` means whetstone injects no flag and
    /// Claude Code uses its own default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    /// Headroom savings profile exported as `HEADROOM_SAVINGS_PROFILE` when set
    /// (see [`SAVINGS_PROFILES`]). `None` means whetstone exports nothing and
    /// Headroom uses its own default (`agent-90`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub savings_profile: Option<String>,
    /// When on, whetstone exports `ENABLE_TOOL_SEARCH=1` so Claude Code turns on
    /// deferred-tool search. `None` means whetstone exports nothing and any
    /// externally-set `ENABLE_TOOL_SEARCH` passes through untouched.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enable_tool_search: Option<bool>,
    /// SSH destination of a machine that runs the Headroom proxy for this
    /// scope (`user@host`, an ssh-config alias, or `ssh://user@host:port`).
    /// A project value of `local` overrides a global remote back to local.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_remote: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headroom_env: BTreeMap<String, String>,
}

/// Valid Claude Code `--permission-mode` values, most-permissive-first for the
/// settings TUI's cycle order (the first entry is the value a freshly-enabled
/// setting seeds).
pub const PERMISSION_MODES: [&str; 4] =
    ["acceptEdits", "default", "plan", "bypassPermissions"];

/// Selectable Headroom savings profiles for the settings TUI's cycle order.
/// The TUI's leading "Off" slot is the "None" option (no override; Headroom
/// falls back to its own default, `agent-90`).
pub const SAVINGS_PROFILES: [&str; 4] =
    ["coding", "agent-90", "balanced", "general"];

/// Project-level `headroom_remote` value that forces a local proxy even when
/// the global setting names a remote host.
pub const REMOTE_LOCAL: &str = "local";

const GLOBAL_DIR: &str = ".whetstone";
const GLOBAL_SETTINGS_FILENAME: &str = "settings.json";

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GlobalSettings {
    #[serde(default)]
    pub headroom_telemetry: bool,
    #[serde(default)]
    pub headroom_memory: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anthropic_api_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub savings_profile: Option<String>,
    #[serde(default)]
    pub enable_tool_search: bool,
    /// SSH destination of a machine that runs the Headroom proxy for this
    /// scope (`user@host`, an ssh-config alias, or `ssh://user@host:port`).
    /// A project value of `local` overrides a global remote back to local.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headroom_remote: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub headroom_env: BTreeMap<String, String>,
}

/// Write a file so readers only ever see the old or the new contents: a
/// plain `fs::write` truncates first, and a launch reading in that instant
/// would silently fall back to default settings.
pub fn write_atomic(path: &Path, contents: &str) -> Result<()> {
    let mut tmp = path.as_os_str().to_owned();
    tmp.push(".tmp");
    fs::write(&tmp, contents)
        .and_then(|()| fs::rename(&tmp, path))
        .with_context(|| format!("writing {}", path.display()))
}

impl GlobalSettings {
    pub fn path() -> Option<PathBuf> {
        dirs::home_dir()
            .map(|h| h.join(GLOBAL_DIR).join(GLOBAL_SETTINGS_FILENAME))
    }

    pub fn load() -> Result<Self> {
        let Some(path) = Self::path() else {
            return Ok(Self::default());
        };
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        serde_json::from_str(&raw)
            .with_context(|| format!("parsing {}", path.display()))
    }

    pub fn save(&self) -> Result<()> {
        let path =
            Self::path().context("could not determine home directory")?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        let pretty = serde_json::to_string_pretty(self)
            .context("serializing global settings")?;
        write_atomic(&path, &pretty)
    }
}

/// Which settings layer supplied a value, so a message can tell the user
/// which file to change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PinScope {
    /// `.claude/whetstone.json` in the current project.
    Project,
    /// `~/.whetstone/settings.json`.
    Global,
}

impl PinScope {
    /// Human-facing description of where the value lives.
    pub fn label(self) -> &'static str {
        match self {
            Self::Project => "project .claude/whetstone.json",
            Self::Global => "global ~/.whetstone/settings.json",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedSettings {
    pub headroom_telemetry: bool,
    pub headroom_memory: bool,
    pub api_model: Option<String>,
    /// Which layer `api_model` came from; `None` when nothing is pinned.
    pub api_model_scope: Option<PinScope>,
    pub anthropic_api_url: Option<String>,
    pub permission_mode: Option<String>,
    pub savings_profile: Option<String>,
    pub enable_tool_search: bool,
    /// SSH destination of the remote Headroom host; `None` means local.
    pub headroom_remote: Option<String>,
    pub headroom_env: BTreeMap<String, String>,
}

impl ResolvedSettings {
    pub fn resolve(global: &GlobalSettings, project: &ProjectSettings) -> Self {
        let mut headroom_env = global.headroom_env.clone();
        headroom_env.extend(project.headroom_env.clone());

        Self {
            headroom_telemetry: project
                .headroom_telemetry
                .unwrap_or(global.headroom_telemetry),
            headroom_memory: project
                .headroom_memory
                .unwrap_or(global.headroom_memory),
            api_model: project
                .api_model
                .clone()
                .or_else(|| global.api_model.clone()),
            api_model_scope: match (&project.api_model, &global.api_model) {
                (Some(_), _) => Some(PinScope::Project),
                (None, Some(_)) => Some(PinScope::Global),
                (None, None) => None,
            },
            anthropic_api_url: project
                .anthropic_api_url
                .clone()
                .or_else(|| global.anthropic_api_url.clone()),
            permission_mode: project
                .permission_mode
                .clone()
                .or_else(|| global.permission_mode.clone()),
            savings_profile: project
                .savings_profile
                .clone()
                .or_else(|| global.savings_profile.clone()),
            enable_tool_search: project
                .enable_tool_search
                .unwrap_or(global.enable_tool_search),
            headroom_remote: project
                .headroom_remote
                .clone()
                .or_else(|| global.headroom_remote.clone())
                .map(|d| d.trim().to_string())
                .filter(|d| !d.is_empty() && d != REMOTE_LOCAL),
            headroom_env,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WhetstoneManifest {
    pub schema: u32,
    pub whetstone_version: String,
    pub integration_version: u32,
    pub provider: ProviderTag,
    #[serde(default)]
    pub tool_versions: ToolVersions,
    #[serde(default)]
    pub settings: ProjectSettings,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub migration_id: Option<String>,
    /// Model ids the user chose to permanently dismiss from the launch-time
    /// update prompt. Bookkeeping, not a settings-TUI knob — hence top-level.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dismissed_models: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl WhetstoneManifest {
    /// Fresh manifest stamped for a brand-new `whetstone setup` run.
    pub fn new(provider: MemoryProvider, tool_versions: ToolVersions) -> Self {
        let now = Utc::now();
        Self {
            schema: SCHEMA_VERSION,
            whetstone_version: crate::version::current().to_string(),
            integration_version: INTEGRATION_VERSION,
            provider: provider.into(),
            tool_versions,
            settings: ProjectSettings::default(),
            migration_id: None,
            dismissed_models: Vec::new(),
            created_at: now,
            updated_at: now,
        }
    }

    /// Conventional path: `<project>/.claude/whetstone.json`.
    pub fn path_for(project_dir: &Path) -> PathBuf {
        project_dir.join(".claude").join(MANIFEST_FILENAME)
    }

    /// Load the manifest if it exists. Returns `Ok(None)` for "no manifest
    /// yet" (fresh project), and a real error for a malformed file.
    pub fn load(path: &Path) -> Result<Option<Self>> {
        if !path.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(path)
            .with_context(|| format!("reading {}", path.display()))?;
        let parsed: Self = serde_json::from_str(&raw).with_context(|| {
            format!("parsing manifest at {}", path.display())
        })?;
        Ok(Some(parsed))
    }

    /// Serialize, ensure the parent dir exists, write atomically.
    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        let pretty = serde_json::to_string_pretty(self)
            .context("serializing whetstone.json")?;
        write_atomic(path, &pretty)
    }

    /// Refresh `updated_at` and persist the change.
    pub fn touch_and_save(&mut self, path: &Path) -> Result<()> {
        self.updated_at = Utc::now();
        self.save(path)
    }

    /// Migration id stamped by `whetstone migrate` (Phase 3.6).
    pub fn migration_id(&self) -> Option<&str> {
        self.migration_id.as_deref()
    }

    /// Set the migration id (called by `whetstone migrate` after re-init).
    pub fn set_migration_id(&mut self, id: &str) {
        self.migration_id = Some(id.to_string());
    }

    /// Clear the migration id (called by `--rollback`).
    pub fn clear_migration_id(&mut self) {
        self.migration_id = None;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn resolve_prefers_project_anthropic_api_url() {
        let global = GlobalSettings {
            anthropic_api_url: Some("https://global.example".into()),
            ..Default::default()
        };
        let project = ProjectSettings {
            anthropic_api_url: Some("https://project.example".into()),
            ..Default::default()
        };
        let resolved = ResolvedSettings::resolve(&global, &project);
        assert_eq!(
            resolved.anthropic_api_url.as_deref(),
            Some("https://project.example")
        );
    }

    #[test]
    fn resolve_falls_back_to_global_anthropic_api_url() {
        let global = GlobalSettings {
            anthropic_api_url: Some("https://global.example".into()),
            ..Default::default()
        };
        let resolved =
            ResolvedSettings::resolve(&global, &ProjectSettings::default());
        assert_eq!(
            resolved.anthropic_api_url.as_deref(),
            Some("https://global.example")
        );
    }

    #[test]
    fn resolve_anthropic_api_url_none_when_unset() {
        let resolved = ResolvedSettings::resolve(
            &GlobalSettings::default(),
            &ProjectSettings::default(),
        );
        assert!(resolved.anthropic_api_url.is_none());
    }

    #[test]
    fn resolve_prefers_project_permission_mode() {
        let global = GlobalSettings {
            permission_mode: Some("plan".into()),
            ..Default::default()
        };
        let project = ProjectSettings {
            permission_mode: Some("acceptEdits".into()),
            ..Default::default()
        };
        let resolved = ResolvedSettings::resolve(&global, &project);
        assert_eq!(resolved.permission_mode.as_deref(), Some("acceptEdits"));
    }

    #[test]
    fn resolve_falls_back_to_global_permission_mode() {
        let global = GlobalSettings {
            permission_mode: Some("bypassPermissions".into()),
            ..Default::default()
        };
        let resolved =
            ResolvedSettings::resolve(&global, &ProjectSettings::default());
        assert_eq!(
            resolved.permission_mode.as_deref(),
            Some("bypassPermissions")
        );
    }

    #[test]
    fn resolve_permission_mode_none_when_unset() {
        let resolved = ResolvedSettings::resolve(
            &GlobalSettings::default(),
            &ProjectSettings::default(),
        );
        assert!(resolved.permission_mode.is_none());
    }

    #[test]
    fn empty_permission_mode_omitted_from_project_json() {
        let s = ProjectSettings::default();
        let raw = serde_json::to_string(&s).unwrap();
        assert!(!raw.contains("permission_mode"));
    }

    #[test]
    fn resolve_prefers_project_savings_profile() {
        let global = GlobalSettings {
            savings_profile: Some("balanced".into()),
            ..Default::default()
        };
        let project = ProjectSettings {
            savings_profile: Some("coding".into()),
            ..Default::default()
        };
        let resolved = ResolvedSettings::resolve(&global, &project);
        assert_eq!(resolved.savings_profile.as_deref(), Some("coding"));
    }

    #[test]
    fn resolve_falls_back_to_global_savings_profile() {
        let global = GlobalSettings {
            savings_profile: Some("general".into()),
            ..Default::default()
        };
        let resolved =
            ResolvedSettings::resolve(&global, &ProjectSettings::default());
        assert_eq!(resolved.savings_profile.as_deref(), Some("general"));
    }

    #[test]
    fn resolve_savings_profile_none_when_unset() {
        let resolved = ResolvedSettings::resolve(
            &GlobalSettings::default(),
            &ProjectSettings::default(),
        );
        assert!(resolved.savings_profile.is_none());
    }

    #[test]
    fn empty_savings_profile_omitted_from_project_json() {
        let s = ProjectSettings::default();
        let raw = serde_json::to_string(&s).unwrap();
        assert!(!raw.contains("savings_profile"));
    }

    #[test]
    fn resolve_prefers_project_enable_tool_search() {
        let global = GlobalSettings {
            enable_tool_search: false,
            ..Default::default()
        };
        let project = ProjectSettings {
            enable_tool_search: Some(true),
            ..Default::default()
        };
        let resolved = ResolvedSettings::resolve(&global, &project);
        assert!(resolved.enable_tool_search);
    }

    #[test]
    fn resolve_falls_back_to_global_enable_tool_search() {
        let global = GlobalSettings {
            enable_tool_search: true,
            ..Default::default()
        };
        let resolved =
            ResolvedSettings::resolve(&global, &ProjectSettings::default());
        assert!(resolved.enable_tool_search);
    }

    #[test]
    fn resolve_enable_tool_search_off_when_unset() {
        let resolved = ResolvedSettings::resolve(
            &GlobalSettings::default(),
            &ProjectSettings::default(),
        );
        assert!(!resolved.enable_tool_search);
    }

    #[test]
    fn resolve_project_false_overrides_global_enable_tool_search() {
        let global = GlobalSettings {
            enable_tool_search: true,
            ..Default::default()
        };
        let project = ProjectSettings {
            enable_tool_search: Some(false),
            ..Default::default()
        };
        let resolved = ResolvedSettings::resolve(&global, &project);
        assert!(!resolved.enable_tool_search);
    }

    #[test]
    fn empty_enable_tool_search_omitted_from_project_json() {
        let s = ProjectSettings::default();
        let raw = serde_json::to_string(&s).unwrap();
        assert!(!raw.contains("enable_tool_search"));
    }

    #[test]
    fn resolve_headroom_remote_project_over_global_and_local_override() {
        let global = GlobalSettings {
            headroom_remote: Some("me@big-box".into()),
            ..Default::default()
        };
        let resolve = |project: Option<&str>| {
            ResolvedSettings::resolve(
                &global,
                &ProjectSettings {
                    headroom_remote: project.map(str::to_string),
                    ..Default::default()
                },
            )
            .headroom_remote
        };
        assert_eq!(resolve(None).as_deref(), Some("me@big-box"));
        assert_eq!(resolve(Some("other")).as_deref(), Some("other"));
        assert_eq!(resolve(Some("local")), None);
        assert_eq!(
            ResolvedSettings::resolve(
                &GlobalSettings::default(),
                &ProjectSettings::default()
            )
            .headroom_remote,
            None
        );
    }

    #[test]
    fn provider_round_trip() {
        let icm: ProviderTag = MemoryProvider::Icm.into();
        assert_eq!(MemoryProvider::from(icm), MemoryProvider::Icm);
        let skip: ProviderTag = MemoryProvider::Skip.into();
        assert_eq!(MemoryProvider::from(skip), MemoryProvider::Skip);
    }

    #[test]
    fn provider_serializes_snake_case() {
        let tag = ProviderTag::Icm;
        let s = serde_json::to_string(&tag).unwrap();
        assert_eq!(s, "\"icm\"");
    }

    #[test]
    fn new_manifest_has_current_schema_and_integration_version() {
        let m = WhetstoneManifest::new(
            MemoryProvider::Icm,
            ToolVersions::default(),
        );
        assert_eq!(m.schema, SCHEMA_VERSION);
        assert_eq!(m.integration_version, INTEGRATION_VERSION);
        assert_eq!(m.provider, ProviderTag::Icm);
        assert!(m.migration_id.is_none());
    }

    #[test]
    fn save_and_load_round_trip() {
        let m = WhetstoneManifest::new(
            MemoryProvider::Icm,
            ToolVersions {
                rtk: Some("0.42.3".into()),
                icm: Some("0.10.43".into()),
                headroom: Some("0.23.0".into()),
            },
        );
        let f = NamedTempFile::new().unwrap();
        m.save(f.path()).unwrap();
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert_eq!(loaded.provider, m.provider);
        assert_eq!(loaded.tool_versions.rtk.as_deref(), Some("0.42.3"));
    }

    #[test]
    fn load_returns_none_when_file_missing() {
        let path = Path::new("/nonexistent-whetstone-test/whetstone.json");
        assert!(WhetstoneManifest::load(path).unwrap().is_none());
    }

    #[test]
    fn load_errors_on_malformed_json() {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(b"not json").unwrap();
        assert!(WhetstoneManifest::load(f.path()).is_err());
    }

    #[test]
    fn path_for_uses_dot_claude() {
        let p = WhetstoneManifest::path_for(Path::new("/tmp/proj"));
        assert!(p.ends_with(".claude/whetstone.json"));
    }

    #[test]
    fn manifest_round_trips_dismissed_models() {
        let mut m = WhetstoneManifest::new(
            MemoryProvider::Icm,
            ToolVersions::default(),
        );
        m.dismissed_models.push("claude-opus-4-8".into());
        m.dismissed_models.push("claude-fable-5".into());
        let f = NamedTempFile::new().unwrap();
        m.save(f.path()).unwrap();
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert_eq!(
            loaded.dismissed_models,
            vec!["claude-opus-4-8".to_string(), "claude-fable-5".to_string()]
        );
    }

    #[test]
    fn legacy_manifest_without_dismissed_models_parses() {
        let m = WhetstoneManifest::new(
            MemoryProvider::Skip,
            ToolVersions::default(),
        );
        let mut value = serde_json::to_value(&m).unwrap();
        value.as_object_mut().unwrap().remove("dismissed_models");
        let raw = serde_json::to_string(&value).unwrap();
        let parsed: WhetstoneManifest = serde_json::from_str(&raw).unwrap();
        assert!(parsed.dismissed_models.is_empty());
    }

    #[test]
    fn empty_dismissed_models_omitted_from_json() {
        let m = WhetstoneManifest::new(
            MemoryProvider::Skip,
            ToolVersions::default(),
        );
        let raw = serde_json::to_string(&m).unwrap();
        assert!(!raw.contains("dismissed_models"));
    }

    #[test]
    fn touch_and_save_bumps_updated_at() {
        let mut m = WhetstoneManifest::new(
            MemoryProvider::Skip,
            ToolVersions::default(),
        );
        let original = m.updated_at;
        let f = NamedTempFile::new().unwrap();
        // Sleep enough to guarantee a chrono-detectable bump on fast machines.
        std::thread::sleep(std::time::Duration::from_millis(10));
        m.touch_and_save(f.path()).unwrap();
        assert!(m.updated_at > original);
    }

    #[test]
    fn resolve_merges_headroom_env_project_over_global() {
        let mut global = GlobalSettings::default();
        global
            .headroom_env
            .insert("HEADROOM_RPM".into(), "60".into());
        global
            .headroom_env
            .insert("HEADROOM_TPM".into(), "1000".into());
        let mut project = ProjectSettings::default();
        project
            .headroom_env
            .insert("HEADROOM_RPM".into(), "120".into());

        let resolved = ResolvedSettings::resolve(&global, &project);

        // project wins on the shared key, global-only key survives
        assert_eq!(
            resolved
                .headroom_env
                .get("HEADROOM_RPM")
                .map(String::as_str),
            Some("120")
        );
        assert_eq!(
            resolved
                .headroom_env
                .get("HEADROOM_TPM")
                .map(String::as_str),
            Some("1000")
        );
    }

    #[test]
    fn empty_headroom_env_omitted_from_project_json() {
        let s = ProjectSettings::default();
        let raw = serde_json::to_string(&s).unwrap();
        assert!(!raw.contains("headroom_env"));
    }
}