modelshelf 0.1.0

A shared local LLM model registry: discover, deduplicate, download, and update models across desktop apps.
Documentation
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
//! Hardware-aware model recommendation.
//!
//! [`recommend`] is a pure function from (catalog, hardware, registry
//! contents) to a report: which curated models fit this machine, which one
//! is the best pick, whether any of them (or something similar) is already
//! installed, and — for machines provisioned through
//! [`crate::Shelf::provision_recommended`] — whether a better model has
//! since appeared in the catalog. Applications surface that last signal as
//! their own "upgrade available" notification.
//!
//! The memory model is deliberately simple and conservative; the constants
//! below document it.

use serde::Serialize;

use crate::catalog::{Catalog, CatalogEntry, CatalogOrigin};
use crate::hw::Hardware;
use crate::registry::{ModelEntry, ModelId};

/// Reserved application-id *prefix* under which `provision_recommended`
/// (and the CLI `recommend --pull`) records which model is this machine's
/// current recommendation for a task: the full id is
/// `sh.modelshelf.recommend.<task>` (see [`recommend_app_id`]). The ref's
/// alias stores the catalog entry name — companion files carry the alias
/// `<name>#extra` so the main model is distinguishable.
pub const RECOMMEND_APP_ID: &str = "sh.modelshelf.recommend";

/// The use cases the current curated catalog covers. Informational (the
/// `task` field is free-form data): new tasks may appear in newer catalogs
/// without a code change.
pub const KNOWN_TASKS: [&str; 7] = [
    "chat",
    "code",
    "reasoning",
    "embedding",
    "stt",
    "tts",
    "vision",
];

/// The reserved application id marking the provisioned model for `task`.
pub fn recommend_app_id(task: &str) -> String {
    format!("{RECOMMEND_APP_ID}.{task}")
}

/// Whether `app_id` marks the provisioned model for `task`. The bare prefix
/// (written by early builds) counts as `chat`.
pub fn is_recommend_ref(app_id: &str, task: &str) -> bool {
    app_id == recommend_app_id(task) || (task == "chat" && app_id == RECOMMEND_APP_ID)
}

/// The *main* model currently provisioned for `task`, if any: it carries the
/// task's recommend ref with a plain entry-name alias (companion files use
/// `<name>#extra`).
pub fn provisioned_for_task<'a>(installed: &'a [ModelEntry], task: &str) -> Option<&'a ModelEntry> {
    installed.iter().find(|m| {
        m.refs.iter().any(|r| {
            is_recommend_ref(&r.app_id, task)
                && !r.alias.as_deref().unwrap_or_default().contains('#')
        })
    })
}

const GIB: u64 = 1024 * 1024 * 1024;

/// Fraction of a discrete GPU's VRAM budgeted for the model.
pub const DISCRETE_GPU_FACTOR: f64 = 0.90;
/// Fraction of unified (Apple Silicon) memory budgeted for the model.
pub const UNIFIED_MEMORY_FACTOR: f64 = 0.70;
/// Fraction of plain RAM budgeted for CPU-only inference.
pub const CPU_FACTOR: f64 = 0.60;
/// A discrete GPU is preferred even when plain RAM would allow a larger
/// model, unless RAM offers more than this multiple of the GPU budget:
/// GPU inference is roughly an order of magnitude faster, so only a *much*
/// larger model justifies the CPU path.
pub const GPU_PREFERENCE: f64 = 2.0;
/// Estimated memory need scales with file size (compute buffers, mmap
/// overshoot) ...
const WEIGHTS_OVERHEAD: f64 = 1.15;
/// ... plus a flat allowance for the KV cache of a ~8K context and scratch.
const RUNTIME_OVERHEAD_BYTES: u64 = 3 * GIB / 2;

/// The execution backend a budget was computed for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Backend {
    /// Model weights live in discrete-GPU VRAM.
    DiscreteGpu,
    /// Apple Silicon unified memory (GPU-accelerated, one pool).
    UnifiedMemory,
    /// CPU inference from plain RAM.
    CpuOnly,
}

/// An already-installed model matching a catalog entry.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct InstalledRef {
    /// The registry model.
    pub id: ModelId,
    /// True for an exact source match (same repo and file); false for a
    /// best-effort "similar model" match (same size class, or family name).
    pub exact: bool,
}

/// One catalog entry evaluated against this machine.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Recommendation {
    /// The catalog entry.
    pub entry: CatalogEntry,
    /// Estimated memory needed to run it (weights + runtime overhead).
    pub required_bytes: u64,
    /// Whether `required_bytes` fits within the machine's budget.
    pub fits: bool,
    /// A local model that already is (or resembles) this entry, if any.
    pub installed: Option<InstalledRef>,
}

/// A better recommendation than the currently provisioned model.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Upgrade {
    /// The currently provisioned model (carries [`RECOMMEND_APP_ID`]).
    pub from: ModelId,
    /// Its display name.
    pub from_name: String,
    /// The catalog entry that now fits this machine better.
    pub to: CatalogEntry,
}

/// Result of [`recommend`] / [`crate::Shelf::recommend`].
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RecommendReport {
    /// The use case this report is scoped to.
    pub task: String,
    /// The hardware the report was computed for.
    pub hardware: Hardware,
    /// Version of the catalog used.
    pub catalog_version: u64,
    /// `updated` timestamp of the catalog used.
    pub catalog_updated: String,
    /// Whether the catalog came from the cache or the embedded snapshot.
    pub catalog_origin: CatalogOrigin,
    /// The backend the budget assumes.
    pub backend: Backend,
    /// Memory available for a model on this machine, in bytes.
    pub budget_bytes: u64,
    /// Every catalog entry, evaluated. Catalog order is preserved.
    pub items: Vec<Recommendation>,
    /// Name of the best entry: the largest non-deprecated one that fits.
    pub best: Option<String>,
    /// Set when the provisioned model is no longer the best pick.
    pub upgrade: Option<Upgrade>,
}

impl RecommendReport {
    /// The [`Recommendation`] named by [`RecommendReport::best`].
    pub fn best_item(&self) -> Option<&Recommendation> {
        let best = self.best.as_deref()?;
        self.items.iter().find(|r| r.entry.name == best)
    }
}

/// The memory budget for this machine and the backend it assumes.
///
/// A discrete GPU wins by default ([`GPU_PREFERENCE`]); plain RAM takes over
/// only when it is so much larger that it enables a whole different class of
/// model (e.g. a 4 GiB GPU in a 64 GiB workstation).
pub fn budget(hw: &Hardware) -> (Backend, u64) {
    let mut best = (Backend::CpuOnly, (hw.ram_bytes as f64 * CPU_FACTOR) as u64);
    if hw.unified_memory {
        let unified = (hw.ram_bytes as f64 * UNIFIED_MEMORY_FACTOR) as u64;
        if unified > best.1 {
            best = (Backend::UnifiedMemory, unified);
        }
    }
    if let Some(vram) = hw.gpus.iter().map(|g| g.vram_bytes).max() {
        let gpu = (vram as f64 * DISCRETE_GPU_FACTOR) as u64;
        if gpu as f64 * GPU_PREFERENCE >= best.1 as f64 {
            best = (Backend::DiscreteGpu, gpu);
        }
    }
    best
}

/// Estimated memory required to run a model of this file size.
pub fn required_bytes(file_bytes: u64) -> u64 {
    (file_bytes as f64 * WEIGHTS_OVERHEAD) as u64 + RUNTIME_OVERHEAD_BYTES
}

/// Evaluate the `task`-scoped slice of `catalog` against `hw` and the
/// registry contents `installed`. Pure: no I/O, no network.
pub fn recommend(
    catalog: &Catalog,
    origin: CatalogOrigin,
    hw: &Hardware,
    installed: &[ModelEntry],
    task: &str,
) -> RecommendReport {
    let (backend, budget_bytes) = budget(hw);

    let items: Vec<Recommendation> = catalog
        .entries
        .iter()
        .filter(|entry| entry.task == task)
        .map(|entry| {
            let required = required_bytes(entry.total_bytes());
            Recommendation {
                required_bytes: required,
                fits: required <= budget_bytes,
                installed: find_installed(entry, installed),
                entry: entry.clone(),
            }
        })
        .collect();

    let best = items
        .iter()
        .filter(|r| r.fits && !r.entry.deprecated)
        .max_by_key(|r| r.entry.total_bytes())
        .map(|r| r.entry.name.clone());

    let provisioned = provisioned_for_task(installed, task);
    let upgrade = match (provisioned, &best) {
        (Some(current), Some(best_name)) => {
            let best_item = items
                .iter()
                .find(|r| &r.entry.name == best_name)
                .expect("best names an item");
            let current_is_best = best_item
                .installed
                .as_ref()
                .is_some_and(|i| i.exact && i.id == current.id);
            (!current_is_best).then(|| Upgrade {
                from: current.id.clone(),
                from_name: current.display_name.clone(),
                to: best_item.entry.clone(),
            })
        }
        _ => None,
    };

    RecommendReport {
        task: task.to_owned(),
        hardware: hw.clone(),
        catalog_version: catalog.catalog_version,
        catalog_updated: catalog.updated.clone(),
        catalog_origin: origin,
        backend,
        budget_bytes,
        items,
        best,
        upgrade,
    }
}

/// Upgrade signals for *every* task that has a provisioned model. What the
/// `update` command (and application background checks) surface.
pub fn all_upgrades(
    catalog: &Catalog,
    origin: CatalogOrigin,
    hw: &Hardware,
    installed: &[ModelEntry],
) -> Vec<Upgrade> {
    let mut tasks: Vec<String> = installed
        .iter()
        .flat_map(|m| m.refs.iter())
        .filter_map(|r| {
            let app_id = r.app_id.as_str();
            if app_id == RECOMMEND_APP_ID {
                return Some("chat".to_owned()); // legacy bare ref
            }
            app_id
                .strip_prefix(RECOMMEND_APP_ID)
                .and_then(|rest| rest.strip_prefix('.'))
                .map(str::to_owned)
        })
        .collect();
    tasks.sort();
    tasks.dedup();
    tasks
        .iter()
        .filter_map(|task| recommend(catalog, origin, hw, installed, task).upgrade)
        .collect()
}

/// Find a registry model that is (exact) or resembles (similar) `entry`.
///
/// Exact: the model's recorded source is the same repo and file. Similar
/// (best-effort, for models installed through other ecosystems): parameter
/// count within ±10% and the same quantization label, or the entry name
/// appearing in the model's display name.
fn find_installed(entry: &CatalogEntry, installed: &[ModelEntry]) -> Option<InstalledRef> {
    if let Some(m) = installed.iter().find(|m| {
        m.source
            .as_ref()
            .is_some_and(|s| s.repo == entry.repo && s.filename == entry.filename)
    }) {
        return Some(InstalledRef {
            id: m.id.clone(),
            exact: true,
        });
    }
    installed
        .iter()
        .find(|m| is_similar(entry, m))
        .map(|m| InstalledRef {
            id: m.id.clone(),
            exact: false,
        })
}

fn is_similar(entry: &CatalogEntry, model: &ModelEntry) -> bool {
    let by_size_class = model.gguf.as_ref().is_some_and(|g| {
        let same_params = g.parameter_count.is_some_and(|count| {
            let target = entry.params_b * 1e9;
            (count as f64 - target).abs() <= target * 0.10
        });
        let same_quant = g
            .quantization
            .as_ref()
            .is_some_and(|q| q.eq_ignore_ascii_case(&entry.quant));
        same_params && same_quant
    });
    by_size_class
        || crate::shelf::normalize(&model.display_name)
            .contains(&crate::shelf::normalize(&entry.name))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catalog::Catalog;
    use crate::registry::{AppRef, GgufMeta};

    fn hw(ram_gib: u64, vram_gib: Option<u64>, unified: bool) -> Hardware {
        Hardware {
            ram_bytes: ram_gib * GIB,
            ram_assumed: false,
            gpus: vram_gib
                .map(|v| {
                    vec![crate::hw::Gpu {
                        name: "Test GPU".into(),
                        vram_bytes: v * GIB,
                    }]
                })
                .unwrap_or_default(),
            unified_memory: unified,
        }
    }

    fn catalog(entries: Vec<CatalogEntry>) -> Catalog {
        Catalog {
            catalog_version: 7,
            updated: "2026-07-10T00:00:00Z".into(),
            entries,
        }
    }

    fn centry(name: &str, file_gib: f64) -> CatalogEntry {
        CatalogEntry {
            name: name.into(),
            task: "chat".into(),
            repo: format!("org/{name}"),
            filename: format!("{name}.gguf"),
            format: "gguf".into(),
            quant: "Q4_K_M".into(),
            file_bytes: (file_gib * GIB as f64) as u64,
            params_b: 8.0,
            japanese: false,
            notes: String::new(),
            deprecated: false,
            extra_files: Vec::new(),
        }
    }

    fn centry_task(name: &str, file_gib: f64, task: &str) -> CatalogEntry {
        CatalogEntry {
            task: task.into(),
            ..centry(name, file_gib)
        }
    }

    fn model(id_seed: &str, display_name: &str) -> ModelEntry {
        ModelEntry {
            id: ModelId::from_sha256_hex(&format!("{id_seed:0>64}")),
            format: "gguf".into(),
            size_bytes: 1,
            display_name: display_name.into(),
            gguf: None,
            source: None,
            store_path: None,
            locations: Vec::new(),
            refs: Vec::new(),
            first_seen: "2026-01-01T00:00:00Z".into(),
            last_verified: None,
            extra: Default::default(),
        }
    }

    fn with_source(mut m: ModelEntry, repo: &str, filename: &str) -> ModelEntry {
        m.source = Some(crate::registry::Source {
            kind: "huggingface".into(),
            repo: repo.into(),
            filename: filename.into(),
            revision: None,
            resolved_at: "2026-01-01T00:00:00Z".into(),
            extra: Default::default(),
        });
        m
    }

    fn with_recommend_ref(mut m: ModelEntry, task: &str, alias: &str) -> ModelEntry {
        m.refs.push(AppRef {
            app_id: recommend_app_id(task),
            alias: Some(alias.into()),
            added_at: "2026-01-01T00:00:00Z".into(),
            extra: Default::default(),
        });
        m
    }

    #[test]
    fn budget_prefers_gpu_unless_ram_dwarfs_it() {
        // Plain 64 GiB machine: CPU only.
        assert_eq!(
            budget(&hw(64, None, false)),
            (Backend::CpuOnly, (64.0 * GIB as f64 * 0.60) as u64)
        );
        // 24 GiB GPU in a 32 GiB machine: GPU.
        assert_eq!(
            budget(&hw(32, Some(24), false)),
            (Backend::DiscreteGpu, (24.0 * GIB as f64 * 0.90) as u64)
        );
        // 8 GiB GPU in a 16 GiB machine: the CPU budget (9.6) is larger than
        // the GPU budget (7.2) but within GPU_PREFERENCE — GPU wins on speed.
        assert_eq!(budget(&hw(16, Some(8), false)).0, Backend::DiscreteGpu);
        // A tiny 4 GiB GPU in a 64 GiB workstation: RAM enables a different
        // class of model (38.4 > 2 × 3.6), CPU wins.
        assert_eq!(budget(&hw(64, Some(4), false)).0, Backend::CpuOnly);
        // Apple Silicon 32 GiB unified.
        assert_eq!(
            budget(&hw(32, None, true)),
            (Backend::UnifiedMemory, (32.0 * GIB as f64 * 0.70) as u64)
        );
    }

    #[test]
    fn required_bytes_is_documented_formula() {
        let five_gib = 5 * GIB;
        assert_eq!(
            required_bytes(five_gib),
            (five_gib as f64 * 1.15) as u64 + 3 * GIB / 2
        );
    }

    #[test]
    fn best_is_largest_fitting_non_deprecated() {
        let mut old = centry("old-flagship", 6.0);
        old.deprecated = true;
        let cat = catalog(vec![centry("small", 1.0), centry("mid", 4.0), old]);
        // 16 GiB CPU budget = 9.6 GiB; "old-flagship" needs 8.4 and fits,
        // but is deprecated; "mid" needs 6.1 and wins.
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[],
            "chat",
        );
        assert_eq!(report.best.as_deref(), Some("mid"));
        let items: Vec<(&str, bool)> = report
            .items
            .iter()
            .map(|r| (r.entry.name.as_str(), r.fits))
            .collect();
        assert_eq!(
            items,
            vec![("small", true), ("mid", true), ("old-flagship", true)]
        );

        // Nothing fits a 1 GiB machine.
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(1, None, false),
            &[],
            "chat",
        );
        assert_eq!(report.best, None);
    }

    #[test]
    fn tasks_are_scoped_and_independent() {
        let cat = catalog(vec![
            centry("chat-model", 1.0),
            centry_task("coder-small", 1.0, "code"),
            centry_task("coder-big", 4.0, "code"),
            centry_task("speech", 0.2, "tts"),
        ]);
        let machine = hw(16, None, false);

        // Each task sees only its own entries.
        let chat = recommend(&cat, CatalogOrigin::Embedded, &machine, &[], "chat");
        assert_eq!(chat.items.len(), 1);
        assert_eq!(chat.best.as_deref(), Some("chat-model"));
        let code = recommend(&cat, CatalogOrigin::Embedded, &machine, &[], "code");
        assert_eq!(code.items.len(), 2);
        assert_eq!(code.best.as_deref(), Some("coder-big"));
        let unknown = recommend(&cat, CatalogOrigin::Embedded, &machine, &[], "nonexistent");
        assert!(unknown.items.is_empty());
        assert_eq!(unknown.best, None);

        // A provisioned chat model does not trigger code upgrades: upgrades
        // are per task.
        let chat_provisioned = with_recommend_ref(
            with_source(
                model("aa", "Chat Model"),
                "org/chat-model",
                "chat-model.gguf",
            ),
            "chat",
            "chat-model",
        );
        let code_provisioned = with_recommend_ref(
            with_source(
                model("bb", "Coder Small"),
                "org/coder-small",
                "coder-small.gguf",
            ),
            "code",
            "coder-small",
        );
        let installed = [chat_provisioned, code_provisioned];
        let chat = recommend(&cat, CatalogOrigin::Embedded, &machine, &installed, "chat");
        assert!(chat.upgrade.is_none(), "chat pick is already the best");
        let code = recommend(&cat, CatalogOrigin::Embedded, &machine, &installed, "code");
        let up = code.upgrade.expect("coder-big supersedes coder-small");
        assert_eq!(up.to.name, "coder-big");

        // all_upgrades reports exactly the code upgrade.
        let ups = all_upgrades(&cat, CatalogOrigin::Embedded, &machine, &installed);
        assert_eq!(ups.len(), 1);
        assert_eq!(ups[0].to.name, "coder-big");
    }

    #[test]
    fn extra_files_count_toward_required_memory() {
        let mut entry = centry_task("speech", 1.0, "tts");
        entry.extra_files.push(crate::catalog::ExtraFile {
            repo: Some("org/decoder".into()),
            filename: "decoder.gguf".into(),
            file_bytes: GIB,
        });
        assert_eq!(entry.total_bytes(), 2 * GIB);
        let cat = catalog(vec![entry]);
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[],
            "tts",
        );
        assert_eq!(report.items[0].required_bytes, required_bytes(2 * GIB));
    }

    #[test]
    fn legacy_bare_ref_counts_as_chat() {
        let cat = catalog(vec![centry("small", 1.0), centry("big", 4.0)]);
        let mut legacy = with_source(model("aa", "Small Model"), "org/small", "small.gguf");
        legacy.refs.push(AppRef {
            app_id: RECOMMEND_APP_ID.into(), // bare prefix from early builds
            alias: Some("small".into()),
            added_at: "2026-01-01T00:00:00Z".into(),
            extra: Default::default(),
        });
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            std::slice::from_ref(&legacy),
            "chat",
        );
        assert_eq!(report.upgrade.expect("legacy ref upgrades").to.name, "big");
        let ups = all_upgrades(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[legacy],
        );
        assert_eq!(ups.len(), 1);
    }

    #[test]
    fn embedded_catalog_covers_the_fallback_machine() {
        // Even the assumed-8-GiB fallback machine must get a recommendation.
        let mut fallback = hw(8, None, false);
        fallback.ram_assumed = true;
        let report = recommend(
            &Catalog::embedded(),
            CatalogOrigin::Embedded,
            &fallback,
            &[],
            "chat",
        );
        assert!(report.best.is_some(), "8 GiB machine got no recommendation");
        // …and every task in the embedded catalog has at least one entry
        // reachable by a modest 16 GiB machine.
        let embedded = Catalog::embedded();
        let mut tasks: Vec<&str> = embedded.entries.iter().map(|e| e.task.as_str()).collect();
        tasks.sort();
        tasks.dedup();
        assert_eq!(tasks.len(), KNOWN_TASKS.len(), "catalog/KNOWN_TASKS drift");
        for task in tasks {
            let report = recommend(
                &embedded,
                CatalogOrigin::Embedded,
                &hw(16, None, false),
                &[],
                task,
            );
            assert!(report.best.is_some(), "no {task} pick for a 16 GiB machine");
        }
    }

    #[test]
    fn installed_exact_beats_similar() {
        let cat = catalog(vec![centry("alpha", 1.0)]);
        let exact = with_source(model("aa", "Anything"), "org/alpha", "alpha.gguf");
        let similar = model("bb", "Alpha 8B Instruct");
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[similar, exact],
            "chat",
        );
        let inst = report.items[0].installed.as_ref().unwrap();
        assert!(inst.exact);
        assert_eq!(inst.id, ModelId::from_sha256_hex(&format!("{:0>64}", "aa")));
    }

    #[test]
    fn similar_matches_by_size_class_or_name() {
        let entry = centry("qwen3-8b", 5.0); // params_b = 8.0, Q4_K_M
        let mut by_params = model("cc", "totally different name");
        by_params.gguf = Some(GgufMeta {
            general_name: None,
            architecture: None,
            quantization: Some("q4_k_m".into()),
            parameter_count: Some(8_200_000_000), // within ±10%
            context_length: None,
            extra: Default::default(),
        });
        assert!(is_similar(&entry, &by_params));

        // Params match but the quantization differs: not similar by size.
        let mut wrong_quant = by_params.clone();
        wrong_quant.gguf.as_mut().unwrap().quantization = Some("Q8_0".into());
        assert!(!is_similar(&entry, &wrong_quant));

        // Name-based fallback, tolerant of separators and case.
        assert!(is_similar(&entry, &model("dd", "Qwen3 8B Instruct")));
        assert!(is_similar(&entry, &model("ee", "qwen3_8b-q4")));
        assert!(!is_similar(&entry, &model("ff", "Llama 3.1 8B")));
    }

    #[test]
    fn upgrade_fires_only_for_provisioned_machines() {
        let cat = catalog(vec![centry("small", 1.0), centry("big", 4.0)]);
        let small_installed = with_recommend_ref(
            with_source(model("aa", "Small Model"), "org/small", "small.gguf"),
            "chat",
            "small",
        );

        // Provisioned "small", but "big" now fits: upgrade.
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            std::slice::from_ref(&small_installed),
            "chat",
        );
        let up = report.upgrade.expect("upgrade expected");
        assert_eq!(up.from, small_installed.id);
        assert_eq!(up.to.name, "big");

        // Same registry but no recommend ref: no upgrade signal.
        let unprovisioned = with_source(model("aa", "Small Model"), "org/small", "small.gguf");
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[unprovisioned],
            "chat",
        );
        assert!(report.upgrade.is_none());

        // Provisioned model IS the best: no upgrade.
        let big_installed = with_recommend_ref(
            with_source(model("bb", "Big Model"), "org/big", "big.gguf"),
            "chat",
            "big",
        );
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(16, None, false),
            &[big_installed],
            "chat",
        );
        assert!(report.upgrade.is_none());

        // A companion file's ref (alias `name#extra`) is not "the current
        // model": it must not drive upgrade comparisons.
        let extra_only = with_recommend_ref(
            with_source(model("cc", "Decoder"), "org/decoder", "decoder.gguf"),
            "chat",
            "small#extra",
        );
        assert!(provisioned_for_task(&[extra_only], "chat").is_none());

        // Provisioned machine that shrank (nothing fits): no upgrade target.
        let report = recommend(
            &cat,
            CatalogOrigin::Embedded,
            &hw(1, None, false),
            &[small_installed],
            "chat",
        );
        assert!(report.upgrade.is_none());
    }

    #[test]
    fn report_serializes_for_json_consumers() {
        let cat = catalog(vec![centry("small", 1.0)]);
        let report = recommend(
            &cat,
            CatalogOrigin::Cached,
            &hw(16, Some(8), false),
            &[],
            "chat",
        );
        let json = serde_json::to_value(&report).unwrap();
        assert_eq!(json["task"], "chat");
        assert_eq!(json["catalog_origin"], "cached");
        assert_eq!(json["backend"], "discrete_gpu");
        assert!(json["items"][0]["required_bytes"].is_u64());
    }
}