llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
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
//! Local OCI layout types and read/write helpers — a Rust equivalent of
//! go-shim/shared_oci.go's blob helpers and manifest_ref.go, plus the
//! CNCF ModelPack manifest construction the Go shim's own (since
//! deleted) `buildCNCFManifest` used to do.
//!
//! Writes the exact same on-disk format Go's `push`/`inspect` and
//! `crate::storage`'s `build`/`tag`/`list`/`run`/`serve` already read
//! and write (content-addressed `blobs/<alg>/<hex>`, `manifests-v2/<repo>/<tag>.json`
//! pointer files, `oci-layout`) — a from-scratch equivalent, not a
//! replacement, so a native pull never needs to call into Go.
//!
//! Shared with `crate::sources`, which stores the ModelScope/NGC/S3/GCS/
//! local-directory sources in exactly this format too.

use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};

// ---------------------------------------------------------------------------
// OCI image-spec types — just enough of the public spec to round-trip
// what this codebase actually produces/reads (mirrors
// opencontainers/image-spec's Go structs field-for-field).
// ---------------------------------------------------------------------------

pub const MEDIA_TYPE_IMAGE_MANIFEST: &str = "application/vnd.oci.image.manifest.v1+json";
pub const ANNOTATION_REF_NAME: &str = "org.opencontainers.image.ref.name";
pub const ANNOTATION_TITLE: &str = "org.opencontainers.image.title";

/// Matches `ocispec.Descriptor`'s JSON shape exactly.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Descriptor {
    #[serde(rename = "mediaType")]
    pub media_type: String,
    pub digest: String,
    pub size: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub urls: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,
    #[serde(
        rename = "artifactType",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub artifact_type: Option<String>,
}

impl Descriptor {
    pub fn annotation(&self, key: &str) -> Option<&str> {
        self.annotations.as_ref()?.get(key).map(String::as_str)
    }
}

/// Matches `ocispec.Manifest`'s JSON shape exactly.
#[derive(Debug, Serialize, Deserialize)]
pub struct Manifest {
    #[serde(rename = "schemaVersion")]
    pub schema_version: i32,
    #[serde(rename = "mediaType")]
    pub media_type: String,
    #[serde(
        rename = "artifactType",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub artifact_type: Option<String>,
    pub config: Descriptor,
    pub layers: Vec<Descriptor>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<BTreeMap<String, String>>,
}

// ---------------------------------------------------------------------------
// CNCF ModelPack config (github.com/modelpack/model-spec) — just the
// fields buildCNCFManifest actually populates.
// ---------------------------------------------------------------------------

pub const ARTIFACT_TYPE_MODEL_MANIFEST: &str = "application/vnd.cncf.model.manifest.v1+json";
pub const MEDIA_TYPE_MODEL_CONFIG: &str = "application/vnd.cncf.model.config.v1+json";
pub const MEDIA_TYPE_MODEL_WEIGHT_RAW: &str = "application/vnd.cncf.model.weight.v1.raw";
pub const MEDIA_TYPE_MODEL_WEIGHT_CONFIG_RAW: &str =
    "application/vnd.cncf.model.weight.config.v1.raw";
pub const MEDIA_TYPE_MODEL_DOC_RAW: &str = "application/vnd.cncf.model.doc.v1.raw";
/// Inference/handler scripts shipped alongside the weights. Only
/// `crate::sources` produces these — a HuggingFace repo's `.py` files
/// aren't among the ones `select_downloadable_hf_files` fetches.
pub const MEDIA_TYPE_MODEL_CODE_RAW: &str = "application/vnd.cncf.model.code.v1.raw";
pub const ANNOTATION_FILEPATH: &str = "org.cncf.model.filepath";

#[derive(Serialize, Default)]
struct ModelDescriptor {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    licenses: Vec<String>,
    /// The source control revision the weights were taken from (the Hub
    /// commit sha for a HuggingFace pull); CNCF model-spec `descriptor.revision`.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    revision: String,
}

#[derive(Serialize)]
struct ModelFS {
    #[serde(rename = "type")]
    kind: String,
    #[serde(rename = "diffIds")]
    diff_ids: Vec<String>,
}

#[derive(Serialize, Default)]
struct ModelCapabilities {
    #[serde(rename = "inputTypes", default, skip_serializing_if = "Vec::is_empty")]
    input_types: Vec<&'static str>,
    #[serde(rename = "outputTypes", default, skip_serializing_if = "Vec::is_empty")]
    output_types: Vec<&'static str>,
}

#[derive(Serialize, Default)]
struct ModelConfig {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    format: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    capabilities: Option<ModelCapabilities>,
}

#[derive(Serialize)]
struct Model {
    #[serde(rename = "descriptor")]
    descriptor: ModelDescriptor,
    modelfs: ModelFS,
    #[serde(default, skip_serializing_if = "is_default_config")]
    config: ModelConfig,
}

fn is_default_config(c: &ModelConfig) -> bool {
    c.format.is_empty() && c.capabilities.is_none()
}

/// Mirrors `modelMeta` in hf.go: the optional-but-valuable metadata
/// `build_cncf_manifest` populates beyond the bare config.format+modelfs.
#[derive(Default)]
pub struct ModelMeta {
    pub format: String,
    pub licenses: Vec<String>,
    pub vision: bool,
    /// A latent diffusion model: generates media instead of text. The
    /// listed output types (`"image"`, `"video"`, `"audio"`) become the
    /// model's capabilities.
    pub diffusion_outputs: Vec<&'static str>,
}

/// Layer annotation naming the part a sidecar plays in a diffusion
/// model: `"vae"`, `"audio_vae"`, `"text_proj"` or `"text_encoder"`.
/// Layers without it are the model itself (plus mmproj / license).
pub const ANNOTATION_ROLE: &str = "org.llmman.role";

/// Manifest annotation carrying the same source revision as the config's
/// `descriptor.revision`, so `llmman show` surfaces it without reading
/// the config blob.
pub const ANNOTATION_REVISION: &str = "org.llmman.revision";

/// Builds a conformant CNCF model-spec config blob and manifest
/// referencing `layers`, writing each into `layout_dir`, and returns the
/// manifest's descriptor. `filepath_annotation` sets the manifest-level
/// `org.cncf.model.filepath` annotation for the single-weight-file case
/// (GGUF); pass `""` for the multi-layer safetensors case. `commit` is
/// the source revision recorded as `descriptor.revision` and the
/// `org.llmman.revision` annotation; pass `""` when the source has none.
pub fn build_cncf_manifest(
    layout_dir: &Path,
    meta: &ModelMeta,
    model_repo: &str,
    filepath_annotation: &str,
    commit: &str,
    layers: Vec<Descriptor>,
) -> Result<Descriptor> {
    let model = Model {
        descriptor: ModelDescriptor {
            licenses: meta.licenses.clone(),
            revision: commit.to_string(),
        },
        modelfs: ModelFS {
            kind: "layers".to_string(),
            diff_ids: layers.iter().map(|l| l.digest.clone()).collect(),
        },
        config: ModelConfig {
            format: meta.format.clone(),
            capabilities: if !meta.diffusion_outputs.is_empty() {
                Some(ModelCapabilities {
                    input_types: vec!["text"],
                    output_types: meta.diffusion_outputs.clone(),
                })
            } else {
                meta.vision.then(|| ModelCapabilities {
                    input_types: vec!["text", "image"],
                    output_types: vec!["text"],
                })
            },
        },
    };
    let cfg_data = serde_json::to_vec(&model).context("marshal CNCF model config")?;
    let config_desc = write_blob(layout_dir, MEDIA_TYPE_MODEL_CONFIG, &cfg_data)
        .context("store CNCF model config")?;

    let mut annotations = BTreeMap::new();
    annotations.insert("ai.model.repo".to_string(), model_repo.to_string());
    if !filepath_annotation.is_empty() {
        annotations.insert(
            ANNOTATION_FILEPATH.to_string(),
            filepath_annotation.to_string(),
        );
    }
    if !commit.is_empty() {
        annotations.insert(ANNOTATION_REVISION.to_string(), commit.to_string());
    }
    let manifest = Manifest {
        schema_version: 2,
        media_type: MEDIA_TYPE_IMAGE_MANIFEST.to_string(),
        artifact_type: Some(ARTIFACT_TYPE_MODEL_MANIFEST.to_string()),
        config: config_desc,
        layers,
        annotations: Some(annotations),
    };
    let manifest_data = serde_json::to_vec(&manifest).context("marshal CNCF manifest")?;
    write_blob(layout_dir, MEDIA_TYPE_IMAGE_MANIFEST, &manifest_data).context("store CNCF manifest")
}

// ---------------------------------------------------------------------------
// Blob storage — mirrors shared_oci.go's blobPath/readBlob/writeBlob/
// writeBlobStream/blobExists.
// ---------------------------------------------------------------------------

/// Process-wide, so no two temp paths written here can ever collide.
fn next_counter() -> u64 {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

fn digest_to_path(layout_dir: &Path, digest: &str) -> Result<PathBuf> {
    let (alg, hex) = digest
        .split_once(':')
        .with_context(|| format!("malformed digest {digest:?}"))?;
    Ok(layout_dir.join("blobs").join(alg).join(hex))
}

pub fn blob_exists(layout_dir: &Path, desc: &Descriptor) -> bool {
    match digest_to_path(layout_dir, &desc.digest) {
        Ok(p) => std::fs::metadata(&p)
            .map(|m| m.len() as i64 == desc.size)
            .unwrap_or(false),
        Err(_) => false,
    }
}

pub fn read_blob(layout_dir: &Path, digest: &str) -> Result<Vec<u8>> {
    std::fs::read(digest_to_path(layout_dir, digest)?).context("read blob")
}

/// Atomically writes `data` to the layout's blobs directory, keyed by its
/// own sha256 — mirrors `writeBlob`.
pub fn write_blob(layout_dir: &Path, media_type: &str, data: &[u8]) -> Result<Descriptor> {
    let digest = format!("sha256:{:x}", Sha256::digest(data));
    let dir = layout_dir.join("blobs").join("sha256");
    std::fs::create_dir_all(&dir)?;
    let dest = dir.join(digest.trim_start_matches("sha256:"));
    if let Ok(m) = std::fs::metadata(&dest) {
        if m.len() as usize == data.len() {
            return Ok(Descriptor {
                media_type: media_type.to_string(),
                digest,
                size: data.len() as i64,
                ..Default::default()
            });
        }
    }
    // A counter, not a name derived from the digest: two concurrent
    // writes of byte-identical content (same digest) would otherwise
    // share a tmp path and could truncate each other mid-write.
    let tmp = dir.join(format!("{}-{}.tmp", std::process::id(), next_counter()));
    {
        let mut f = std::fs::File::create(&tmp)?;
        f.write_all(data)?;
    }
    std::fs::rename(&tmp, &dest)?;
    Ok(Descriptor {
        media_type: media_type.to_string(),
        digest,
        size: data.len() as i64,
        ..Default::default()
    })
}

/// Stores a file already on local disk as a blob, hashing a chunk at a
/// time rather than reading it whole into memory — the input here is a
/// multi-gigabyte safetensors shard.
///
/// `consume` moves the file in (a temp file this process owns and that
/// nothing else can be writing). Otherwise it is copied and hashed in
/// one pass into a temp file, so the bytes stored under the returned
/// digest are the exact bytes that were hashed even if the caller's own
/// file changes underneath; either way that file is left untouched.
///
/// A file whose digest is already stored costs nothing to re-offer, so
/// the caller still owns any staging file after this returns.
pub fn write_blob_from_file(
    layout_dir: &Path,
    media_type: &str,
    path: &Path,
    consume: bool,
) -> Result<Descriptor> {
    let dir = layout_dir.join("blobs").join("sha256");
    std::fs::create_dir_all(&dir)?;
    let tmp = dir.join(format!("{}-{}.tmp", std::process::id(), next_counter()));
    let mut source =
        std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;

    // Owning the file means nobody else is writing it, so hashing it
    // where it lies and then renaming is safe — and free.
    let ((size, hex), staged) = if consume {
        let hashed = crate::fsutil::copy_hashing(&mut source, &mut std::io::sink())
            .with_context(|| format!("hash {}", path.display()))?;
        (hashed, path.to_path_buf())
    } else {
        let mut out = std::fs::File::create(&tmp)?;
        let copied = crate::fsutil::copy_hashing(&mut source, &mut out)
            .with_context(|| format!("copy {} into the blob store", path.display()));
        // Closed before the remove below: Windows refuses to delete an
        // open file.
        drop(out);
        match copied {
            Ok(copied) => (copied, tmp.clone()),
            Err(e) => {
                let _ = std::fs::remove_file(&tmp);
                return Err(e);
            }
        }
    };
    drop(source);
    let digest = format!("sha256:{hex}");
    let dest = dir.join(digest.trim_start_matches("sha256:"));

    // Content-addressed, so an existing blob of this digest already
    // holds exactly these bytes. Renaming (never writing to `dest`
    // directly) is what keeps a concurrent writer of the same digest
    // from ever seeing a half-written blob at its final path.
    if dest.exists() {
        // Reused: refresh its age so a concurrent sweep's grace window
        // covers it until the caller's manifest or tag lands.
        let _ = std::fs::OpenOptions::new()
            .write(true)
            .open(&dest)
            .and_then(|f| f.set_modified(std::time::SystemTime::now()));
    } else {
        match std::fs::rename(&staged, &dest) {
            Ok(()) => {}
            // A sibling won the race and published the identical blob
            // first; POSIX overwrites silently, Windows errors.
            Err(_) if dest.exists() => {}
            Err(e) => {
                if !consume {
                    let _ = std::fs::remove_file(&tmp);
                }
                return Err(e).with_context(|| format!("publish blob for {}", path.display()));
            }
        }
    }
    if !consume {
        let _ = std::fs::remove_file(&tmp);
    }
    Ok(Descriptor {
        media_type: media_type.to_string(),
        digest,
        size: size as i64,
        ..Default::default()
    })
}

// ---------------------------------------------------------------------------
// Manifest-ref bookkeeping — mirrors manifest_ref.go.
// ---------------------------------------------------------------------------

fn manifest_ref_path(layout_dir: &Path, reference: &str) -> PathBuf {
    crate::storage::oci::manifest_ref_path(layout_dir, reference)
}

pub fn read_manifest_ref(layout_dir: &Path, reference: &str) -> Result<Descriptor> {
    for (i, path) in [
        manifest_ref_path(layout_dir, reference),
        crate::storage::oci::legacy_manifest_ref_path(layout_dir, reference),
    ]
    .into_iter()
    .enumerate()
    {
        match std::fs::read(path) {
            Ok(data) => {
                let desc: Descriptor = serde_json::from_slice(&data)?;
                if desc
                    .annotations
                    .as_ref()
                    .and_then(|ann| ann.get(ANNOTATION_REF_NAME))
                    .is_some_and(|name| {
                        crate::storage::default_tag(name) == crate::storage::default_tag(reference)
                    })
                {
                    return Ok(desc);
                }
            }
            Err(err)
                if err.kind() == std::io::ErrorKind::NotFound
                    || (i == 1 && crate::storage::oci::missing_legacy_ref(&err)) =>
            {
                continue
            }
            Err(err) => return Err(err.into()),
        }
    }
    Err(std::io::Error::from(std::io::ErrorKind::NotFound).into())
}

/// Atomically records that `reference` now points at `manifest_desc` —
/// mirrors `writeManifestRef`.
pub fn write_manifest_ref(
    layout_dir: &Path,
    reference: &str,
    mut manifest_desc: Descriptor,
) -> Result<()> {
    let mut ann = manifest_desc.annotations.clone().unwrap_or_default();
    ann.insert(ANNOTATION_REF_NAME.to_string(), reference.to_string());
    manifest_desc.annotations = Some(ann);

    let path = manifest_ref_path(layout_dir, reference);
    let dir = path.parent().context("manifest ref path has no parent")?;
    std::fs::create_dir_all(dir)?;
    let data = serde_json::to_vec_pretty(&manifest_desc)?;

    let tmp = dir.join(format!(
        "{}.{}-{}.tmp",
        path.file_name().unwrap().to_string_lossy(),
        std::process::id(),
        next_counter()
    ));
    std::fs::write(&tmp, &data)?;
    std::fs::rename(&tmp, &path)?;
    Ok(())
}

/// Records `alias` as a second name for whatever `reference` already
/// points at. Needed when staging a pull into a throwaway layout that is
/// then pushed under a *different* reference: `llmman_push` resolves the
/// manifest by an exact ref lookup, so the staged model has to be
/// findable under the destination's own name.
pub fn alias_manifest_ref(layout_dir: &Path, reference: &str, alias: &str) -> Result<()> {
    if alias == reference {
        return Ok(());
    }
    let desc = read_manifest_ref(layout_dir, reference)
        .with_context(|| format!("read staged manifest for {reference}"))?;
    write_manifest_ref(layout_dir, alias, desc)
}

/// Initializes the OCI layout marker files and `manifests-v2/` directory if
/// not already present — mirrors `ensureLayout`. The legacy tree is read-only.
pub fn ensure_layout(layout_dir: &Path) -> Result<()> {
    std::fs::create_dir_all(layout_dir)?;
    std::fs::create_dir_all(layout_dir.join("manifests-v2"))?;
    let marker = layout_dir.join("oci-layout");
    if !marker.exists() {
        std::fs::write(marker, br#"{"imageLayoutVersion":"1.0.0"}"#)?;
    }
    Ok(())
}

/// Returns the cached layer's filename if `reference` is already fully
/// cached in `layout_dir` (manifest blob + every layer blob present), or
/// `None` — mirrors `cachedLayerName`.
pub fn cached_layer_name(layout_dir: &Path, reference: &str) -> Option<String> {
    let m = read_manifest_ref(layout_dir, reference).ok()?;
    if !blob_exists(layout_dir, &m) {
        return None;
    }
    let data = read_blob(layout_dir, &m.digest).ok()?;
    let manifest: Manifest = serde_json::from_slice(&data).ok()?;
    for layer in &manifest.layers {
        if !blob_exists(layout_dir, layer) {
            return None;
        }
    }
    if let Some(layer) = manifest.layers.first() {
        for key in [ANNOTATION_FILEPATH, ANNOTATION_TITLE] {
            if let Some(name) = layer.annotation(key) {
                if !name.is_empty() {
                    return Path::new(name)
                        .file_name()
                        .map(|f| f.to_string_lossy().into_owned());
                }
            }
        }
    }
    Some(reference.to_string())
}

/// Prints "Cached &lt;label&gt;" and returns true if `reference` is
/// already fully cached — mirrors `reportCached`.
pub fn report_cached(layout_dir: &Path, reference: &str) -> bool {
    match cached_layer_name(layout_dir, reference) {
        Some(name) => {
            eprintln!("Cached   {name}");
            true
        }
        None => false,
    }
}

/// The stored manifest and config blob of `reference` in `layout_dir`.
#[cfg(test)]
pub(crate) fn read_manifest_and_config(
    layout_dir: &Path,
    reference: &str,
) -> (Manifest, serde_json::Value) {
    let desc = read_manifest_ref(layout_dir, reference).unwrap();
    let manifest: Manifest =
        serde_json::from_slice(&read_blob(layout_dir, &desc.digest).unwrap()).unwrap();
    let config: serde_json::Value =
        serde_json::from_slice(&read_blob(layout_dir, &manifest.config.digest).unwrap()).unwrap();
    (manifest, config)
}

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

    #[test]
    fn staged_manifest_is_visible_to_local_store() {
        let dir = tempfile();
        let reference = "reg.example:5000/ns/model:t";
        let desc = Descriptor {
            media_type: MEDIA_TYPE_IMAGE_MANIFEST.into(),
            digest: "sha256:deadbeef".into(),
            size: 12,
            ..Default::default()
        };
        write_manifest_ref(&dir, reference, desc).unwrap();
        let store = crate::storage::oci::OciStore::open(&dir).unwrap();
        assert_eq!(store.find(reference).unwrap().digest, "sha256:deadbeef");
    }

    #[test]
    fn write_blob_then_read_blob_round_trips() {
        let dir = tempfile();
        let desc = write_blob(&dir, "text/plain", b"hello world").unwrap();
        assert_eq!(desc.size, 11);
        assert!(blob_exists(&dir, &desc));
        assert_eq!(read_blob(&dir, &desc.digest).unwrap(), b"hello world");
    }

    #[test]
    fn write_blob_from_file_moves_a_file_it_owns_and_copies_one_it_does_not() {
        let dir = tempfile();
        let src = dir.join("weights.safetensors");
        std::fs::write(&src, b"weights").unwrap();

        let copied = write_blob_from_file(&dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, &src, false).unwrap();
        assert_eq!(copied.size, 7);
        assert!(
            src.exists(),
            "consume=false must leave a user's own file alone"
        );
        assert_eq!(read_blob(&dir, &copied.digest).unwrap(), b"weights");

        // Same content, so the blob already exists and nothing is
        // written — but the caller still owns the staging file.
        let staged = dir.join("staged.part");
        std::fs::write(&staged, b"weights").unwrap();
        let moved = write_blob_from_file(&dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, &staged, true).unwrap();
        assert_eq!(moved.digest, copied.digest);

        // Distinct content: consume=true really does move it away.
        let staged2 = dir.join("staged2.part");
        std::fs::write(&staged2, b"other weights").unwrap();
        let moved2 =
            write_blob_from_file(&dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, &staged2, true).unwrap();
        assert!(!staged2.exists(), "consume=true must move, not copy");
        assert_eq!(read_blob(&dir, &moved2.digest).unwrap(), b"other weights");

        std::fs::remove_dir_all(&dir).ok();
    }

    /// A directory opens on Unix but fails to read, which is a copy that
    /// dies after the staging file exists.
    #[cfg(unix)]
    #[test]
    fn write_blob_from_file_leaves_no_staging_file_when_the_copy_fails() {
        let dir = tempfile();
        let src = dir.join("not-a-file");
        std::fs::create_dir_all(&src).unwrap();

        write_blob_from_file(&dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, &src, false).unwrap_err();

        let leftovers: Vec<_> = std::fs::read_dir(dir.join("blobs").join("sha256"))
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn alias_manifest_ref_makes_a_staged_pull_findable_under_another_name() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let desc = Descriptor {
            media_type: MEDIA_TYPE_IMAGE_MANIFEST.to_string(),
            digest: "sha256:abc".to_string(),
            size: 3,
            ..Default::default()
        };
        write_manifest_ref(&dir, "s3://bucket/model:latest", desc).unwrap();
        alias_manifest_ref(&dir, "s3://bucket/model:latest", "ghcr.io/me/model:v1").unwrap();
        assert_eq!(
            read_manifest_ref(&dir, "ghcr.io/me/model:v1")
                .unwrap()
                .digest,
            "sha256:abc"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn write_blob_is_idempotent() {
        let dir = tempfile();
        let d1 = write_blob(&dir, "text/plain", b"same content").unwrap();
        let d2 = write_blob(&dir, "text/plain", b"same content").unwrap();
        assert_eq!(d1.digest, d2.digest);
    }

    #[test]
    fn manifest_ref_round_trips_and_records_ref_name_annotation() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let desc = Descriptor {
            media_type: MEDIA_TYPE_IMAGE_MANIFEST.to_string(),
            digest: "sha256:abc".to_string(),
            size: 3,
            ..Default::default()
        };
        write_manifest_ref(&dir, "owner/repo:tag", desc).unwrap();
        let got = read_manifest_ref(&dir, "owner/repo:tag").unwrap();
        assert_eq!(got.annotation(ANNOTATION_REF_NAME), Some("owner/repo:tag"));
    }

    #[test]
    fn legacy_ancestor_file_does_not_block_staged_ref() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let reference = "reg.example/ns/model/sub:t";
        let ancestor =
            crate::storage::oci::legacy_manifest_ref_path(&dir, "reg.example/ns/model:sub");
        std::fs::create_dir_all(ancestor.parent().unwrap()).unwrap();
        std::fs::write(&ancestor, b"another pointer").unwrap();
        assert!(read_manifest_ref(&dir, reference).is_err());

        let desc = Descriptor {
            digest: "sha256:abc".into(),
            ..Default::default()
        };
        write_manifest_ref(&dir, reference, desc).unwrap();
        assert_eq!(
            read_manifest_ref(&dir, reference).unwrap().digest,
            "sha256:abc"
        );
        assert_eq!(std::fs::read(&ancestor).unwrap(), b"another pointer");
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn long_opaque_key_ignores_unrepresentable_legacy_pointer() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let reference = format!("s3://bucket/{}", "a".repeat(256));
        let legacy = crate::storage::oci::legacy_manifest_ref_path(&dir, &reference);
        std::fs::create_dir_all(legacy.parent().unwrap().parent().unwrap()).unwrap();
        assert!(read_manifest_ref(&dir, &reference).is_err());
        write_manifest_ref(
            &dir,
            &reference,
            Descriptor {
                digest: "sha256:abc".into(),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            read_manifest_ref(&dir, &reference).unwrap().digest,
            "sha256:abc"
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn cached_layer_name_is_none_when_nothing_cached() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        assert!(cached_layer_name(&dir, "owner/repo:tag").is_none());
    }

    #[test]
    fn cached_layer_name_returns_filename_once_fully_cached() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let layer = write_blob(&dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, b"weights").unwrap();
        let mut layer = layer;
        layer.annotations = Some(BTreeMap::from([(
            ANNOTATION_FILEPATH.to_string(),
            "model.gguf".to_string(),
        )]));
        let manifest_desc = build_cncf_manifest(
            &dir,
            &ModelMeta {
                format: "gguf".to_string(),
                ..Default::default()
            },
            "owner/repo",
            "model.gguf",
            "",
            vec![layer],
        )
        .unwrap();
        write_manifest_ref(&dir, "owner/repo:tag", manifest_desc).unwrap();
        assert_eq!(
            cached_layer_name(&dir, "owner/repo:tag").as_deref(),
            Some("model.gguf")
        );
    }

    fn manifest_and_config(dir: &Path, commit: &str) -> (Manifest, serde_json::Value) {
        let layer = write_blob(dir, MEDIA_TYPE_MODEL_WEIGHT_RAW, b"weights").unwrap();
        let desc = build_cncf_manifest(
            dir,
            &ModelMeta {
                format: "gguf".to_string(),
                ..Default::default()
            },
            "owner/repo",
            "model.gguf",
            commit,
            vec![layer],
        )
        .unwrap();
        write_manifest_ref(dir, "owner/repo:tag", desc).unwrap();
        read_manifest_and_config(dir, "owner/repo:tag")
    }

    #[test]
    fn build_cncf_manifest_records_the_commit_in_config_and_annotation() {
        let dir = tempfile();
        ensure_layout(&dir).unwrap();
        let commit = "7ae557604adf67be50417f59c2c2f167def9a775";

        let (manifest, config) = manifest_and_config(&dir, commit);
        assert_eq!(config["descriptor"]["revision"], commit);
        assert_eq!(
            manifest.annotations.as_ref().unwrap()[ANNOTATION_REVISION],
            commit
        );

        let (manifest, config) = manifest_and_config(&dir, "");
        assert!(config["descriptor"].get("revision").is_none());
        assert!(!manifest
            .annotations
            .as_ref()
            .unwrap()
            .contains_key(ANNOTATION_REVISION));
        std::fs::remove_dir_all(dir).unwrap();
    }

    fn tempfile() -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "llmman-oci-test-{}-{}",
            std::process::id(),
            rand_suffix()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn rand_suffix() -> u64 {
        use std::time::{SystemTime, UNIX_EPOCH};
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos() as u64
    }
}