lean-ctx-engine 3.12.3

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
//! Embedding model registry — model configs, selection, and metadata.
//!
//! Supports multiple ONNX embedding models with different dimensions,
//! tokenizers, and download sources. Models are selected via the
//! `LEAN_CTX_EMBEDDING_MODEL` env var or the `[embedding].model` key in `config.toml`
//! (env var wins) — see [`resolve_model`].
//!
//! Besides the built-ins, any compatible HuggingFace repo can be loaded with
//! `model = "hf:org/repo[@revision]"` (GL #397, upstream #328): the repo must
//! ship an ONNX export (`onnx/model.onnx`) and a `tokenizer.json`. This custom
//! path probes the ONNX graph for its real input/output signature, so it suits
//! code-specialized models (e.g. `hf:jinaai/jina-embeddings-v2-base-code`) that
//! need no hand-maintained config. See `docs/guides/custom-embeddings.md`.

use std::fmt;

/// Supported embedding models.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EmbeddingModel {
    /// all-MiniLM-L6-v2 — generic sentence embeddings (384d, ~91MB).
    /// Default model for backward compatibility.
    AllMiniLmL6V2,
    /// nomic-embed-text-v1.5 — top MTEB general-purpose (768d, ~547MB).
    /// Matryoshka representation learning, supports dimension truncation.
    NomicEmbedV1_5,
    /// potion-code-16M — static (model2vec) code embeddings (256d, ~64MB),
    /// run in pure Rust: no ONNX Runtime, microseconds per chunk.
    #[serde(rename = "potion-code-16m")]
    PotionCode16M,
    /// Any HuggingFace repo with an ONNX export + tokenizer.json
    /// (`hf:org/repo[@revision]`, GL #397).
    Custom(CustomModelSpec),
}

/// How a model's weights are stored and run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModelFormat {
    /// An ONNX graph run by ONNX Runtime (needs the `embeddings` feature).
    Onnx,
    /// A model2vec token-embedding table in safetensors, run in pure Rust.
    StaticSafetensors,
}

impl ModelFormat {
    /// File name of the weights inside the model directory.
    #[must_use]
    pub fn local_file(self) -> &'static str {
        match self {
            Self::Onnx => "model.onnx",
            Self::StaticSafetensors => "model.safetensors",
        }
    }
}

/// potion-code-16M at a fixed revision with its file hashes (MIT,
/// <https://huggingface.co/minishlab/potion-code-16M>). A built-in model is
/// pinned outright rather than trusted on first use.
const POTION_CODE_REVISION: &str = "1b0ff71095656b23306542bbad34a09109673720";
const POTION_CODE_SHA256: &[(&str, &str)] = &[
    (
        "model.safetensors",
        "ca6159081a6e96cebe4ad878e5e8437bfccc761e8db16223370149cd2faa6c0b",
    ),
    (
        "tokenizer.json",
        "8e84217af15e70e8127c855435fc3d8a4cd91d7bbe686f72e75f188118ec78ae",
    ),
];

/// A user-supplied HuggingFace embedding model (`hf:org/repo[@revision]`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct CustomModelSpec {
    /// HuggingFace repo id, e.g. `jinaai/jina-embeddings-v2-base-code`.
    pub repo: String,
    /// Optional revision pin (tag/branch/commit). `None` resolves `main` —
    /// supply-chain-wise a pin is strongly recommended and the resolver warns
    /// without one.
    pub revision: Option<String>,
    /// Embedding dimensions (`[embedding].dimensions`). When unset, the real
    /// value is detected from a probe inference at load time; this is only the
    /// declared fallback.
    pub dimensions: Option<usize>,
}

impl CustomModelSpec {
    /// Parse `org/repo[@revision]` (the part after the `hf:` scheme).
    /// Returns `None` when the repo id is not plausibly a HuggingFace repo.
    fn parse(s: &str) -> Option<Self> {
        let (repo, revision) = match s.split_once('@') {
            Some((r, rev)) => (
                r.trim(),
                Some(rev.trim().to_string()).filter(|v| !v.is_empty()),
            ),
            None => (s.trim(), None),
        };
        // A HF repo id is exactly `owner/name` with no whitespace.
        let mut parts = repo.split('/');
        let (owner, name) = (parts.next()?, parts.next()?);
        if parts.next().is_some()
            || owner.is_empty()
            || name.is_empty()
            || repo.chars().any(char::is_whitespace)
        {
            return None;
        }
        Some(Self {
            repo: repo.to_string(),
            revision,
            dimensions: None,
        })
    }

    /// Filesystem-safe storage slug, unique per repo+revision.
    fn storage_slug(&self) -> String {
        let mut slug = String::from("hf-");
        for c in self.repo.chars() {
            slug.push(match c {
                'a'..='z' | '0'..='9' | '-' => c,
                'A'..='Z' => c.to_ascii_lowercase(),
                _ => '-',
            });
        }
        if let Some(rev) = &self.revision {
            slug.push('-');
            for c in rev.chars().take(16) {
                slug.push(match c {
                    'a'..='z' | '0'..='9' | '-' => c,
                    'A'..='Z' => c.to_ascii_lowercase(),
                    _ => '-',
                });
            }
        }
        slug
    }
}

impl EmbeddingModel {
    pub const DEFAULT: Self = Self::AllMiniLmL6V2;

    pub fn config(&self) -> ModelConfig {
        match self {
            Self::AllMiniLmL6V2 => ModelConfig {
                model: self.clone(),
                name: "all-MiniLM-L6-v2".into(),
                hf_repo: "sentence-transformers/all-MiniLM-L6-v2".into(),
                revision: None,
                onnx_path: "onnx/model.onnx".into(),
                vocab_file: VocabSource::VocabTxt("vocab.txt".into()),
                dimensions: 384,
                max_seq_len: 256,
                model_min_bytes: 1_000_000,
                vocab_min_bytes: 100_000,
                query_prefix: None,
                document_prefix: None,
                needs_token_type_ids: true,
                format: ModelFormat::Onnx,
                pinned_sha256: &[],
            },
            Self::PotionCode16M => ModelConfig {
                model: self.clone(),
                name: "potion-code-16M".into(),
                hf_repo: "minishlab/potion-code-16M".into(),
                revision: Some(POTION_CODE_REVISION.into()),
                onnx_path: "model.safetensors".into(),
                vocab_file: VocabSource::TokenizerJson("tokenizer.json".into()),
                dimensions: 256,
                // Static models average token vectors and see no positions, so a
                // long chunk costs only its token count; cap it like model2vec.
                max_seq_len: 512,
                model_min_bytes: 10_000_000,
                vocab_min_bytes: 100_000,
                query_prefix: None,
                document_prefix: None,
                needs_token_type_ids: false,
                format: ModelFormat::StaticSafetensors,
                pinned_sha256: POTION_CODE_SHA256,
            },
            Self::NomicEmbedV1_5 => ModelConfig {
                model: self.clone(),
                name: "nomic-embed-text-v1.5".into(),
                hf_repo: "nomic-ai/nomic-embed-text-v1.5".into(),
                revision: None,
                onnx_path: "onnx/model.onnx".into(),
                vocab_file: VocabSource::VocabTxt("vocab.txt".into()),
                dimensions: 768,
                max_seq_len: 512,
                model_min_bytes: 100_000_000,
                vocab_min_bytes: 100_000,
                query_prefix: Some("search_query: ".into()),
                document_prefix: Some("search_document: ".into()),
                needs_token_type_ids: false,
                format: ModelFormat::Onnx,
                pinned_sha256: &[],
            },
            Self::Custom(spec) => ModelConfig {
                model: self.clone(),
                // The canonical name doubles as the index `model_id`, so a
                // repo or revision change triggers the one-shot re-index.
                name: match &spec.revision {
                    Some(rev) => format!("hf:{}@{rev}", spec.repo),
                    None => format!("hf:{}", spec.repo),
                },
                hf_repo: spec.repo.clone(),
                revision: spec.revision.clone(),
                onnx_path: "onnx/model.onnx".into(),
                // Custom repos must ship a HuggingFace tokenizer.json — the
                // universal format (WordPiece/BPE/Unigram all serialize to it).
                vocab_file: VocabSource::TokenizerJson("tokenizer.json".into()),
                // Declared fallback; the probe inference at load time detects
                // the real width (`detect_dimensions`) and wins.
                dimensions: spec.dimensions.unwrap_or(768),
                max_seq_len: 512,
                model_min_bytes: 1_000_000,
                vocab_min_bytes: 1_000,
                query_prefix: None,
                document_prefix: None,
                // Probed from the ONNX graph at load time; BERT-style models
                // with a third input still get token_type_ids wired up.
                needs_token_type_ids: false,
                format: ModelFormat::Onnx,
                pinned_sha256: &[],
            },
        }
    }

    /// Parse model name from string (env var / config file).
    ///
    /// Accepts the built-in aliases plus the `hf:org/repo[@revision]` scheme
    /// for custom HuggingFace models (GL #397).
    pub fn from_str_name(s: &str) -> Option<Self> {
        let trimmed = s.trim();
        if let Some(rest) = trimmed.strip_prefix("hf:") {
            return CustomModelSpec::parse(rest).map(Self::Custom);
        }
        match trimmed.to_lowercase().replace('_', "-").as_str() {
            "all-minilm-l6-v2" | "minilm" | "default" => Some(Self::AllMiniLmL6V2),
            "nomic-embed-v1.5" | "nomic-embed-text-v1.5" | "nomic" | "nomic-embed" => {
                Some(Self::NomicEmbedV1_5)
            }
            "potion-code-16m" | "potion-code" | "potion" | "static" => Some(Self::PotionCode16M),
            _ => None,
        }
    }

    /// All built-in model variants (custom models are user-defined).
    pub const ALL: &'static [Self] = &[
        Self::AllMiniLmL6V2,
        Self::NomicEmbedV1_5,
        Self::PotionCode16M,
    ];

    /// Unique subdirectory name for model storage isolation.
    pub fn storage_dir_name(&self) -> String {
        match self {
            Self::AllMiniLmL6V2 => "all-minilm-l6-v2".to_string(),
            Self::NomicEmbedV1_5 => "nomic-embed-v1.5".to_string(),
            Self::PotionCode16M => "potion-code-16m".to_string(),
            Self::Custom(spec) => spec.storage_slug(),
        }
    }
}

impl fmt::Display for EmbeddingModel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.config().name)
    }
}

/// Vocabulary/tokenizer source for a model.
#[derive(Debug, Clone)]
pub enum VocabSource {
    /// Standard BERT vocab.txt (one token per line, WordPiece).
    VocabTxt(String),
    /// HuggingFace tokenizer.json (BPE/Unigram/WordPiece via JSON config).
    TokenizerJson(String),
}

impl VocabSource {
    pub fn filename(&self) -> &str {
        match self {
            Self::VocabTxt(f) | Self::TokenizerJson(f) => f,
        }
    }

    pub fn is_wordpiece(&self) -> bool {
        matches!(self, Self::VocabTxt(_))
    }
}

/// Complete configuration for a single embedding model.
#[derive(Debug, Clone)]
pub struct ModelConfig {
    pub model: EmbeddingModel,
    pub name: String,
    pub hf_repo: String,
    /// Optional revision pin for custom models (`None` = `main`).
    pub revision: Option<String>,
    pub onnx_path: String,
    pub vocab_file: VocabSource,
    pub dimensions: usize,
    pub max_seq_len: usize,
    pub model_min_bytes: u64,
    pub vocab_min_bytes: u64,
    /// Optional prefix prepended to queries before embedding.
    pub query_prefix: Option<String>,
    /// Optional prefix prepended to documents/code before embedding.
    pub document_prefix: Option<String>,
    /// Whether the model expects token_type_ids input (BERT-style).
    /// Some models (e.g. nomic-embed) only use input_ids + attention_mask.
    pub needs_token_type_ids: bool,
    /// How the weights are stored and run.
    pub format: ModelFormat,
    /// `(local file, sha256-hex)` every download must match; empty means
    /// trust-on-first-use via `model.lock.json`.
    pub pinned_sha256: &'static [(&'static str, &'static str)],
}

impl ModelConfig {
    fn resolve_base(&self) -> String {
        format!(
            "https://huggingface.co/{}/resolve/{}",
            self.hf_repo,
            self.revision.as_deref().unwrap_or("main")
        )
    }

    /// File name of the weights inside the model directory.
    #[must_use]
    pub fn local_model_file(&self) -> &'static str {
        self.format.local_file()
    }

    /// Full HuggingFace download URL for the model weights.
    pub fn model_url(&self) -> String {
        format!("{}/{}", self.resolve_base(), self.onnx_path)
    }

    /// Full HuggingFace download URL for the vocabulary/tokenizer file.
    pub fn vocab_url(&self) -> String {
        format!("{}/{}", self.resolve_base(), self.vocab_file.filename())
    }
}

/// Resolve which embedding model to use.
///
/// Priority: `LEAN_CTX_EMBEDDING_MODEL` env var > `[embedding].model` in `config.toml` >
/// the default model. An unrecognized name is skipped (with a warning) so a typo in one
/// source never silently swaps the model — which would otherwise force a full re-index.
pub fn resolve_model() -> EmbeddingModel {
    resolve_model_with_source().0
}

/// Which setting selected the embedding model (#2049: `embeddings status`
/// says so, because the env var and `config.toml` are easy to confuse).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelSource {
    /// `LEAN_CTX_EMBEDDING_MODEL`, with its raw value.
    Env(String),
    /// `[embedding].model` in `config.toml`, with its raw value.
    Config(String),
    /// Nothing (valid) set.
    Default,
}

/// [`resolve_model`] plus the setting it came from.
pub fn resolve_model_with_source() -> (EmbeddingModel, ModelSource) {
    let env_val = std::env::var("LEAN_CTX_EMBEDDING_MODEL").ok();
    let embedding_cfg = crate::core::config::Config::load().embedding;
    resolve_model_with_source_from(
        env_val.as_deref(),
        embedding_cfg.model.as_deref(),
        embedding_cfg.dimensions,
        default_model(),
    )
}

/// The model used when none is configured: MiniLM where ONNX Runtime is
/// installed, the static `potion-code-16m` everywhere else.
///
/// Measured 2026-10-13 on 8,086 documented functions of this repository
/// (docstring → code): MiniLM MRR 0.348 / recall@10 0.570, potion-code MRR
/// 0.247 / recall@10 0.431 — but potion-code indexed them in 0.07 s instead
/// of 557 s (CPU, `eval.rs`), answers a query in 9 µs instead of 26 ms, and
/// needs no `libonnxruntime` — without which an installation has no semantic
/// search at all. So the better model wins where it can run, and the one that
/// runs everywhere covers the rest. Resolved once per process; it only
/// searches the file system, it never loads the library.
#[must_use]
pub fn default_model() -> EmbeddingModel {
    #[cfg(feature = "embeddings")]
    {
        static ORT_PRESENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        let ort_present = *ORT_PRESENT
            .get_or_init(|| crate::core::ort_environment::resolved_ort_dylib_path().is_ok());
        if !ort_present {
            return EmbeddingModel::PotionCode16M;
        }
    }
    EmbeddingModel::DEFAULT
}

/// Pure model resolution used by [`resolve_model`]; kept separate so the env-var/config
/// precedence is unit-testable without touching the process environment or the on-disk
/// `config.toml`.
#[cfg(test)]
fn resolve_model_from(
    env_val: Option<&str>,
    config_val: Option<&str>,
    config_dims: Option<usize>,
) -> EmbeddingModel {
    resolve_model_with_source_from(env_val, config_val, config_dims, EmbeddingModel::DEFAULT).0
}

fn resolve_model_with_source_from(
    env_val: Option<&str>,
    config_val: Option<&str>,
    config_dims: Option<usize>,
    default: EmbeddingModel,
) -> (EmbeddingModel, ModelSource) {
    for (source, raw) in [
        ("LEAN_CTX_EMBEDDING_MODEL", env_val),
        ("[embedding].model", config_val),
    ] {
        let Some(name) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
            continue;
        };
        let origin = if source == "LEAN_CTX_EMBEDDING_MODEL" {
            ModelSource::Env(name.to_string())
        } else {
            ModelSource::Config(name.to_string())
        };
        match EmbeddingModel::from_str_name(name) {
            Some(EmbeddingModel::Custom(mut spec)) => {
                spec.dimensions = config_dims;
                if spec.revision.is_none() {
                    tracing::warn!(
                        "Custom embedding model {:?} has no revision pin — supply-chain best \
                         practice is `hf:{}@<commit-or-tag>` so upstream pushes can never \
                         silently change your index",
                        spec.repo,
                        spec.repo
                    );
                }
                return (EmbeddingModel::Custom(spec), origin);
            }
            Some(model) => return (model, origin),
            None => {
                tracing::warn!(
                    "Unknown embedding model {name:?} from {source}; using {default} instead \
                     (built-ins: minilm, nomic, potion-code — or hf:org/repo[@rev])"
                );
            }
        }
    }
    (default, ModelSource::Default)
}

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

    #[test]
    fn default_model_is_minilm() {
        assert_eq!(EmbeddingModel::DEFAULT, EmbeddingModel::AllMiniLmL6V2);
    }

    #[test]
    fn from_str_name_variants() {
        assert_eq!(
            EmbeddingModel::from_str_name("minilm"),
            Some(EmbeddingModel::AllMiniLmL6V2)
        );
        assert_eq!(
            EmbeddingModel::from_str_name("nomic-embed-v1.5"),
            Some(EmbeddingModel::NomicEmbedV1_5)
        );
        assert_eq!(
            EmbeddingModel::from_str_name("nomic"),
            Some(EmbeddingModel::NomicEmbedV1_5)
        );
        assert_eq!(
            EmbeddingModel::from_str_name("default"),
            Some(EmbeddingModel::AllMiniLmL6V2)
        );
        assert_eq!(EmbeddingModel::from_str_name("unknown"), None);
        // The removed jina built-in must no longer resolve as an alias; it is
        // reachable only via the explicit `hf:` custom scheme.
        assert_eq!(EmbeddingModel::from_str_name("jina-code-v2"), None);
        assert_eq!(EmbeddingModel::from_str_name("jina"), None);
    }

    #[test]
    fn custom_hf_scheme_parses_repo_and_revision() {
        let m = EmbeddingModel::from_str_name("hf:jinaai/jina-embeddings-v2-base-code").unwrap();
        let EmbeddingModel::Custom(spec) = &m else {
            panic!("expected custom")
        };
        assert_eq!(spec.repo, "jinaai/jina-embeddings-v2-base-code");
        assert_eq!(spec.revision, None);

        let m = EmbeddingModel::from_str_name("hf:org/model@abc123").unwrap();
        let EmbeddingModel::Custom(spec) = &m else {
            panic!("expected custom")
        };
        assert_eq!(spec.repo, "org/model");
        assert_eq!(spec.revision.as_deref(), Some("abc123"));
    }

    #[test]
    fn custom_hf_scheme_rejects_invalid_repos() {
        for bad in [
            "hf:",
            "hf:no-slash",
            "hf:too/many/slashes",
            "hf:with space/repo",
            "hf:/leading",
            "hf:trailing/",
            "hf:org/model@",
        ] {
            let parsed = EmbeddingModel::from_str_name(bad);
            if bad == "hf:org/model@" {
                // Empty revision degrades to an unpinned spec, not a reject.
                let Some(EmbeddingModel::Custom(spec)) = parsed else {
                    panic!("expected custom for {bad}")
                };
                assert_eq!(spec.revision, None);
            } else {
                assert_eq!(parsed, None, "{bad} should be rejected");
            }
        }
    }

    #[test]
    fn custom_config_urls_and_storage() {
        let m = EmbeddingModel::from_str_name("hf:Org/My_Model@v1.2").unwrap();
        let cfg = m.config();
        assert_eq!(
            cfg.model_url(),
            "https://huggingface.co/Org/My_Model/resolve/v1.2/onnx/model.onnx"
        );
        assert_eq!(
            cfg.vocab_url(),
            "https://huggingface.co/Org/My_Model/resolve/v1.2/tokenizer.json"
        );
        assert!(!cfg.vocab_file.is_wordpiece());
        assert_eq!(cfg.name, "hf:Org/My_Model@v1.2");
        assert_eq!(m.storage_dir_name(), "hf-org-my-model-v1-2");
    }

    #[test]
    fn custom_storage_slugs_differ_per_revision() {
        let a = EmbeddingModel::from_str_name("hf:org/model@aaa").unwrap();
        let b = EmbeddingModel::from_str_name("hf:org/model@bbb").unwrap();
        let c = EmbeddingModel::from_str_name("hf:org/model").unwrap();
        let slugs = [
            a.storage_dir_name(),
            b.storage_dir_name(),
            c.storage_dir_name(),
        ];
        let unique: std::collections::HashSet<_> = slugs.iter().collect();
        assert_eq!(unique.len(), 3);
    }

    #[test]
    fn all_models_have_valid_configs() {
        for model in EmbeddingModel::ALL {
            let cfg = model.config();
            assert!(!cfg.name.is_empty(), "`cfg.name` is empty");
            assert!(!cfg.hf_repo.is_empty(), "`cfg.hf_repo` is empty");
            assert!(cfg.dimensions > 0);
            assert!(cfg.max_seq_len > 0);
            assert!(cfg.model_min_bytes > 0);
            assert!(cfg.vocab_min_bytes > 0);
        }
    }

    #[test]
    fn model_urls_are_valid() {
        for model in EmbeddingModel::ALL {
            let cfg = model.config();
            let model_url = cfg.model_url();
            let vocab_url = cfg.vocab_url();
            assert!(model_url.starts_with("https://huggingface.co/"));
            assert!(vocab_url.starts_with("https://huggingface.co/"));
            // Pinned built-ins resolve their exact revision, the rest `main`.
            let rev = cfg.revision.as_deref().unwrap_or("main");
            assert!(
                model_url.contains(&format!("resolve/{rev}/")),
                "{model_url}"
            );
        }
    }

    #[test]
    fn storage_dir_names_are_unique() {
        let names: Vec<_> = EmbeddingModel::ALL
            .iter()
            .map(EmbeddingModel::storage_dir_name)
            .collect();
        let unique: std::collections::HashSet<_> = names.iter().collect();
        assert_eq!(names.len(), unique.len());
    }

    #[test]
    fn display_uses_model_name() {
        assert_eq!(
            format!("{}", EmbeddingModel::AllMiniLmL6V2),
            "all-MiniLM-L6-v2"
        );
        assert_eq!(
            format!("{}", EmbeddingModel::NomicEmbedV1_5),
            "nomic-embed-text-v1.5"
        );
    }

    #[test]
    fn resolve_defaults_when_nothing_set() {
        assert_eq!(
            resolve_model_from(None, None, None),
            EmbeddingModel::DEFAULT
        );
        assert_eq!(
            resolve_model_from(Some(""), Some("   "), None),
            EmbeddingModel::DEFAULT
        );
    }

    #[test]
    fn config_selects_model_when_env_unset() {
        assert_eq!(
            resolve_model_from(None, Some("nomic"), None),
            EmbeddingModel::NomicEmbedV1_5
        );
        assert_eq!(
            resolve_model_from(None, Some("minilm"), None),
            EmbeddingModel::AllMiniLmL6V2
        );
    }

    #[test]
    fn resolution_reports_the_setting_that_won() {
        assert_eq!(
            resolve_model_with_source_from(
                Some(" nomic "),
                Some("minilm"),
                None,
                EmbeddingModel::DEFAULT
            )
            .1,
            ModelSource::Env("nomic".into())
        );
        assert_eq!(
            resolve_model_with_source_from(
                Some("bogus"),
                Some("nomic"),
                None,
                EmbeddingModel::DEFAULT
            )
            .1,
            ModelSource::Config("nomic".into())
        );
        assert_eq!(
            resolve_model_with_source_from(None, Some("nope"), None, EmbeddingModel::DEFAULT).1,
            ModelSource::Default
        );
    }

    #[test]
    fn env_var_overrides_config() {
        assert_eq!(
            resolve_model_from(Some("minilm"), Some("nomic"), None),
            EmbeddingModel::AllMiniLmL6V2
        );
    }

    #[test]
    fn unknown_name_falls_through_then_defaults() {
        // Bad env value → valid config value wins.
        assert_eq!(
            resolve_model_from(Some("bogus"), Some("nomic"), None),
            EmbeddingModel::NomicEmbedV1_5
        );
        // Bad everywhere → default (never silently breaks the index).
        assert_eq!(
            resolve_model_from(Some("bogus"), Some("nope"), None),
            EmbeddingModel::DEFAULT
        );
        // Empty/whitespace in the higher-priority source is skipped, not treated as a match.
        assert_eq!(
            resolve_model_from(Some("   "), Some("nomic"), None),
            EmbeddingModel::NomicEmbedV1_5
        );
    }

    #[test]
    fn resolve_custom_picks_up_config_dimensions() {
        let m = resolve_model_from(None, Some("hf:org/model@pin"), Some(1024));
        let EmbeddingModel::Custom(spec) = m else {
            panic!("expected custom")
        };
        assert_eq!(spec.dimensions, Some(1024));
        assert_eq!(spec.revision.as_deref(), Some("pin"));
    }

    #[test]
    fn nomic_has_prefixes() {
        let cfg = EmbeddingModel::NomicEmbedV1_5.config();
        assert!(cfg.query_prefix.is_some());
        assert!(cfg.document_prefix.is_some());
        assert!(!cfg.needs_token_type_ids);
    }

    #[test]
    fn minilm_is_wordpiece() {
        let cfg = EmbeddingModel::AllMiniLmL6V2.config();
        assert!(cfg.vocab_file.is_wordpiece());
    }

    #[test]
    fn builtin_models_have_valid_vocab_sources() {
        // ONNX built-ins are BERT WordPiece (vocab.txt) models; the static
        // model2vec built-in ships its WordPiece vocabulary as tokenizer.json.
        for model in EmbeddingModel::ALL {
            let cfg = model.config();
            match cfg.format {
                ModelFormat::Onnx => assert!(
                    cfg.vocab_file.is_wordpiece(),
                    "{model} should use WordPiece vocab.txt"
                ),
                ModelFormat::StaticSafetensors => assert_eq!(
                    cfg.vocab_file.filename(),
                    "tokenizer.json",
                    "{model} ships tokenizer.json"
                ),
            }
        }
    }

    #[test]
    fn custom_models_use_tokenizer_json() {
        let m = EmbeddingModel::from_str_name("hf:org/model").unwrap();
        assert!(!m.config().vocab_file.is_wordpiece());
        assert_eq!(m.config().vocab_file.filename(), "tokenizer.json");
    }
}