cuenv-core 0.40.6

Core types and error handling for the cuenv ecosystem
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! Lockfile types for cuenv tool management.
//!
//! The lockfile (`cuenv.lock`) stores resolved runtime and tool digests for
//! reproducible, hermetic builds. It supports multiple sources:
//! Nix flakes, GitHub releases, and OCI images.
//!
//! ## Structure (v3)
//!
//! ```toml
//! version = 3
//!
//! # Runtime section - project runtime state
//! [runtimes."."]
//! type = "nix"
//! flake = "."
//! digest = "sha256:runtime..."
//! lockfile = "flake.lock"
//!
//! # Tools section - multi-source tool management
//! [tools.jq]
//! version = "1.7.1"
//!
//!   [tools.jq.platforms."darwin-arm64"]
//!   provider = "github"
//!   digest = "sha256:abc..."
//!   source = { repo = "jqlang/jq", tag = "jq-1.7.1", asset = "jq-macos-arm64" }
//!
//!   [tools.jq.platforms."linux-x86_64"]
//!   provider = "github"
//!   digest = "sha256:def..."
//!   source = { repo = "jqlang/jq", tag = "jq-1.7.1", asset = "jq-linux-amd64" }
//!
//! [tools.rust]
//! version = "1.83.0"
//!
//!   [tools.rust.platforms."darwin-arm64"]
//!   provider = "nix"
//!   digest = "sha256:ghi..."
//!   source = { flake = "nixpkgs", package = "rustc" }
//!
//! [[tools_activation]]
//! var = "PATH"
//! op = "prepend"
//! separator = ":"
//! from = { type = "allBinDirs" }
//!
//! # Legacy artifacts section (for OCI images)
//! [[artifacts]]
//! kind = "image"
//! image = "nginx:1.25-alpine"
//!
//!   [artifacts.platforms]
//!   "linux-x86_64" = { digest = "sha256:abc...", size = 1234567 }
//! ```

use crate::tools::ToolActivationStep;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

/// Current lockfile format version.
pub const LOCKFILE_VERSION: u32 = 3;

/// Filename for the lockfile.
pub const LOCKFILE_NAME: &str = "cuenv.lock";

/// The root lockfile structure.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Lockfile {
    /// Lockfile format version (for future migrations).
    pub version: u32,
    /// Locked project runtimes keyed by project path.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub runtimes: BTreeMap<String, LockedRuntime>,
    /// Locked tools with per-platform resolution (v2+).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tools: BTreeMap<String, LockedTool>,
    /// Tool activation operations shared by CLI/CI execution paths (v3+).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools_activation: Vec<ToolActivationStep>,
    /// Legacy OCI artifacts (for backward compatibility with v1).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub artifacts: Vec<LockedArtifact>,
}

impl Default for Lockfile {
    fn default() -> Self {
        Self {
            version: LOCKFILE_VERSION,
            runtimes: BTreeMap::new(),
            tools: BTreeMap::new(),
            tools_activation: Vec::new(),
            artifacts: Vec::new(),
        }
    }
}

impl Lockfile {
    /// Create a new empty lockfile.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Load a lockfile from a TOML file.
    ///
    /// Returns `None` if the file doesn't exist.
    /// Returns an error if the file exists but is invalid.
    pub fn load(path: &Path) -> crate::Result<Option<Self>> {
        if !path.exists() {
            return Ok(None);
        }

        let content = std::fs::read_to_string(path)
            .map_err(|e| crate::Error::configuration(format!("Failed to read lockfile: {}", e)))?;

        let lockfile: Self = toml::from_str(&content).map_err(|e| {
            crate::Error::configuration(format!(
                "Failed to parse lockfile at {}: {}",
                path.display(),
                e
            ))
        })?;

        // Version check for future migrations
        if lockfile.version > LOCKFILE_VERSION {
            return Err(crate::Error::configuration(format!(
                "Lockfile version {} is newer than supported version {}. Please upgrade cuenv.",
                lockfile.version, LOCKFILE_VERSION
            )));
        }

        Ok(Some(lockfile))
    }

    /// Save the lockfile to a TOML file.
    pub fn save(&self, path: &Path) -> crate::Result<()> {
        let content = toml::to_string_pretty(self).map_err(|e| {
            crate::Error::configuration(format!("Failed to serialize lockfile: {}", e))
        })?;

        std::fs::write(path, content)
            .map_err(|e| crate::Error::configuration(format!("Failed to write lockfile: {}", e)))?;

        Ok(())
    }

    /// Find an image artifact by image reference.
    #[must_use]
    pub fn find_image_artifact(&self, image: &str) -> Option<&LockedArtifact> {
        self.artifacts
            .iter()
            .find(|a| matches!(&a.kind, ArtifactKind::Image { image: img } if img == image))
    }

    /// Find a tool by name.
    #[must_use]
    pub fn find_tool(&self, name: &str) -> Option<&LockedTool> {
        self.tools.get(name)
    }

    /// Find a locked runtime by project path.
    #[must_use]
    pub fn find_runtime(&self, project_path: &str) -> Option<&LockedRuntime> {
        self.runtimes.get(project_path)
    }

    /// Get all tool names.
    #[must_use]
    pub fn tool_names(&self) -> Vec<&str> {
        self.tools.keys().map(String::as_str).collect()
    }

    /// Add or update a tool in the lockfile.
    ///
    /// # Errors
    ///
    /// Returns an error if the tool fails validation (empty platforms or
    /// invalid digest format).
    pub fn upsert_tool(&mut self, name: String, tool: LockedTool) -> crate::Result<()> {
        tool.validate().map_err(|msg| {
            crate::Error::configuration(format!("Invalid tool '{}': {}", name, msg))
        })?;

        self.tools.insert(name, tool);
        Ok(())
    }

    /// Add or update a runtime in the lockfile.
    ///
    /// # Errors
    ///
    /// Returns an error if the runtime fails validation.
    pub fn upsert_runtime(
        &mut self,
        project_path: String,
        runtime: LockedRuntime,
    ) -> crate::Result<()> {
        runtime.validate().map_err(|msg| {
            crate::Error::configuration(format!(
                "Invalid runtime for project '{}': {}",
                project_path, msg
            ))
        })?;

        self.runtimes.insert(project_path, runtime);
        Ok(())
    }

    /// Add or update a single platform for a tool.
    ///
    /// Creates the tool entry if it doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the platform data is invalid.
    pub fn upsert_tool_platform(
        &mut self,
        name: &str,
        version: &str,
        platform: &str,
        data: LockedToolPlatform,
    ) -> crate::Result<()> {
        // Validate digest format
        if !data.digest.starts_with("sha256:") && !data.digest.starts_with("sha512:") {
            return Err(crate::Error::configuration(format!(
                "Invalid digest format for tool '{}' platform '{}': must start with 'sha256:' or 'sha512:'",
                name, platform
            )));
        }

        let tool = self
            .tools
            .entry(name.to_string())
            .or_insert_with(|| LockedTool {
                version: version.to_string(),
                platforms: BTreeMap::new(),
            });

        // Update version if it changed
        if tool.version != version {
            tool.version = version.to_string();
        }

        tool.platforms.insert(platform.to_string(), data);
        Ok(())
    }

    /// Add or update an artifact in the lockfile (legacy v1 format).
    ///
    /// Matches artifacts by image reference.
    ///
    /// # Errors
    ///
    /// Returns an error if the artifact fails validation (empty platforms or
    /// invalid digest format).
    pub fn upsert_artifact(&mut self, artifact: LockedArtifact) -> crate::Result<()> {
        // Validate the artifact before inserting
        artifact
            .validate()
            .map_err(|msg| crate::Error::configuration(format!("Invalid artifact: {}", msg)))?;

        // Find existing artifact with same identity (match Image by full reference)
        let existing_idx = self
            .artifacts
            .iter()
            .position(|a| match (&a.kind, &artifact.kind) {
                (ArtifactKind::Image { image: i1 }, ArtifactKind::Image { image: i2 }) => i1 == i2,
            });

        if let Some(idx) = existing_idx {
            self.artifacts[idx] = artifact;
        } else {
            self.artifacts.push(artifact);
        }

        Ok(())
    }
}

/// A locked OCI artifact with platform-specific digests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockedArtifact {
    /// The kind of artifact (registry package or container image).
    #[serde(flatten)]
    pub kind: ArtifactKind,
    /// Platform-specific resolution data.
    /// Keys are platform strings like "darwin-arm64", "linux-x86_64".
    pub platforms: BTreeMap<String, PlatformData>,
}

impl LockedArtifact {
    /// Get the digest for the current platform.
    #[must_use]
    pub fn digest_for_current_platform(&self) -> Option<&str> {
        let platform = current_platform();
        self.platforms.get(&platform).map(|p| p.digest.as_str())
    }

    /// Get platform data for the current platform.
    #[must_use]
    pub fn platform_data(&self) -> Option<&PlatformData> {
        let platform = current_platform();
        self.platforms.get(&platform)
    }

    /// Validate the artifact has valid data.
    ///
    /// Checks:
    /// - At least one platform is present
    /// - All digests have valid format (sha256: or sha512: prefix)
    fn validate(&self) -> Result<(), String> {
        if self.platforms.is_empty() {
            return Err("Artifact must have at least one platform".to_string());
        }

        for (platform, data) in &self.platforms {
            if !data.digest.starts_with("sha256:") && !data.digest.starts_with("sha512:") {
                return Err(format!(
                    "Invalid digest format for platform '{}': must start with 'sha256:' or 'sha512:'",
                    platform
                ));
            }
        }

        Ok(())
    }
}

/// The kind of OCI artifact.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ArtifactKind {
    /// An OCI image (container images).
    Image {
        /// Full image reference (e.g., "nginx:1.25-alpine").
        image: String,
    },
}

/// Platform-specific artifact data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformData {
    /// Content-addressable digest (e.g., "sha256:abc123...").
    pub digest: String,
    /// Size in bytes (for progress reporting).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u64>,
}

/// A locked project runtime keyed by project path.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum LockedRuntime {
    /// Locked Nix runtime derived from a local flake.lock file.
    Nix(LockedNixRuntime),
}

impl LockedRuntime {
    fn validate(&self) -> Result<(), String> {
        match self {
            Self::Nix(runtime) => runtime.validate(),
        }
    }
}

/// Locked metadata for a Nix runtime.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockedNixRuntime {
    /// Flake reference from the manifest runtime.
    pub flake: String,
    /// Selected shell or package output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
    /// Deterministic digest derived from the local flake.lock content.
    pub digest: String,
    /// Relative path to the flake.lock file used for this digest.
    pub lockfile: String,
}

impl LockedNixRuntime {
    fn validate(&self) -> Result<(), String> {
        if !self.digest.starts_with("sha256:") && !self.digest.starts_with("sha512:") {
            return Err(
                "digest must start with 'sha256:' or 'sha512:' for Nix runtime".to_string(),
            );
        }

        if self.lockfile.trim().is_empty() {
            return Err("lockfile path must not be empty".to_string());
        }

        Ok(())
    }
}

/// A locked tool with version and per-platform resolution (v2+).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockedTool {
    /// Version string (e.g., "1.7.1").
    pub version: String,
    /// Platform-specific resolution data.
    /// Keys are platform strings like "darwin-arm64", "linux-x86_64".
    pub platforms: BTreeMap<String, LockedToolPlatform>,
}

impl LockedTool {
    /// Get platform data for the current platform.
    #[must_use]
    pub fn current_platform(&self) -> Option<&LockedToolPlatform> {
        let platform = current_platform();
        self.platforms.get(&platform)
    }

    /// Validate the locked tool has valid data.
    fn validate(&self) -> Result<(), String> {
        if self.platforms.is_empty() {
            return Err("Tool must have at least one platform".to_string());
        }

        for (platform, data) in &self.platforms {
            if !data.digest.starts_with("sha256:") && !data.digest.starts_with("sha512:") {
                return Err(format!(
                    "Invalid digest format for platform '{}': must start with 'sha256:' or 'sha512:'",
                    platform
                ));
            }
        }

        Ok(())
    }
}

/// Platform-specific tool resolution data (v2+).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LockedToolPlatform {
    /// Provider that resolved this tool (e.g., "github", "nix", "oci").
    pub provider: String,
    /// Content-addressable digest (e.g., "sha256:abc123...").
    pub digest: String,
    /// Provider-specific source data (serialized as inline table).
    /// For GitHub: `{ repo = "...", tag = "...", asset = "..." }`
    /// For Nix: `{ flake = "...", package = "..." }`
    /// For OCI: `{ image = "...", path = "..." }`
    pub source: serde_json::Value,
    /// Size in bytes (for progress reporting).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u64>,
    /// Runtime dependencies (other tool names).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<String>,
}

/// Get the current platform string.
///
/// Format: `{os}-{arch}` where:
/// - os: "darwin", "linux", "windows"
/// - arch: "x86_64", "arm64", "aarch64"
#[must_use]
pub fn current_platform() -> String {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;

    // Normalize arch names
    let arch = match arch {
        "aarch64" => "arm64",
        other => other,
    };

    format!("{}-{}", os, arch)
}

/// Normalize a platform string to our canonical format.
#[must_use]
pub fn normalize_platform(platform: &str) -> String {
    let platform = platform.to_lowercase();

    // Handle various platform formats
    platform
        .replace("macos", "darwin")
        .replace("osx", "darwin")
        .replace("amd64", "x86_64")
        .replace("aarch64", "arm64")
}

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

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

        lockfile
            .upsert_runtime(
                ".".to_string(),
                LockedRuntime::Nix(LockedNixRuntime {
                    flake: ".".to_string(),
                    output: None,
                    digest: "sha256:runtime123".to_string(),
                    lockfile: "flake.lock".to_string(),
                }),
            )
            .unwrap();

        // OCI image artifact
        lockfile.artifacts.push(LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::from([
                (
                    "darwin-arm64".to_string(),
                    PlatformData {
                        digest: "sha256:abc123".to_string(),
                        size: Some(1234567),
                    },
                ),
                (
                    "linux-x86_64".to_string(),
                    PlatformData {
                        digest: "sha256:def456".to_string(),
                        size: Some(1345678),
                    },
                ),
            ]),
        });

        let toml_str = toml::to_string_pretty(&lockfile).unwrap();
        assert!(toml_str.contains("version = 3"));
        assert!(toml_str.contains("type = \"nix\""));
        assert!(toml_str.contains("lockfile = \"flake.lock\""));
        assert!(toml_str.contains("kind = \"image\""));
        assert!(toml_str.contains("nginx:1.25-alpine"));

        // Round-trip test
        let parsed: Lockfile = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed, lockfile);
    }

    #[test]
    fn test_find_image_artifact() {
        let mut lockfile = Lockfile::new();
        lockfile.artifacts.push(LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::new(),
        });

        assert!(lockfile.find_image_artifact("nginx:1.25-alpine").is_some());
        assert!(lockfile.find_image_artifact("nginx:1.24-alpine").is_none());
    }

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

        let artifact1 = LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::from([(
                "darwin-arm64".to_string(),
                PlatformData {
                    digest: "sha256:old".to_string(),
                    size: None,
                },
            )]),
        };

        lockfile.upsert_artifact(artifact1).unwrap();
        assert_eq!(lockfile.artifacts.len(), 1);

        // Update with new digest
        let artifact2 = LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::from([(
                "darwin-arm64".to_string(),
                PlatformData {
                    digest: "sha256:new".to_string(),
                    size: Some(123),
                },
            )]),
        };

        lockfile.upsert_artifact(artifact2).unwrap();
        assert_eq!(lockfile.artifacts.len(), 1);
        assert_eq!(
            lockfile.artifacts[0].platforms["darwin-arm64"].digest,
            "sha256:new"
        );
    }

    #[test]
    fn test_current_platform() {
        let platform = current_platform();
        // Should contain OS and arch
        assert!(platform.contains('-'));
        let parts: Vec<&str> = platform.split('-').collect();
        assert_eq!(parts.len(), 2);
    }

    #[test]
    fn test_normalize_platform() {
        assert_eq!(normalize_platform("macos-amd64"), "darwin-x86_64");
        assert_eq!(normalize_platform("linux-aarch64"), "linux-arm64");
        assert_eq!(normalize_platform("Darwin-ARM64"), "darwin-arm64");
    }

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

        let artifact = LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::new(), // Empty - should fail
        };

        let result = lockfile.upsert_artifact(artifact);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("at least one platform")
        );
    }

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

        let artifact = LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::from([(
                "darwin-arm64".to_string(),
                PlatformData {
                    digest: "invalid-no-prefix".to_string(), // Missing sha256: prefix
                    size: None,
                },
            )]),
        };

        let result = lockfile.upsert_artifact(artifact);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Invalid digest format")
        );
    }

    #[test]
    fn test_artifact_validate_valid() {
        let artifact = LockedArtifact {
            kind: ArtifactKind::Image {
                image: "nginx:1.25-alpine".to_string(),
            },
            platforms: BTreeMap::from([
                (
                    "darwin-arm64".to_string(),
                    PlatformData {
                        digest: "sha256:abc123".to_string(),
                        size: Some(1234),
                    },
                ),
                (
                    "linux-x86_64".to_string(),
                    PlatformData {
                        digest: "sha512:def456".to_string(),
                        size: None,
                    },
                ),
            ]),
        };

        assert!(artifact.validate().is_ok());
    }

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

        lockfile
            .upsert_tool_platform(
                "jq",
                "1.7.1",
                "darwin-arm64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:abc123".to_string(),
                    source: serde_json::json!({ "repo": "jqlang/jq", "tag": "jq-1.7.1", "asset": "jq-macos-arm64" }),
                    size: Some(1234567),
                    dependencies: vec![],
                },
            )
            .unwrap();

        lockfile
            .upsert_tool_platform(
                "jq",
                "1.7.1",
                "linux-x86_64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:def456".to_string(),
                    source: serde_json::json!({ "repo": "jqlang/jq", "tag": "jq-1.7.1", "asset": "jq-linux-amd64" }),
                    size: Some(1345678),
                    dependencies: vec![],
                },
            )
            .unwrap();

        let toml_str = toml::to_string_pretty(&lockfile).unwrap();
        assert!(toml_str.contains("version = 3"));
        assert!(toml_str.contains("[tools.jq]"));
        assert!(toml_str.contains("provider = \"github\""));
        assert!(toml_str.contains("digest = \"sha256:abc123\""));

        // Round-trip test
        let parsed: Lockfile = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.tools.len(), 1);
        assert_eq!(parsed.tools["jq"].version, "1.7.1");
        assert_eq!(parsed.tools["jq"].platforms.len(), 2);
    }

    #[test]
    fn test_tools_activation_serialization() {
        use crate::tools::{ToolActivationOperation, ToolActivationSource, ToolActivationStep};

        let mut lockfile = Lockfile::new();
        lockfile.tools_activation.push(ToolActivationStep {
            var: "PATH".to_string(),
            op: ToolActivationOperation::Prepend,
            separator: ":".to_string(),
            from: ToolActivationSource::AllBinDirs,
        });

        let toml_str = toml::to_string_pretty(&lockfile).unwrap();
        assert!(toml_str.contains("[[tools_activation]]"));
        assert!(toml_str.contains("var = \"PATH\""));
        assert!(toml_str.contains("op = \"prepend\""));
        assert!(toml_str.contains("type = \"allBinDirs\""));

        let parsed: Lockfile = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.tools_activation.len(), 1);
        assert_eq!(parsed.tools_activation[0], lockfile.tools_activation[0]);
    }

    #[test]
    fn test_find_runtime() {
        let mut lockfile = Lockfile::new();
        lockfile
            .upsert_runtime(
                ".".to_string(),
                LockedRuntime::Nix(LockedNixRuntime {
                    flake: ".".to_string(),
                    output: Some("devShells.x86_64-linux.default".to_string()),
                    digest: "sha256:abc123".to_string(),
                    lockfile: "flake.lock".to_string(),
                }),
            )
            .unwrap();

        assert!(lockfile.find_runtime(".").is_some());
        assert!(lockfile.find_runtime("apps/api").is_none());
    }

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

        let result = lockfile.upsert_runtime(
            ".".to_string(),
            LockedRuntime::Nix(LockedNixRuntime {
                flake: ".".to_string(),
                output: None,
                digest: "invalid".to_string(),
                lockfile: "flake.lock".to_string(),
            }),
        );

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("digest must start with")
        );
    }

    #[test]
    fn test_find_tool() {
        let mut lockfile = Lockfile::new();
        lockfile
            .upsert_tool_platform(
                "jq",
                "1.7.1",
                "darwin-arm64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:abc123".to_string(),
                    source: serde_json::json!({ "repo": "jqlang/jq", "tag": "jq-1.7.1", "asset": "jq-macos-arm64" }),
                    size: None,
                    dependencies: vec![],
                },
            )
            .unwrap();

        assert!(lockfile.find_tool("jq").is_some());
        assert!(lockfile.find_tool("yq").is_none());
    }

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

        // Add first platform
        lockfile
            .upsert_tool_platform(
                "bun",
                "1.3.5",
                "darwin-arm64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:aaa".to_string(),
                    source: serde_json::json!({ "url": "https://..." }),
                    size: None,
                    dependencies: vec![],
                },
            )
            .unwrap();

        assert_eq!(lockfile.tools.len(), 1);
        assert_eq!(lockfile.tools["bun"].platforms.len(), 1);

        // Add second platform
        lockfile
            .upsert_tool_platform(
                "bun",
                "1.3.5",
                "linux-x86_64",
                LockedToolPlatform {
                    provider: "oci".to_string(),
                    digest: "sha256:bbb".to_string(),
                    source: serde_json::json!({ "image": "oven/bun:1.3.5" }),
                    size: None,
                    dependencies: vec![],
                },
            )
            .unwrap();

        assert_eq!(lockfile.tools.len(), 1);
        assert_eq!(lockfile.tools["bun"].platforms.len(), 2);
        assert_eq!(
            lockfile.tools["bun"].platforms["darwin-arm64"].provider,
            "github"
        );
        assert_eq!(
            lockfile.tools["bun"].platforms["linux-x86_64"].provider,
            "oci"
        );
    }

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

        let result = lockfile.upsert_tool_platform(
            "jq",
            "1.7.1",
            "darwin-arm64",
            LockedToolPlatform {
                provider: "github".to_string(),
                digest: "invalid".to_string(), // Missing sha256: prefix
                source: serde_json::json!({}),
                size: None,
                dependencies: vec![],
            },
        );

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Invalid digest format")
        );
    }

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

        let tool = LockedTool {
            version: "1.7.1".to_string(),
            platforms: BTreeMap::new(), // Empty - should fail
        };

        let result = lockfile.upsert_tool("jq".to_string(), tool);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("at least one platform")
        );
    }

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

        lockfile
            .upsert_tool_platform(
                "jq",
                "1.7.1",
                "darwin-arm64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:abc".to_string(),
                    source: serde_json::json!({}),
                    size: None,
                    dependencies: vec![],
                },
            )
            .unwrap();

        lockfile
            .upsert_tool_platform(
                "yq",
                "4.44.6",
                "darwin-arm64",
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:def".to_string(),
                    source: serde_json::json!({}),
                    size: None,
                    dependencies: vec![],
                },
            )
            .unwrap();

        let names = lockfile.tool_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"jq"));
        assert!(names.contains(&"yq"));
    }
}