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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Launch-time model update prompt.
//!
//! On the default `headroom wrap claude` launch, whetstone notices that
//! Anthropic has published a model newer than the one this project runs — or a
//! brand-new model family — and offers, via a full-screen modal, to pin it as
//! the project default, use it for one session, or dismiss it permanently.
//!
//! The decision logic here is pure and exhaustively unit-tested; the effectful
//! shell (guards, state I/O, TUI) lives alongside it but is kept thin.

use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::{DefaultTerminal, Frame};

use crate::config::{PinScope, ResolvedSettings, WhetstoneManifest};
use crate::settings::family_order;

/// `family_order` value assigned to models we don't recognize; never matches.
const UNKNOWN_FAMILY: u8 = 4;

/// What the caller does with the model list after the prompt resolves.
#[derive(Debug, PartialEq, Eq)]
pub enum ModelDecision {
    /// Pin as project default and launch with it.
    UsePinned(String),
    /// Launch with it once; nothing persisted.
    UseSession(String),
    /// Leave resolution to the existing default path.
    NoChange,
}

/// The action a user picks in the modal, orthogonal to which model is
/// highlighted (that id is supplied separately to [`apply_action`]).
#[derive(Debug, PartialEq, Eq)]
pub enum ModalAction {
    /// Pin the highlighted model as the project default.
    Pin,
    /// Use the highlighted model for this session only.
    Session,
    /// Never offer the highlighted model again.
    Dismiss,
    /// Do nothing; ask again next launch.
    NotNow,
}

/// Two ids belong to the same recognized model family.
fn same_family(a: &str, b: &str) -> bool {
    let fa = family_order(a);
    fa != UNKNOWN_FAMILY && fa == family_order(b)
}

/// `candidate` is a newer release of `current`'s own family.
fn is_model_newer(candidate: &str, current: &str) -> bool {
    same_family(candidate, current) && candidate > current
}

/// Newest id in `available` that shares `model`'s family (lexical max).
fn newest_in_family(available: &[String], model: &str) -> Option<String> {
    available
        .iter()
        .filter(|id| same_family(id, model))
        .max()
        .cloned()
}

/// Models worth offering, per the trigger rule in the design doc:
/// a newer release within `effective`'s own family, plus the flagship of any
/// recognized family present in `available` but absent from `seen`. `effective`
/// and `dismissed` ids are removed and the result is deduped in stable order.
/// On first run (`seen` empty) the brand-new-family signal is suppressed.
fn model_offers(
    effective: &str,
    available: &[String],
    seen: &[String],
    dismissed: &[String],
) -> Vec<String> {
    let mut offers: Vec<String> = Vec::new();

    // Signal: a newer release within the in-use family.
    if let Some(newest) = newest_in_family(available, effective) {
        if is_model_newer(&newest, effective) {
            offers.push(newest);
        }
    }

    // Signal: a brand-new family flagship (only after seeding).
    if !seen.is_empty() {
        let seen_families: HashSet<u8> =
            seen.iter().map(|id| family_order(id)).collect();
        let mut new_families: Vec<u8> = available
            .iter()
            .map(|id| family_order(id))
            .filter(|f| *f != UNKNOWN_FAMILY && !seen_families.contains(f))
            .collect();
        new_families.sort_unstable();
        new_families.dedup();
        for f in new_families {
            if let Some(flagship) =
                available.iter().filter(|id| family_order(id) == f).max()
            {
                offers.push(flagship.clone());
            }
        }
    }

    let mut deduped = HashSet::new();
    offers
        .into_iter()
        .filter(|m| m != effective && !dismissed.contains(m))
        .filter(|m| deduped.insert(m.clone()))
        .collect()
}

/// Base model id with any trailing date snapshot removed, so
/// `claude-opus-4-8-20260501` and `claude-opus-4-8` compare equal.
fn base_model_id(id: &str) -> &str {
    crate::settings::strip_date_suffix(id).unwrap_or(id)
}

/// What a startup notice should say about a pinned model.
#[derive(Debug, PartialEq, Eq)]
pub enum PinStatus {
    /// The models list does not carry this id at all — retired, renamed, or a
    /// typo. Carries the newest release of its family when there is one to
    /// move to. Only ever concluded from a *live* list.
    Unsupported { replacement: Option<String> },
    /// Still listed, but a newer release of its own family exists.
    Superseded { newer: String },
    /// Nothing worth saying.
    Current,
}

/// Classify a pinned model against the available roster. `live` says whether
/// that roster came from the models API: absence only means "retired" when the
/// list is authoritative, because the static `FALLBACK_MODELS` floor holds the
/// current generation only and a valid older pin is missing from it by design.
fn pin_status(pinned: &str, available: &[String], live: bool) -> PinStatus {
    // A dated snapshot of the pin itself (`claude-opus-4-8-20260501` against
    // `claude-opus-4-8`) sorts higher but is the same model, so compare base
    // ids before calling anything an upgrade.
    let newer = newest_in_family(available, pinned).filter(|newest| {
        base_model_id(newest) != base_model_id(pinned)
            && is_model_newer(newest, pinned)
    });

    let listed = available
        .iter()
        .any(|id| base_model_id(id) == base_model_id(pinned));
    if live && !listed {
        return PinStatus::Unsupported { replacement: newer };
    }

    match newer {
        Some(newer) => PinStatus::Superseded { newer },
        None => PinStatus::Current,
    }
}

/// One-line warning text for a stale pin. Always names the model, the file it
/// came from, and where to change it.
fn pin_notice(pinned: &str, scope: PinScope, status: &PinStatus) -> String {
    let fix = "change it with `whetstone settings` (API Model)";
    match status {
        PinStatus::Unsupported { replacement } => {
            let suggestion = match replacement {
                Some(newer) => format!("newest in its family is {newer}"),
                // Unknown or retired family — point at the launch default
                // rather than inventing a successor.
                None => format!(
                    "whetstone's default is {}",
                    crate::wrapper::DEFAULT_MODEL
                ),
            };
            format!(
                "Pinned model {pinned} ({}) is no longer in Anthropic's \
                 models list — {suggestion}; {fix}.",
                scope.label()
            )
        }
        PinStatus::Superseded { newer } => format!(
            "Pinned model {pinned} ({}) has been superseded by {newer}; {fix}.",
            scope.label()
        ),
        // Callers filter this out; render something harmless rather than
        // panicking if one ever doesn't.
        PinStatus::Current => format!("Pinned model {pinned} is current."),
    }
}

/// Warn at launch when the model about to run came from a pin that the models
/// list has retired or superseded.
///
/// Silent unless the launching model *is* the pin: an explicit `--model`, an
/// unpinned project (the resolved default is current by construction), and a
/// model the update modal just swapped in all have nothing to report.
pub fn notify_pinned_model(
    launching: &str,
    pinned: Option<&str>,
    scope: Option<PinScope>,
    user_set: bool,
) {
    if user_set || pinned != Some(launching) {
        return;
    }
    let Some(scope) = scope else {
        return;
    };
    let (available, live) = crate::settings::available_models_for_prompt();
    let status = pin_status(launching, &available, live);
    if status != PinStatus::Current {
        crate::ui::warn(&pin_notice(launching, scope, &status));
    }
}

/// Stable hex hash of a project directory, used to name its seen-cache file.
/// Canonicalizes when possible so `.`/symlinks map to one file; falls back to
/// the raw path (e.g. for a not-yet-existing dir in tests).
fn hash_project_dir(project_dir: &Path) -> String {
    let canon = std::fs::canonicalize(project_dir)
        .unwrap_or_else(|_| project_dir.to_path_buf());
    let mut hasher = DefaultHasher::new();
    canon.to_string_lossy().hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// Path to a project's seen-cache file under an arbitrary cache base.
fn seen_cache_path_in(base: &Path, project_dir: &Path) -> PathBuf {
    base.join("model-seen")
        .join(format!("{}.json", hash_project_dir(project_dir)))
}

/// Real cache base: `~/.cache/whetstone`.
fn seen_cache_base() -> Option<PathBuf> {
    Some(dirs::home_dir()?.join(".cache").join("whetstone"))
}

/// Read the seen baseline under an arbitrary base. Missing or garbage ⇒ `[]`.
fn read_seen_in(base: &Path, project_dir: &Path) -> Vec<String> {
    let path = seen_cache_path_in(base, project_dir);
    let Ok(content) = std::fs::read_to_string(&path) else {
        return Vec::new();
    };
    serde_json::from_str(&content).unwrap_or_default()
}

/// Best-effort write of the seen baseline under an arbitrary base.
fn write_seen_in(base: &Path, project_dir: &Path, models: &[String]) {
    let path = seen_cache_path_in(base, project_dir);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Ok(json) = serde_json::to_string(models) {
        let _ = std::fs::write(path, json);
    }
}

/// Seen baseline for `project_dir` from the real cache; `[]` if unavailable.
fn read_seen(project_dir: &Path) -> Vec<String> {
    match seen_cache_base() {
        Some(base) => read_seen_in(&base, project_dir),
        None => Vec::new(),
    }
}

/// Persist the seen baseline for `project_dir` to the real cache (best-effort).
fn write_seen(project_dir: &Path, models: &[String]) {
    if let Some(base) = seen_cache_base() {
        write_seen_in(&base, project_dir, models);
    }
}

/// The model a launch would use today: the project's pin, else the newest
/// available Opus. `None` only when neither is determinable.
fn effective_model(resolved: &ResolvedSettings) -> Option<String> {
    resolved
        .api_model
        .clone()
        .or_else(crate::settings::preferred_default_model)
}

/// Persist (or not) the user's modal choice and map it to a [`ModelDecision`].
/// `selected` is the highlighted model id the action applies to.
fn apply_action(
    action: ModalAction,
    selected: &str,
    manifest_path: &Path,
) -> Result<ModelDecision> {
    match action {
        ModalAction::Pin => {
            let Some(mut manifest) = WhetstoneManifest::load(manifest_path)?
            else {
                return Ok(ModelDecision::NoChange);
            };
            manifest.settings.api_model = Some(selected.to_string());
            manifest.touch_and_save(manifest_path)?;
            Ok(ModelDecision::UsePinned(selected.to_string()))
        }
        ModalAction::Session => {
            Ok(ModelDecision::UseSession(selected.to_string()))
        }
        ModalAction::Dismiss => {
            let Some(mut manifest) = WhetstoneManifest::load(manifest_path)?
            else {
                return Ok(ModelDecision::NoChange);
            };
            if !manifest.dismissed_models.iter().any(|d| d == selected) {
                manifest.dismissed_models.push(selected.to_string());
                manifest.touch_and_save(manifest_path)?;
            }
            Ok(ModelDecision::NoChange)
        }
        ModalAction::NotNow => Ok(ModelDecision::NoChange),
    }
}

/// Launch-time entry point. Returns [`ModelDecision::NoChange`] on any guard
/// (non-interactive, no cwd, no v3 manifest, offline) so every existing launch
/// path is unaffected. Otherwise computes offers, seeds the seen baseline, and
/// — when there is something to offer — drives the modal and applies the choice.
pub fn maybe_prompt(resolved: &ResolvedSettings) -> ModelDecision {
    if !crate::ui::is_interactive() {
        return ModelDecision::NoChange;
    }
    let Ok(cwd) = std::env::current_dir() else {
        return ModelDecision::NoChange;
    };
    let manifest_path = WhetstoneManifest::path_for(&cwd);
    let Ok(Some(manifest)) = WhetstoneManifest::load(&manifest_path) else {
        return ModelDecision::NoChange;
    };
    // Offline (or credential-less) launches still compare the in-use model
    // against the static current-generation roster, so a pin left behind by an
    // earlier release gets an upgrade offer instead of booting silently.
    let (available, live) = crate::settings::available_models_for_prompt();

    let effective = effective_model(resolved)
        .unwrap_or_else(|| crate::wrapper::DEFAULT_MODEL.to_string());
    let seen = read_seen(&cwd);
    let offers =
        model_offers(&effective, &available, &seen, &manifest.dismissed_models);

    // Record the current list as the new baseline whenever it changed (this is
    // also the first-run seeding that suppresses brand-new-family until
    // later). Only a live list may become the baseline — seeding it from
    // `FALLBACK_MODELS` would mark families as "seen" that the user has never
    // actually been offered.
    if live && seen != available {
        write_seen(&cwd, &available);
    }

    if offers.is_empty() {
        return ModelDecision::NoChange;
    }

    let (action, selected) = prompt_modal(&offers);
    apply_action(action, &selected, &manifest_path)
        .unwrap_or(ModelDecision::NoChange)
}

/// Full-screen modal offering the newer/new model(s). Returns the chosen
/// action and the highlighted model id. Falls back to `NotNow` on any terminal
/// error so a launch never hangs on TUI failure.
fn prompt_modal(offered: &[String]) -> (ModalAction, String) {
    let fallback = || {
        (
            ModalAction::NotNow,
            offered.first().cloned().unwrap_or_default(),
        )
    };
    let mut terminal = ratatui::init();
    let result = modal_loop(&mut terminal, offered);
    ratatui::restore();
    result.unwrap_or_else(|_| fallback())
}

/// Render/input loop for the modal. `Enter`/`p` pin, `s` session, `d` dismiss,
/// `Esc`/`q` not now; `↑↓`/`j`/`k` move the highlight when >1 model is offered.
fn modal_loop(
    terminal: &mut DefaultTerminal,
    offered: &[String],
) -> Result<(ModalAction, String)> {
    let mut selected = 0usize;
    loop {
        terminal.draw(|frame| draw_modal(frame, offered, selected))?;

        if !event::poll(Duration::from_millis(250))? {
            continue;
        }
        let Event::Key(key) = event::read()? else {
            continue;
        };
        if key.kind != KeyEventKind::Press {
            continue;
        }
        let current = offered.get(selected).cloned().unwrap_or_default();
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                selected = selected.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j')
                if selected + 1 < offered.len() =>
            {
                selected += 1;
            }
            KeyCode::Char('p') | KeyCode::Enter => {
                return Ok((ModalAction::Pin, current));
            }
            KeyCode::Char('s') => {
                return Ok((ModalAction::Session, current));
            }
            KeyCode::Char('d') => {
                return Ok((ModalAction::Dismiss, current));
            }
            KeyCode::Char('q') | KeyCode::Esc => {
                return Ok((ModalAction::NotNow, current));
            }
            _ => {}
        }
    }
}

fn draw_modal(frame: &mut Frame, offered: &[String], selected: usize) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(5),
            Constraint::Min(3),
            Constraint::Length(3),
        ])
        .split(frame.area());

    draw_modal_header(frame, chunks[0]);
    draw_modal_list(frame, chunks[1], offered, selected);
    draw_modal_footer(frame, chunks[2]);
}

fn draw_modal_header(frame: &mut Frame, area: Rect) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(Span::styled(
            " New model available ",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ))
        .border_style(Style::default().fg(Color::Cyan));

    let body = Paragraph::new(vec![
        Line::from(""),
        Line::from(Span::styled(
            " Anthropic published a model newer than this project uses.",
            Style::default().add_modifier(Modifier::DIM),
        )),
        Line::from(Span::styled(
            " Pin it as the project default, use it once, or dismiss it.",
            Style::default().add_modifier(Modifier::DIM),
        )),
    ])
    .block(block);
    frame.render_widget(body, area);
}

fn draw_modal_list(
    frame: &mut Frame,
    area: Rect,
    offered: &[String],
    selected: usize,
) {
    let lines: Vec<Line<'_>> = offered
        .iter()
        .enumerate()
        .map(|(i, model)| {
            let marker = if i == selected { " ▶ " } else { "   " };
            let style = if i == selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            Line::from(Span::styled(format!("{marker}{model}"), style))
        })
        .collect();

    let list = Paragraph::new(lines)
        .block(Block::default().borders(Borders::ALL).title(" Offered "));
    frame.render_widget(list, area);
}

fn draw_modal_footer(frame: &mut Frame, area: Rect) {
    let footer = Paragraph::new(Line::from(Span::styled(
        " ↑/↓ select   p pin as default   s this session   \
         d dismiss   Esc not now",
        Style::default().fg(Color::DarkGray),
    )))
    .block(Block::default().borders(Borders::ALL));
    frame.render_widget(footer, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ToolVersions, WhetstoneManifest};
    use crate::memory::MemoryProvider;

    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }

    fn seed_manifest(path: &Path) {
        WhetstoneManifest::new(MemoryProvider::Icm, ToolVersions::default())
            .save(path)
            .unwrap();
    }

    #[test]
    fn apply_pin_writes_api_model_and_returns_use_pinned() {
        let f = tempfile::NamedTempFile::new().unwrap();
        seed_manifest(f.path());
        let decision =
            apply_action(ModalAction::Pin, "claude-opus-4-8", f.path())
                .unwrap();
        assert_eq!(
            decision,
            ModelDecision::UsePinned("claude-opus-4-8".into())
        );
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert_eq!(
            loaded.settings.api_model.as_deref(),
            Some("claude-opus-4-8")
        );
    }

    #[test]
    fn apply_dismiss_appends_to_dismissed_models_and_returns_no_change() {
        let f = tempfile::NamedTempFile::new().unwrap();
        seed_manifest(f.path());
        let decision =
            apply_action(ModalAction::Dismiss, "claude-fable-5", f.path())
                .unwrap();
        assert_eq!(decision, ModelDecision::NoChange);
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert_eq!(loaded.dismissed_models, s(&["claude-fable-5"]));
    }

    #[test]
    fn apply_session_persists_nothing_returns_use_session() {
        let f = tempfile::NamedTempFile::new().unwrap();
        seed_manifest(f.path());
        let decision =
            apply_action(ModalAction::Session, "claude-sonnet-5", f.path())
                .unwrap();
        assert_eq!(
            decision,
            ModelDecision::UseSession("claude-sonnet-5".into())
        );
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert!(loaded.settings.api_model.is_none());
        assert!(loaded.dismissed_models.is_empty());
    }

    #[test]
    fn apply_not_now_persists_nothing_returns_no_change() {
        let f = tempfile::NamedTempFile::new().unwrap();
        seed_manifest(f.path());
        let decision =
            apply_action(ModalAction::NotNow, "claude-sonnet-5", f.path())
                .unwrap();
        assert_eq!(decision, ModelDecision::NoChange);
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert!(loaded.settings.api_model.is_none());
        assert!(loaded.dismissed_models.is_empty());
    }

    #[test]
    fn dismiss_does_not_duplicate_existing_ids() {
        let f = tempfile::NamedTempFile::new().unwrap();
        seed_manifest(f.path());
        apply_action(ModalAction::Dismiss, "claude-fable-5", f.path()).unwrap();
        apply_action(ModalAction::Dismiss, "claude-fable-5", f.path()).unwrap();
        let loaded = WhetstoneManifest::load(f.path()).unwrap().unwrap();
        assert_eq!(loaded.dismissed_models, s(&["claude-fable-5"]));
    }

    #[test]
    fn is_model_newer_within_family() {
        assert!(is_model_newer("claude-sonnet-5", "claude-sonnet-4-6"));
    }

    #[test]
    fn is_model_newer_cross_family_false() {
        assert!(!is_model_newer("claude-opus-4-8", "claude-sonnet-4-6"));
    }

    #[test]
    fn is_model_newer_same_id_false() {
        assert!(!is_model_newer("claude-sonnet-5", "claude-sonnet-5"));
    }

    #[test]
    fn offers_family_upgrade_for_pinned_older_sonnet() {
        let available = s(&["claude-sonnet-5", "claude-sonnet-4-6"]);
        let seen = s(&["claude-sonnet-4-6"]);
        let offers = model_offers("claude-sonnet-4-6", &available, &seen, &[]);
        assert_eq!(offers, s(&["claude-sonnet-5"]));
    }

    #[test]
    fn offers_family_upgrade_for_pinned_opus() {
        let available = s(&["claude-opus-4-8", "claude-opus-4-6"]);
        let seen = s(&["claude-opus-4-6"]);
        let offers = model_offers("claude-opus-4-6", &available, &seen, &[]);
        assert_eq!(offers, s(&["claude-opus-4-8"]));
    }

    #[test]
    fn no_sonnet_offer_for_opus_pin_when_sonnet_family_seen() {
        let available = s(&["claude-opus-4-6", "claude-sonnet-5"]);
        let seen = s(&["claude-opus-4-6", "claude-sonnet-4-6"]);
        let offers = model_offers("claude-opus-4-6", &available, &seen, &[]);
        assert!(offers.is_empty());
    }

    #[test]
    fn offers_brand_new_family_flagship() {
        let available = s(&["claude-opus-4-6", "claude-fable-5"]);
        let seen = s(&["claude-opus-4-6"]);
        let offers = model_offers("claude-opus-4-6", &available, &seen, &[]);
        assert_eq!(offers, s(&["claude-fable-5"]));
    }

    #[test]
    fn first_run_suppresses_brand_new_family() {
        // seen empty ⇒ everything looks new; only family-upgrade may fire.
        let available =
            s(&["claude-opus-4-6", "claude-opus-4-8", "claude-fable-5"]);
        let offers = model_offers("claude-opus-4-6", &available, &[], &[]);
        assert_eq!(offers, s(&["claude-opus-4-8"]));
    }

    // The offline shape: no live list, so `available` is the static roster
    // and `seen` is empty. A pin left on last generation's flagship must
    // still draw an upgrade offer rather than booting silently.
    #[test]
    fn offline_roster_offers_upgrade_for_stale_opus_pin() {
        let available = s(crate::settings::FALLBACK_MODELS);
        let offers = model_offers("claude-opus-5", &available, &[], &[]);
        assert_eq!(offers, s(&[crate::wrapper::DEFAULT_MODEL]));
    }

    #[test]
    fn offline_roster_offers_nothing_for_current_flagship() {
        let available = s(crate::settings::FALLBACK_MODELS);
        let offers =
            model_offers(crate::wrapper::DEFAULT_MODEL, &available, &[], &[]);
        assert!(offers.is_empty(), "unexpected offers: {offers:?}");
    }

    // ---- pinned-model startup notice ------------------------------------

    #[test]
    fn pin_status_current_for_newest_in_family() {
        let available = s(&["claude-opus-5-5", "claude-opus-5"]);
        assert_eq!(
            pin_status("claude-opus-5-5", &available, true),
            PinStatus::Current
        );
    }

    #[test]
    fn pin_status_superseded_when_newer_release_listed() {
        let available = s(&["claude-opus-5-5", "claude-opus-5"]);
        assert_eq!(
            pin_status("claude-opus-5", &available, true),
            PinStatus::Superseded {
                newer: "claude-opus-5-5".into()
            }
        );
    }

    #[test]
    fn pin_status_unsupported_carries_family_replacement() {
        let available = s(&["claude-opus-5-5", "claude-opus-5"]);
        assert_eq!(
            pin_status("claude-opus-4-6", &available, true),
            PinStatus::Unsupported {
                replacement: Some("claude-opus-5-5".into())
            }
        );
    }

    // A legacy id still names its family, so the notice can point at that
    // family's current flagship.
    #[test]
    fn pin_status_unsupported_suggests_flagship_for_legacy_id() {
        let available = s(&["claude-opus-5-5", "claude-sonnet-5-5"]);
        assert_eq!(
            pin_status("claude-3-5-sonnet-20241022", &available, true),
            PinStatus::Unsupported {
                replacement: Some("claude-sonnet-5-5".into())
            }
        );
    }

    #[test]
    fn pin_status_unsupported_without_replacement_for_unknown_family() {
        let available = s(&["claude-opus-5-5", "claude-sonnet-5-5"]);
        assert_eq!(
            pin_status("gpt-4o", &available, true),
            PinStatus::Unsupported { replacement: None }
        );
    }

    // The static roster holds the current generation only, so absence from it
    // proves nothing. An offline launch may still report "superseded", but
    // never "unsupported" — that would cry wolf over a valid older pin.
    #[test]
    fn pin_status_never_unsupported_from_a_non_live_roster() {
        let available = s(crate::settings::FALLBACK_MODELS);
        assert_eq!(
            pin_status("claude-opus-4-6", &available, false),
            PinStatus::Superseded {
                newer: crate::wrapper::DEFAULT_MODEL.into()
            }
        );
        // Still a true statement without a live list; only the "not listed"
        // conclusion needs one.
        assert_eq!(
            pin_status("claude-3-5-sonnet-20241022", &available, false),
            PinStatus::Superseded {
                newer: "claude-sonnet-5-5".into()
            }
        );
    }

    #[test]
    fn pin_status_ignores_date_snapshot_when_matching() {
        let available = s(&["claude-opus-4-8-20260501"]);
        assert_eq!(
            pin_status("claude-opus-4-8", &available, true),
            PinStatus::Current
        );
    }

    #[test]
    fn pin_notice_names_model_scope_and_remedy() {
        let notice = pin_notice(
            "claude-opus-5",
            PinScope::Global,
            &PinStatus::Superseded {
                newer: "claude-opus-5-5".into(),
            },
        );
        assert!(notice.contains("claude-opus-5"), "{notice}");
        assert!(notice.contains("claude-opus-5-5"), "{notice}");
        assert!(notice.contains("~/.whetstone/settings.json"), "{notice}");
        assert!(notice.contains("whetstone settings"), "{notice}");
    }

    #[test]
    fn pin_notice_falls_back_to_launch_default_for_retired_family() {
        let notice = pin_notice(
            "claude-3-5-sonnet-20241022",
            PinScope::Project,
            &PinStatus::Unsupported { replacement: None },
        );
        assert!(notice.contains(crate::wrapper::DEFAULT_MODEL), "{notice}");
        assert!(notice.contains(".claude/whetstone.json"), "{notice}");
    }

    #[test]
    fn dismissed_excluded_but_newer_still_offered() {
        let available = s(&["claude-sonnet-4-6", "claude-sonnet-6"]);
        let seen = s(&["claude-sonnet-4-6"]);
        // Dismissing an older candidate does not block a newer one.
        let offers = model_offers(
            "claude-sonnet-4-6",
            &available,
            &seen,
            &s(&["claude-sonnet-5"]),
        );
        assert_eq!(offers, s(&["claude-sonnet-6"]));
        // Dismissing the actual newest yields nothing.
        let offers = model_offers(
            "claude-sonnet-4-6",
            &available,
            &seen,
            &s(&["claude-sonnet-6"]),
        );
        assert!(offers.is_empty());
    }

    #[test]
    fn read_seen_missing_returns_empty() {
        let base = tempfile::tempdir().unwrap();
        let proj = Path::new("/some/project");
        assert!(read_seen_in(base.path(), proj).is_empty());
    }

    #[test]
    fn write_then_read_round_trips() {
        let base = tempfile::tempdir().unwrap();
        let proj = Path::new("/some/project");
        let models = s(&["claude-opus-4-8", "claude-sonnet-5"]);
        write_seen_in(base.path(), proj, &models);
        assert_eq!(read_seen_in(base.path(), proj), models);
    }

    #[test]
    fn seen_path_stable_for_same_dir() {
        let base = tempfile::tempdir().unwrap();
        let proj = Path::new("/some/project");
        assert_eq!(
            seen_cache_path_in(base.path(), proj),
            seen_cache_path_in(base.path(), proj)
        );
    }

    #[test]
    fn seen_path_differs_across_dirs() {
        let base = tempfile::tempdir().unwrap();
        let a = seen_cache_path_in(base.path(), Path::new("/proj/a"));
        let b = seen_cache_path_in(base.path(), Path::new("/proj/b"));
        assert_ne!(a, b);
    }

    #[test]
    fn effective_never_offered_and_results_deduped() {
        // effective is already newest in family ⇒ not offered.
        let available = s(&["claude-sonnet-5"]);
        let seen = s(&["claude-sonnet-5"]);
        assert!(
            model_offers("claude-sonnet-5", &available, &seen, &[]).is_empty()
        );

        // Family-upgrade and brand-new-family compute the same flagship for a
        // family absent from `seen`; result is deduped.
        let available = s(&["claude-opus-4-6", "claude-opus-4-8"]);
        let seen = s(&["claude-sonnet-5"]);
        let offers = model_offers("claude-opus-4-6", &available, &seen, &[]);
        assert_eq!(offers, s(&["claude-opus-4-8"]));
    }
}