assay-registry 2.18.0

Pack registry client for remote pack distribution (SPEC-Pack-Registry-v1)
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! Lockfile support for reproducible builds.
//!
//! The lockfile (`assay.packs.lock`) records exact pack versions and digests
//! to ensure reproducible builds across machines and CI runs.
//!
//! # Lockfile Format (v2)
//!
//! ```yaml
//! version: 2
//! generated_at: "2026-01-29T10:00:00Z"
//! generated_by: "assay-cli/2.10.1"
//! packs:
//!   - name: eu-ai-act-pro
//!     version: "1.2.0"
//!     digest: sha256:abc123...
//!     source: registry
//!     registry_url: "https://registry.getassay.dev/v1"
//!     signature:
//!       algorithm: Ed25519
//!       key_id: sha256:def456...
//! ```

use std::path::Path;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::fs;
use tracing::{debug, info, warn};

use crate::error::{RegistryError, RegistryResult};
use crate::reference::PackRef;
use crate::resolver::{PackResolver, ResolveSource};

/// Default lockfile name.
pub const LOCKFILE_NAME: &str = "assay.packs.lock";

/// Current lockfile schema version.
pub const LOCKFILE_VERSION: u8 = 2;

/// A pack lockfile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lockfile {
    /// Schema version.
    pub version: u8,

    /// When the lockfile was generated.
    pub generated_at: DateTime<Utc>,

    /// Tool that generated the lockfile.
    pub generated_by: String,

    /// Locked packs.
    #[serde(default)]
    pub packs: Vec<LockedPack>,
}

/// A locked pack entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockedPack {
    /// Pack name.
    pub name: String,

    /// Pack version.
    pub version: String,

    /// Content digest (sha256:...).
    pub digest: String,

    /// Source type.
    pub source: LockSource,

    /// Registry URL (if source is registry).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry_url: Option<String>,

    /// BYOS URL (if source is byos).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub byos_url: Option<String>,

    /// Signature information (if signed).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<LockSignature>,
}

/// Source type for locked packs.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LockSource {
    /// Bundled pack.
    Bundled,

    /// Registry pack.
    Registry,

    /// BYOS pack.
    Byos,

    /// Local file (not recommended for lockfiles).
    Local,
}

/// Signature information.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockSignature {
    /// Signature algorithm.
    pub algorithm: String,

    /// Key ID used for signing.
    pub key_id: String,
}

/// Lockfile verification result.
#[derive(Debug, Clone)]
pub struct VerifyLockResult {
    /// Whether all packs match.
    pub all_match: bool,

    /// Packs that matched.
    pub matched: Vec<String>,

    /// Packs with digest mismatches.
    pub mismatched: Vec<LockMismatch>,

    /// Packs in lockfile but not resolved.
    pub missing: Vec<String>,

    /// Packs resolved but not in lockfile.
    pub extra: Vec<String>,
}

/// A lockfile mismatch.
#[derive(Debug, Clone)]
pub struct LockMismatch {
    /// Pack name.
    pub name: String,

    /// Pack version.
    pub version: String,

    /// Expected digest from lockfile.
    pub expected: String,

    /// Actual digest from resolution.
    pub actual: String,
}

impl Lockfile {
    /// Create a new empty lockfile.
    pub fn new() -> Self {
        Self {
            version: LOCKFILE_VERSION,
            generated_at: Utc::now(),
            generated_by: format!("assay-cli/{}", env!("CARGO_PKG_VERSION")),
            packs: Vec::new(),
        }
    }

    /// Load a lockfile from a path.
    pub async fn load(path: impl AsRef<Path>) -> RegistryResult<Self> {
        let path = path.as_ref();

        if !path.exists() {
            return Err(RegistryError::Lockfile {
                message: format!("lockfile not found: {}", path.display()),
            });
        }

        let content = fs::read_to_string(path)
            .await
            .map_err(|e| RegistryError::Lockfile {
                message: format!("failed to read lockfile: {}", e),
            })?;

        Self::parse(&content)
    }

    /// Parse a lockfile from YAML content.
    pub fn parse(content: &str) -> RegistryResult<Self> {
        let lockfile: Lockfile =
            serde_yaml::from_str(content).map_err(|e| RegistryError::Lockfile {
                message: format!("failed to parse lockfile: {}", e),
            })?;

        // Validate version
        if lockfile.version > LOCKFILE_VERSION {
            return Err(RegistryError::Lockfile {
                message: format!(
                    "lockfile version {} is newer than supported version {}",
                    lockfile.version, LOCKFILE_VERSION
                ),
            });
        }

        Ok(lockfile)
    }

    /// Save the lockfile to a path.
    pub async fn save(&self, path: impl AsRef<Path>) -> RegistryResult<()> {
        let path = path.as_ref();
        let content = self.to_yaml()?;

        fs::write(path, content)
            .await
            .map_err(|e| RegistryError::Lockfile {
                message: format!("failed to write lockfile: {}", e),
            })?;

        info!(path = %path.display(), "saved lockfile");
        Ok(())
    }

    /// Convert to YAML string.
    pub fn to_yaml(&self) -> RegistryResult<String> {
        serde_yaml::to_string(self).map_err(|e| RegistryError::Lockfile {
            message: format!("failed to serialize lockfile: {}", e),
        })
    }

    /// Add or update a pack in the lockfile.
    pub fn add_pack(&mut self, pack: LockedPack) {
        // Remove existing entry with same name
        self.packs.retain(|p| p.name != pack.name);
        self.packs.push(pack);

        // Keep sorted by name
        self.packs.sort_by(|a, b| a.name.cmp(&b.name));

        // Update timestamp
        self.generated_at = Utc::now();
    }

    /// Remove a pack from the lockfile.
    pub fn remove_pack(&mut self, name: &str) -> bool {
        let len_before = self.packs.len();
        self.packs.retain(|p| p.name != name);
        self.packs.len() != len_before
    }

    /// Get a locked pack by name.
    pub fn get_pack(&self, name: &str) -> Option<&LockedPack> {
        self.packs.iter().find(|p| p.name == name)
    }

    /// Check if a pack is locked.
    pub fn contains(&self, name: &str) -> bool {
        self.packs.iter().any(|p| p.name == name)
    }

    /// Get all pack names.
    pub fn pack_names(&self) -> Vec<&str> {
        self.packs.iter().map(|p| p.name.as_str()).collect()
    }
}

impl Default for Lockfile {
    fn default() -> Self {
        Self::new()
    }
}

/// Generate a lockfile from pack references.
pub async fn generate_lockfile(
    references: &[String],
    resolver: &PackResolver,
) -> RegistryResult<Lockfile> {
    let mut lockfile = Lockfile::new();

    for reference in references {
        debug!(reference, "locking pack");

        let pack_ref = PackRef::parse(reference)?;
        let resolved = resolver.resolve_ref(&pack_ref).await?;

        let (name, version) = match &pack_ref {
            PackRef::Bundled(name) => (name.clone(), "bundled".to_string()),
            PackRef::Registry { name, version, .. } => (name.clone(), version.clone()),
            PackRef::Byos(url) => {
                // Extract name from URL
                let name = url
                    .rsplit('/')
                    .next()
                    .unwrap_or("unknown")
                    .trim_end_matches(".yaml")
                    .trim_end_matches(".yml")
                    .to_string();
                (name, "byos".to_string())
            }
            PackRef::Local(path) => {
                let name = path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("unknown")
                    .to_string();
                warn!(
                    path = %path.display(),
                    "locking local file - consider using registry or bundled packs instead"
                );
                (name, "local".to_string())
            }
        };

        let (source, registry_url, byos_url) = match &resolved.source {
            ResolveSource::Local(_) => (LockSource::Local, None, None),
            ResolveSource::Bundled(_) => (LockSource::Bundled, None, None),
            ResolveSource::Cache => (LockSource::Registry, None, None),
            ResolveSource::Registry(url) => (LockSource::Registry, Some(url.clone()), None),
            ResolveSource::Byos(url) => (LockSource::Byos, None, Some(url.clone())),
        };

        let signature = resolved.verification.as_ref().and_then(|v| {
            v.key_id.as_ref().map(|key_id| LockSignature {
                algorithm: "Ed25519".to_string(),
                key_id: key_id.clone(),
            })
        });

        let locked = LockedPack {
            name,
            version,
            digest: resolved.digest,
            source,
            registry_url,
            byos_url,
            signature,
        };

        lockfile.add_pack(locked);
    }

    Ok(lockfile)
}

/// Verify packs against a lockfile.
pub async fn verify_lockfile(
    lockfile: &Lockfile,
    resolver: &PackResolver,
) -> RegistryResult<VerifyLockResult> {
    let mut matched = Vec::new();
    let mut mismatched = Vec::new();
    let mut missing = Vec::new();

    for locked in &lockfile.packs {
        debug!(name = %locked.name, version = %locked.version, "verifying locked pack");

        // Build reference based on source
        let reference = match locked.source {
            LockSource::Bundled => locked.name.clone(),
            LockSource::Registry => {
                format!("{}@{}#{}", locked.name, locked.version, locked.digest)
            }
            LockSource::Byos => locked
                .byos_url
                .clone()
                .unwrap_or_else(|| locked.name.clone()),
            LockSource::Local => {
                warn!(
                    name = %locked.name,
                    "cannot verify local pack - skipping"
                );
                continue;
            }
        };

        match resolver.resolve(&reference).await {
            Ok(resolved) => {
                if resolved.digest == locked.digest {
                    matched.push(locked.name.clone());
                } else {
                    mismatched.push(LockMismatch {
                        name: locked.name.clone(),
                        version: locked.version.clone(),
                        expected: locked.digest.clone(),
                        actual: resolved.digest,
                    });
                }
            }
            Err(e) => {
                warn!(name = %locked.name, error = %e, "failed to resolve locked pack");
                missing.push(locked.name.clone());
            }
        }
    }

    let all_match = mismatched.is_empty() && missing.is_empty();

    Ok(VerifyLockResult {
        all_match,
        matched,
        mismatched,
        missing,
        extra: Vec::new(), // Would need resolved refs to compute
    })
}

/// Check if lockfile is outdated (any pack has newer version available).
pub async fn check_lockfile(
    lockfile: &Lockfile,
    resolver: &PackResolver,
) -> RegistryResult<Vec<LockMismatch>> {
    // For now, just verify digests match
    let result = verify_lockfile(lockfile, resolver).await?;

    if !result.all_match {
        return Err(RegistryError::Lockfile {
            message: format!(
                "lockfile verification failed: {} mismatched, {} missing",
                result.mismatched.len(),
                result.missing.len()
            ),
        });
    }

    Ok(result.mismatched)
}

/// Update a lockfile with latest versions.
pub async fn update_lockfile(
    lockfile: &mut Lockfile,
    resolver: &PackResolver,
) -> RegistryResult<Vec<String>> {
    let mut updated = Vec::new();

    for locked in &mut lockfile.packs {
        if locked.source != LockSource::Registry {
            continue;
        }

        debug!(name = %locked.name, version = %locked.version, "checking for updates");

        // Build reference without pinned digest to get latest
        let reference = format!("{}@{}", locked.name, locked.version);

        match resolver.resolve(&reference).await {
            Ok(resolved) => {
                if resolved.digest != locked.digest {
                    info!(
                        name = %locked.name,
                        old_digest = %locked.digest,
                        new_digest = %resolved.digest,
                        "updating locked digest"
                    );

                    locked.digest = resolved.digest;
                    updated.push(locked.name.clone());
                }
            }
            Err(e) => {
                warn!(name = %locked.name, error = %e, "failed to update pack");
            }
        }
    }

    if !updated.is_empty() {
        lockfile.generated_at = Utc::now();
    }

    Ok(updated)
}

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

    #[test]
    fn test_lockfile_new() {
        let lockfile = Lockfile::new();
        assert_eq!(lockfile.version, LOCKFILE_VERSION);
        assert!(lockfile.packs.is_empty());
    }

    #[test]
    fn test_lockfile_parse() {
        let yaml = r#"
version: 2
generated_at: "2026-01-29T10:00:00Z"
generated_by: "assay-cli/2.10.1"
packs:
  - name: eu-ai-act-pro
    version: "1.2.0"
    digest: sha256:abc123def456
    source: registry
    registry_url: "https://registry.getassay.dev/v1"
    signature:
      algorithm: Ed25519
      key_id: sha256:keyid123
"#;

        let lockfile = Lockfile::parse(yaml).unwrap();
        assert_eq!(lockfile.version, 2);
        assert_eq!(lockfile.packs.len(), 1);

        let pack = &lockfile.packs[0];
        assert_eq!(pack.name, "eu-ai-act-pro");
        assert_eq!(pack.version, "1.2.0");
        assert_eq!(pack.digest, "sha256:abc123def456");
        assert_eq!(pack.source, LockSource::Registry);
        assert!(pack.signature.is_some());
    }

    #[test]
    fn test_lockfile_parse_unsupported_version() {
        let yaml = r#"
version: 99
generated_at: "2026-01-29T10:00:00Z"
generated_by: "future-cli/9.0.0"
packs: []
"#;

        let result = Lockfile::parse(yaml);
        assert!(matches!(result, Err(RegistryError::Lockfile { .. })));
    }

    #[test]
    fn test_lockfile_add_pack() {
        let mut lockfile = Lockfile::new();

        let pack1 = LockedPack {
            name: "pack-b".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:bbb".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        let pack2 = LockedPack {
            name: "pack-a".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:aaa".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        lockfile.add_pack(pack1);
        lockfile.add_pack(pack2);

        // Should be sorted by name
        assert_eq!(lockfile.packs[0].name, "pack-a");
        assert_eq!(lockfile.packs[1].name, "pack-b");
    }

    #[test]
    fn test_lockfile_add_pack_update() {
        let mut lockfile = Lockfile::new();

        let pack1 = LockedPack {
            name: "my-pack".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:old".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        let pack2 = LockedPack {
            name: "my-pack".to_string(),
            version: "1.1.0".to_string(),
            digest: "sha256:new".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        lockfile.add_pack(pack1);
        lockfile.add_pack(pack2);

        // Should only have one entry (updated)
        assert_eq!(lockfile.packs.len(), 1);
        assert_eq!(lockfile.packs[0].version, "1.1.0");
        assert_eq!(lockfile.packs[0].digest, "sha256:new");
    }

    #[test]
    fn test_lockfile_remove_pack() {
        let mut lockfile = Lockfile::new();

        let pack = LockedPack {
            name: "my-pack".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:abc".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        lockfile.add_pack(pack);
        assert!(lockfile.contains("my-pack"));

        let removed = lockfile.remove_pack("my-pack");
        assert!(removed);
        assert!(!lockfile.contains("my-pack"));

        let removed_again = lockfile.remove_pack("my-pack");
        assert!(!removed_again);
    }

    #[test]
    fn test_lockfile_get_pack() {
        let mut lockfile = Lockfile::new();

        let pack = LockedPack {
            name: "my-pack".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:abc".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        };

        lockfile.add_pack(pack);

        let found = lockfile.get_pack("my-pack");
        assert!(found.is_some());
        assert_eq!(found.unwrap().version, "1.0.0");

        let not_found = lockfile.get_pack("other-pack");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_lockfile_to_yaml() {
        let mut lockfile = Lockfile::new();

        let pack = LockedPack {
            name: "my-pack".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:abc123".to_string(),
            source: LockSource::Registry,
            registry_url: Some("https://registry.example.com/v1".to_string()),
            byos_url: None,
            signature: Some(LockSignature {
                algorithm: "Ed25519".to_string(),
                key_id: "sha256:key123".to_string(),
            }),
        };

        lockfile.add_pack(pack);

        let yaml = lockfile.to_yaml().unwrap();
        assert!(yaml.contains("version: 2"));
        assert!(yaml.contains("my-pack"));
        assert!(yaml.contains("sha256:abc123"));
        assert!(yaml.contains("Ed25519"));
    }

    #[test]
    fn test_lock_source_serialize() {
        let sources = vec![
            (LockSource::Bundled, "bundled"),
            (LockSource::Registry, "registry"),
            (LockSource::Byos, "byos"),
            (LockSource::Local, "local"),
        ];

        for (source, expected) in sources {
            let yaml = serde_yaml::to_string(&source).unwrap();
            assert!(yaml.contains(expected));
        }
    }

    // ==================== Lockfile Semantics Tests (SPEC §8) ====================

    #[test]
    fn test_pack_not_in_lockfile() {
        // SPEC §8.4: Pack not in lockfile should be detectable
        let lockfile = Lockfile::new();

        // contains() should return false for unknown pack
        assert!(!lockfile.contains("unknown-pack"));

        // get_pack() should return None
        assert!(lockfile.get_pack("unknown-pack").is_none());

        // pack_names() should be empty
        assert!(lockfile.pack_names().is_empty());
    }

    #[test]
    fn test_lockfile_v2_roundtrip() {
        // SPEC §8.2: Lockfile should roundtrip through YAML serialization
        let mut lockfile = Lockfile::new();

        // Add multiple packs with all fields
        lockfile.add_pack(LockedPack {
            name: "pack-z".to_string(),
            version: "2.0.0".to_string(),
            digest: "sha256:zzz".to_string(),
            source: LockSource::Registry,
            registry_url: Some("https://registry.example.com/v1".to_string()),
            byos_url: None,
            signature: Some(LockSignature {
                algorithm: "Ed25519".to_string(),
                key_id: "sha256:keyzzz".to_string(),
            }),
        });

        lockfile.add_pack(LockedPack {
            name: "pack-a".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:aaa".to_string(),
            source: LockSource::Bundled,
            registry_url: None,
            byos_url: None,
            signature: None,
        });

        lockfile.add_pack(LockedPack {
            name: "pack-m".to_string(),
            version: "1.5.0".to_string(),
            digest: "sha256:mmm".to_string(),
            source: LockSource::Byos,
            registry_url: None,
            byos_url: Some("s3://bucket/pack.yaml".to_string()),
            signature: None,
        });

        // Serialize to YAML
        let yaml = lockfile.to_yaml().unwrap();

        // Parse back
        let parsed = Lockfile::parse(&yaml).unwrap();

        // Verify version preserved
        assert_eq!(parsed.version, LOCKFILE_VERSION);

        // Verify packs are sorted by name
        assert_eq!(parsed.packs.len(), 3);
        assert_eq!(parsed.packs[0].name, "pack-a");
        assert_eq!(parsed.packs[1].name, "pack-m");
        assert_eq!(parsed.packs[2].name, "pack-z");

        // Verify all fields preserved
        let pack_z = parsed.get_pack("pack-z").unwrap();
        assert_eq!(pack_z.version, "2.0.0");
        assert_eq!(pack_z.digest, "sha256:zzz");
        assert_eq!(pack_z.source, LockSource::Registry);
        assert!(pack_z.signature.is_some());

        let pack_m = parsed.get_pack("pack-m").unwrap();
        assert_eq!(pack_m.byos_url, Some("s3://bucket/pack.yaml".to_string()));
    }

    #[test]
    fn test_lockfile_stable_ordering() {
        // SPEC §8.2: Packs should be sorted by name for stable diffs
        let mut lockfile = Lockfile::new();

        // Add packs in random order
        for name in ["zebra", "alpha", "middle", "beta"] {
            lockfile.add_pack(LockedPack {
                name: name.to_string(),
                version: "1.0.0".to_string(),
                digest: format!("sha256:{}", name),
                source: LockSource::Registry,
                registry_url: None,
                byos_url: None,
                signature: None,
            });
        }

        // Verify sorted
        let names: Vec<&str> = lockfile.pack_names().into_iter().collect();
        assert_eq!(names, vec!["alpha", "beta", "middle", "zebra"]);
    }

    #[test]
    fn test_lockfile_digest_mismatch_detection() {
        // SPEC §8.4: Detect when digest differs from lockfile
        let mut lockfile = Lockfile::new();

        lockfile.add_pack(LockedPack {
            name: "my-pack".to_string(),
            version: "1.0.0".to_string(),
            digest: "sha256:expected_digest_here".to_string(),
            source: LockSource::Registry,
            registry_url: None,
            byos_url: None,
            signature: None,
        });

        // Simulate checking against a different digest
        let locked = lockfile.get_pack("my-pack").unwrap();
        let actual_digest = "sha256:different_digest";

        let mismatch = LockMismatch {
            name: locked.name.clone(),
            version: locked.version.clone(),
            expected: locked.digest.clone(),
            actual: actual_digest.to_string(),
        };

        // Verify mismatch is detectable
        assert_ne!(mismatch.expected, mismatch.actual);
        assert_eq!(mismatch.expected, "sha256:expected_digest_here");
        assert_eq!(mismatch.actual, "sha256:different_digest");
    }

    #[test]
    fn test_lockfile_version_1_rejected() {
        // SPEC §8.2: Old lockfile versions should be handled
        // Version 1 is older than current (2), but should still parse
        let yaml_v1 = r#"
version: 1
generated_at: "2025-01-01T00:00:00Z"
generated_by: "assay-cli/1.0.0"
packs: []
"#;

        let result = Lockfile::parse(yaml_v1);
        // Version 1 is supported (less than current)
        assert!(result.is_ok());
    }

    #[test]
    fn test_lockfile_future_version_rejected() {
        // SPEC §8.2: Future lockfile versions should be rejected
        let yaml_future = r#"
version: 99
generated_at: "2030-01-01T00:00:00Z"
generated_by: "future-cli/99.0.0"
packs: []
"#;

        let result = Lockfile::parse(yaml_future);
        assert!(
            matches!(result, Err(RegistryError::Lockfile { .. })),
            "Should reject future lockfile version"
        );
    }

    #[test]
    fn test_lockfile_signature_fields() {
        // SPEC §8.2: Signature fields in lockfile
        let yaml = r#"
version: 2
generated_at: "2026-01-29T10:00:00Z"
generated_by: "assay-cli/2.10.0"
packs:
  - name: signed-pack
    version: "1.0.0"
    digest: sha256:abc123
    source: registry
    signature:
      algorithm: Ed25519
      key_id: sha256:keyid123
"#;

        let lockfile = Lockfile::parse(yaml).unwrap();
        let pack = lockfile.get_pack("signed-pack").unwrap();

        assert!(pack.signature.is_some());
        let sig = pack.signature.as_ref().unwrap();
        assert_eq!(sig.algorithm, "Ed25519");
        assert_eq!(sig.key_id, "sha256:keyid123");
    }
}