greentic-bundle-reader 1.2.0-dev.26015828189

Read-only bundle reader for greentic-bundle SquashFS artifacts and normalized build directories.
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
use std::fmt;
use std::fs;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};

use backhand::{FilesystemReader, InnerNode};
use serde::{Deserialize, Serialize};

pub const BUNDLE_FORMAT_VERSION: &str = "gtbundle-v1";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleManifest {
    pub format_version: String,
    pub bundle_id: String,
    pub bundle_name: String,
    pub requested_mode: String,
    pub locale: String,
    pub artifact_extension: String,
    #[serde(default)]
    pub generated_resolved_files: Vec<String>,
    #[serde(default)]
    pub generated_setup_files: Vec<String>,
    #[serde(default)]
    pub app_packs: Vec<String>,
    #[serde(default)]
    pub extension_providers: Vec<String>,
    #[serde(default)]
    pub catalogs: Vec<String>,
    #[serde(default)]
    pub hooks: Vec<String>,
    #[serde(default)]
    pub subscriptions: Vec<String>,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default)]
    pub resolved_targets: Vec<BundleResolvedTargetView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleLock {
    pub schema_version: u32,
    pub bundle_id: String,
    pub requested_mode: String,
    pub execution: String,
    pub cache_policy: String,
    pub tool_version: String,
    pub build_format_version: String,
    pub workspace_root: String,
    pub lock_file: String,
    pub catalogs: Vec<CatalogLockEntry>,
    pub app_packs: Vec<DependencyLock>,
    pub extension_providers: Vec<DependencyLock>,
    pub setup_state_files: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogLockEntry {
    pub requested_ref: String,
    pub resolved_ref: String,
    pub digest: String,
    pub source: String,
    pub item_count: usize,
    pub item_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_path: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DependencyLock {
    pub reference: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleSourceKind {
    Artifact,
    BuildDir,
}

impl BundleSourceKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Artifact => "artifact",
            Self::BuildDir => "build_dir",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleRuntimeSurface {
    pub format_version: String,
    pub bundle_id: String,
    pub bundle_name: String,
    pub requested_mode: String,
    pub locale: String,
    pub execution: String,
    pub cache_policy: String,
    pub workspace_root: String,
    pub lock_file: String,
    pub app_packs: Vec<BundleDependencyView>,
    pub extension_providers: Vec<BundleDependencyView>,
    pub catalogs: Vec<BundleCatalogView>,
    pub hooks: Vec<String>,
    pub subscriptions: Vec<String>,
    pub capabilities: Vec<String>,
    pub resolved_targets: Vec<BundleResolvedTargetView>,
    pub generated_resolved_files: Vec<BundleFileView>,
    pub generated_setup_files: Vec<BundleFileView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleDependencyView {
    pub reference: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleCatalogView {
    pub requested_ref: String,
    pub resolved_ref: String,
    pub digest: String,
    pub source: String,
    pub item_count: usize,
    pub item_ids: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_path: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleFileView {
    pub path: String,
    pub kind: BundleFileKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleResolvedTargetView {
    pub path: String,
    pub tenant: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team: Option<String>,
    pub default_policy: String,
    pub tenant_gmap: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team_gmap: Option<String>,
    #[serde(default)]
    pub app_pack_policies: Vec<BundleResolvedReferencePolicyView>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleResolvedReferencePolicyView {
    pub reference: String,
    pub policy: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleFileKind {
    Resolved,
    SetupState,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenedBundle {
    pub source_kind: BundleSourceKind,
    pub source_path: String,
    pub format_version: String,
    pub manifest: BundleManifest,
    pub lock: BundleLock,
}

impl OpenedBundle {
    pub fn from_parts(
        source_kind: BundleSourceKind,
        source_path: impl Into<String>,
        manifest: BundleManifest,
        lock: BundleLock,
    ) -> Result<Self, BundleReadError> {
        let opened = Self {
            source_kind,
            source_path: source_path.into(),
            format_version: manifest.format_version.clone(),
            manifest,
            lock,
        };
        opened.validate_basic_structure()?;
        Ok(opened)
    }

    pub fn runtime_surface(&self) -> BundleRuntimeSurface {
        BundleRuntimeSurface {
            format_version: self.manifest.format_version.clone(),
            bundle_id: self.manifest.bundle_id.clone(),
            bundle_name: self.manifest.bundle_name.clone(),
            requested_mode: self.manifest.requested_mode.clone(),
            locale: self.manifest.locale.clone(),
            execution: self.lock.execution.clone(),
            cache_policy: self.lock.cache_policy.clone(),
            workspace_root: self.lock.workspace_root.clone(),
            lock_file: self.lock.lock_file.clone(),
            app_packs: self
                .lock
                .app_packs
                .iter()
                .map(|entry| BundleDependencyView {
                    reference: entry.reference.clone(),
                    digest: entry.digest.clone(),
                })
                .collect(),
            extension_providers: self
                .lock
                .extension_providers
                .iter()
                .map(|entry| BundleDependencyView {
                    reference: entry.reference.clone(),
                    digest: entry.digest.clone(),
                })
                .collect(),
            catalogs: self
                .lock
                .catalogs
                .iter()
                .map(|entry| BundleCatalogView {
                    requested_ref: entry.requested_ref.clone(),
                    resolved_ref: entry.resolved_ref.clone(),
                    digest: entry.digest.clone(),
                    source: entry.source.clone(),
                    item_count: entry.item_count,
                    item_ids: entry.item_ids.clone(),
                    cache_path: entry.cache_path.clone(),
                })
                .collect(),
            hooks: self.manifest.hooks.clone(),
            subscriptions: self.manifest.subscriptions.clone(),
            capabilities: self.manifest.capabilities.clone(),
            resolved_targets: self.manifest.resolved_targets.clone(),
            generated_resolved_files: self
                .manifest
                .generated_resolved_files
                .iter()
                .map(|path| BundleFileView {
                    path: path.clone(),
                    kind: BundleFileKind::Resolved,
                })
                .collect(),
            generated_setup_files: self
                .manifest
                .generated_setup_files
                .iter()
                .map(|path| BundleFileView {
                    path: path.clone(),
                    kind: BundleFileKind::SetupState,
                })
                .collect(),
        }
    }

    pub fn validate_basic_structure(&self) -> Result<(), BundleReadError> {
        if self.manifest.format_version != BUNDLE_FORMAT_VERSION {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!(
                    "unsupported bundle format version: {}",
                    self.manifest.format_version
                ),
            ));
        }
        if self.manifest.bundle_id.trim().is_empty() {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest is missing bundle_id".to_string(),
            ));
        }
        if self.lock.bundle_id.trim().is_empty() {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle lock is missing bundle_id".to_string(),
            ));
        }
        if self.manifest.bundle_id != self.lock.bundle_id {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock bundle_id do not match".to_string(),
            ));
        }
        if self.manifest.requested_mode != self.lock.requested_mode {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock requested_mode do not match".to_string(),
            ));
        }
        if self.manifest.artifact_extension != ".gtbundle" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!(
                    "unsupported artifact extension: {}",
                    self.manifest.artifact_extension
                ),
            ));
        }
        if self.lock.workspace_root != "bundle.yaml" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!("unexpected workspace_root: {}", self.lock.workspace_root),
            ));
        }
        if self.lock.lock_file != "bundle.lock.json" {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                format!("unexpected lock_file: {}", self.lock.lock_file),
            ));
        }
        if self.lock.setup_state_files != self.manifest.generated_setup_files {
            return Err(BundleReadError::invalid(
                self.source_kind,
                &self.source_path,
                "bundle manifest and lock setup state files do not match".to_string(),
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleReadError {
    pub kind: BundleReadErrorKind,
    pub source_kind: BundleSourceKind,
    pub source_path: String,
    pub details: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundleReadErrorKind {
    Io,
    Invalid,
    Tool,
}

impl BundleReadError {
    fn io(source_kind: BundleSourceKind, source_path: &Path, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Io,
            source_kind,
            source_path: source_path.display().to_string(),
            details,
        }
    }

    fn invalid(source_kind: BundleSourceKind, source_path: &str, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Invalid,
            source_kind,
            source_path: source_path.to_string(),
            details,
        }
    }

    fn tool(source_kind: BundleSourceKind, source_path: &Path, details: String) -> Self {
        Self {
            kind: BundleReadErrorKind::Tool,
            source_kind,
            source_path: source_path.display().to_string(),
            details,
        }
    }
}

impl fmt::Display for BundleReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} read failed for {} ({}): {}",
            self.source_kind.as_str(),
            self.source_path,
            match self.kind {
                BundleReadErrorKind::Io => "io",
                BundleReadErrorKind::Invalid => "invalid",
                BundleReadErrorKind::Tool => "tool",
            },
            self.details
        )
    }
}

impl std::error::Error for BundleReadError {}

pub fn open_artifact(path: &Path) -> Result<OpenedBundle, BundleReadError> {
    let manifest_raw = read_artifact_file(path, "bundle-manifest.json")?;
    let lock_raw = read_artifact_file(path, "bundle-lock.json")?;
    let manifest = parse_manifest(BundleSourceKind::Artifact, path, &manifest_raw)?;
    let lock = parse_lock(BundleSourceKind::Artifact, path, &lock_raw)?;
    let opened = OpenedBundle::from_parts(
        BundleSourceKind::Artifact,
        path.display().to_string(),
        manifest,
        lock,
    )?;
    validate_artifact_contents(path, &opened)?;
    Ok(opened)
}

pub fn open_build_dir(path: &Path) -> Result<OpenedBundle, BundleReadError> {
    open_build_dir_with_source(path, path.display().to_string())
}

pub fn open_build_dir_with_source(
    path: &Path,
    source_path: impl Into<String>,
) -> Result<OpenedBundle, BundleReadError> {
    let manifest_raw = read_build_file(path, "bundle-manifest.json")?;
    let lock_raw = read_build_file(path, "bundle-lock.json")?;
    let manifest = parse_manifest(BundleSourceKind::BuildDir, path, &manifest_raw)?;
    let lock = parse_lock(BundleSourceKind::BuildDir, path, &lock_raw)?;
    let opened = OpenedBundle::from_parts(BundleSourceKind::BuildDir, source_path, manifest, lock)?;
    validate_build_dir_contents(path, &opened)?;
    Ok(opened)
}

fn read_build_file(root: &Path, name: &str) -> Result<String, BundleReadError> {
    fs::read_to_string(root.join(name)).map_err(|error| {
        BundleReadError::io(
            BundleSourceKind::BuildDir,
            root,
            format!("read {}: {error}", root.join(name).display()),
        )
    })
}

fn read_artifact_file(path: &Path, inner_path: &str) -> Result<String, BundleReadError> {
    let bytes = read_artifact_bytes(path, inner_path)?;
    String::from_utf8(bytes).map_err(|error| {
        BundleReadError::invalid(
            BundleSourceKind::Artifact,
            &path.display().to_string(),
            format!("artifact entry {inner_path} is not valid utf-8: {error}"),
        )
    })
}

fn read_artifact_bytes(path: &Path, inner_path: &str) -> Result<Vec<u8>, BundleReadError> {
    let filesystem = open_artifact_filesystem(path)?;
    let normalized_inner = normalize_artifact_path(inner_path).map_err(|error| {
        BundleReadError::invalid(
            BundleSourceKind::Artifact,
            &path.display().to_string(),
            format!("invalid artifact path {inner_path}: {error}"),
        )
    })?;
    for node in filesystem.files() {
        let Some(node_path) = normalize_node_path(&node.fullpath).map_err(|error| {
            BundleReadError::tool(
                BundleSourceKind::Artifact,
                path,
                format!("read SquashFS path {}: {error}", node.fullpath.display()),
            )
        })?
        else {
            continue;
        };
        if node_path != normalized_inner {
            continue;
        }
        let InnerNode::File(file) = &node.inner else {
            return Err(BundleReadError::invalid(
                BundleSourceKind::Artifact,
                &path.display().to_string(),
                format!("artifact entry {inner_path} is not a file"),
            ));
        };
        let mut reader = filesystem.file(file).reader();
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).map_err(|error| {
            BundleReadError::tool(
                BundleSourceKind::Artifact,
                path,
                format!("read artifact entry {inner_path}: {error}"),
            )
        })?;
        return Ok(bytes);
    }
    Err(BundleReadError::tool(
        BundleSourceKind::Artifact,
        path,
        format!("artifact entry {inner_path} not found"),
    ))
}

fn open_artifact_filesystem(path: &Path) -> Result<FilesystemReader<'static>, BundleReadError> {
    let file = fs::File::open(path).map_err(|error| {
        BundleReadError::io(
            BundleSourceKind::Artifact,
            path,
            format!("open artifact {}: {error}", path.display()),
        )
    })?;
    FilesystemReader::from_reader(BufReader::new(file)).map_err(|error| {
        BundleReadError::tool(
            BundleSourceKind::Artifact,
            path,
            format!("read SquashFS artifact with Rust-native reader: {error}"),
        )
    })
}

fn normalize_node_path(path: &Path) -> Result<Option<String>, String> {
    if path == Path::new("/") {
        return Ok(None);
    }
    let stripped = path.strip_prefix("/").unwrap_or(path);
    normalize_path(stripped).map(Some)
}

fn normalize_artifact_path(path: &str) -> Result<String, String> {
    normalize_path(Path::new(path.trim_matches('/')))
}

fn normalize_path(path: &Path) -> Result<String, String> {
    let mut parts = Vec::new();
    for component in path.components() {
        match component {
            std::path::Component::Normal(part) => {
                let part = part
                    .to_str()
                    .ok_or_else(|| format!("path must be valid UTF-8: {}", path.display()))?;
                parts.push(part.to_string());
            }
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir
            | std::path::Component::RootDir
            | std::path::Component::Prefix(_) => {
                return Err(format!("path must be relative: {}", path.display()));
            }
        }
    }
    if parts.is_empty() {
        return Err("path cannot be empty".to_string());
    }
    Ok(parts.join("/"))
}

fn parse_manifest(
    source_kind: BundleSourceKind,
    source_path: &Path,
    raw: &str,
) -> Result<BundleManifest, BundleReadError> {
    serde_json::from_str(raw).map_err(|error| {
        BundleReadError::invalid(
            source_kind,
            &source_path.display().to_string(),
            format!("parse bundle-manifest.json: {error}"),
        )
    })
}

fn parse_lock(
    source_kind: BundleSourceKind,
    source_path: &Path,
    raw: &str,
) -> Result<BundleLock, BundleReadError> {
    serde_json::from_str(raw).map_err(|error| {
        BundleReadError::invalid(
            source_kind,
            &source_path.display().to_string(),
            format!("parse bundle-lock.json: {error}"),
        )
    })
}

fn validate_build_dir_contents(path: &Path, opened: &OpenedBundle) -> Result<(), BundleReadError> {
    ensure_path_exists(
        BundleSourceKind::BuildDir,
        path,
        &path.join("bundle.yaml"),
        "bundle.yaml",
    )?;
    for rel_path in &opened.manifest.generated_resolved_files {
        ensure_path_exists(
            BundleSourceKind::BuildDir,
            path,
            &path.join(rel_path),
            rel_path,
        )?;
    }
    for rel_path in &opened.manifest.generated_setup_files {
        ensure_path_exists(
            BundleSourceKind::BuildDir,
            path,
            &path.join(rel_path),
            rel_path,
        )?;
    }
    Ok(())
}

fn validate_artifact_contents(path: &Path, opened: &OpenedBundle) -> Result<(), BundleReadError> {
    read_artifact_file(path, "bundle.yaml")?;
    for rel_path in &opened.manifest.generated_resolved_files {
        read_artifact_file(path, rel_path)?;
    }
    for rel_path in &opened.manifest.generated_setup_files {
        read_artifact_file(path, rel_path)?;
    }
    Ok(())
}

fn ensure_path_exists(
    source_kind: BundleSourceKind,
    source_path: &Path,
    full_path: &Path,
    display_path: &str,
) -> Result<(), BundleReadError> {
    if full_path.exists() {
        return Ok(());
    }
    Err(BundleReadError::invalid(
        source_kind,
        &source_path.display().to_string(),
        format!("missing required bundle file: {display_path}"),
    ))
}

pub fn build_dir_from_artifact_source(root: &Path, bundle_id: &str) -> PathBuf {
    root.join("state")
        .join("build")
        .join(bundle_id)
        .join("normalized")
}

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

    fn valid_manifest() -> BundleManifest {
        BundleManifest {
            format_version: BUNDLE_FORMAT_VERSION.to_string(),
            bundle_id: "demo".to_string(),
            bundle_name: "Demo".to_string(),
            requested_mode: "auto".to_string(),
            locale: "en".to_string(),
            artifact_extension: ".gtbundle".to_string(),
            generated_resolved_files: Vec::new(),
            generated_setup_files: Vec::new(),
            app_packs: Vec::new(),
            extension_providers: Vec::new(),
            catalogs: Vec::new(),
            hooks: Vec::new(),
            subscriptions: Vec::new(),
            capabilities: Vec::new(),
            resolved_targets: Vec::new(),
        }
    }

    fn valid_lock() -> BundleLock {
        BundleLock {
            schema_version: 1,
            bundle_id: "demo".to_string(),
            requested_mode: "auto".to_string(),
            execution: "exec".to_string(),
            cache_policy: "policy".to_string(),
            tool_version: "0.0.0".to_string(),
            build_format_version: BUNDLE_FORMAT_VERSION.to_string(),
            workspace_root: "bundle.yaml".to_string(),
            lock_file: "bundle.lock.json".to_string(),
            catalogs: Vec::new(),
            app_packs: Vec::new(),
            extension_providers: Vec::new(),
            setup_state_files: Vec::new(),
        }
    }

    fn opened_with(
        manifest: BundleManifest,
        lock: BundleLock,
    ) -> Result<OpenedBundle, BundleReadError> {
        OpenedBundle::from_parts(BundleSourceKind::Artifact, "demo.gtbundle", manifest, lock)
    }

    #[test]
    fn source_kind_as_str_returns_canonical_labels() {
        assert_eq!(BundleSourceKind::Artifact.as_str(), "artifact");
        assert_eq!(BundleSourceKind::BuildDir.as_str(), "build_dir");
    }

    #[test]
    fn display_renders_kind_and_details() {
        let io = BundleReadError {
            kind: BundleReadErrorKind::Io,
            source_kind: BundleSourceKind::Artifact,
            source_path: "demo.gtbundle".to_string(),
            details: "boom".to_string(),
        };
        assert_eq!(
            io.to_string(),
            "artifact read failed for demo.gtbundle (io): boom"
        );

        let invalid = BundleReadError {
            kind: BundleReadErrorKind::Invalid,
            source_kind: BundleSourceKind::BuildDir,
            source_path: "build/".to_string(),
            details: "bad".to_string(),
        };
        assert_eq!(
            invalid.to_string(),
            "build_dir read failed for build/ (invalid): bad"
        );

        let tool = BundleReadError {
            kind: BundleReadErrorKind::Tool,
            source_kind: BundleSourceKind::Artifact,
            source_path: "x".to_string(),
            details: "y".to_string(),
        };
        assert_eq!(tool.to_string(), "artifact read failed for x (tool): y");
    }

    #[test]
    fn from_parts_succeeds_for_consistent_manifest_and_lock() {
        let opened = opened_with(valid_manifest(), valid_lock()).expect("valid bundle");
        assert_eq!(opened.source_kind, BundleSourceKind::Artifact);
        assert_eq!(opened.format_version, BUNDLE_FORMAT_VERSION);
        let surface = opened.runtime_surface();
        assert_eq!(surface.bundle_id, "demo");
        assert_eq!(surface.workspace_root, "bundle.yaml");
        assert!(surface.generated_resolved_files.is_empty());
        assert!(surface.generated_setup_files.is_empty());
    }

    #[test]
    fn validate_rejects_unsupported_format_version() {
        let mut manifest = valid_manifest();
        manifest.format_version = "gtbundle-v999".to_string();
        let err = opened_with(manifest, valid_lock()).expect_err("bad version");
        assert_eq!(err.kind, BundleReadErrorKind::Invalid);
        assert!(err.details.contains("unsupported bundle format version"));
    }

    #[test]
    fn validate_rejects_empty_manifest_bundle_id() {
        let mut manifest = valid_manifest();
        manifest.bundle_id = "   ".to_string();
        let err = opened_with(manifest, valid_lock()).expect_err("empty manifest id");
        assert!(err.details.contains("manifest is missing bundle_id"));
    }

    #[test]
    fn validate_rejects_empty_lock_bundle_id() {
        let mut lock = valid_lock();
        lock.bundle_id = " ".to_string();
        let err = opened_with(valid_manifest(), lock).expect_err("empty lock id");
        assert!(err.details.contains("lock is missing bundle_id"));
    }

    #[test]
    fn validate_rejects_mismatched_bundle_id() {
        let mut lock = valid_lock();
        lock.bundle_id = "other".to_string();
        let err = opened_with(valid_manifest(), lock).expect_err("mismatched id");
        assert!(err.details.contains("bundle_id do not match"));
    }

    #[test]
    fn validate_rejects_mismatched_requested_mode() {
        let mut lock = valid_lock();
        lock.requested_mode = "different".to_string();
        let err = opened_with(valid_manifest(), lock).expect_err("mismatched mode");
        assert!(err.details.contains("requested_mode do not match"));
    }

    #[test]
    fn validate_rejects_unexpected_artifact_extension() {
        let mut manifest = valid_manifest();
        manifest.artifact_extension = ".zip".to_string();
        let err = opened_with(manifest, valid_lock()).expect_err("bad ext");
        assert!(err.details.contains("unsupported artifact extension"));
    }

    #[test]
    fn validate_rejects_unexpected_workspace_root() {
        let mut lock = valid_lock();
        lock.workspace_root = "other.yaml".to_string();
        let err = opened_with(valid_manifest(), lock).expect_err("bad workspace");
        assert!(err.details.contains("unexpected workspace_root"));
    }

    #[test]
    fn validate_rejects_unexpected_lock_file_name() {
        let mut lock = valid_lock();
        lock.lock_file = "other.json".to_string();
        let err = opened_with(valid_manifest(), lock).expect_err("bad lock file");
        assert!(err.details.contains("unexpected lock_file"));
    }

    #[test]
    fn validate_rejects_mismatched_setup_state_files() {
        let mut manifest = valid_manifest();
        manifest.generated_setup_files = vec!["state/a.json".to_string()];
        let err = opened_with(manifest, valid_lock()).expect_err("setup mismatch");
        assert!(err.details.contains("setup state files do not match"));
    }

    #[test]
    fn normalize_artifact_path_strips_leading_and_trailing_slashes() {
        assert_eq!(
            normalize_artifact_path("/bundle-manifest.json").expect("normalize"),
            "bundle-manifest.json"
        );
        assert_eq!(
            normalize_artifact_path("setup/state.json/").expect("normalize"),
            "setup/state.json"
        );
    }

    #[test]
    fn normalize_artifact_path_rejects_empty_input() {
        let err = normalize_artifact_path("").expect_err("empty path");
        assert!(err.contains("path cannot be empty"));
    }

    #[test]
    fn normalize_artifact_path_rejects_parent_segments() {
        let err = normalize_artifact_path("a/../b").expect_err("parent dir");
        assert!(err.contains("path must be relative"));
    }

    #[test]
    fn normalize_node_path_treats_root_as_none() {
        assert_eq!(normalize_node_path(Path::new("/")).expect("root"), None);
        assert_eq!(
            normalize_node_path(Path::new("/bundle-manifest.json")).expect("file"),
            Some("bundle-manifest.json".to_string())
        );
        assert_eq!(
            normalize_node_path(Path::new("/nested/dir/file.bin")).expect("nested"),
            Some("nested/dir/file.bin".to_string())
        );
    }

    #[test]
    fn build_dir_from_artifact_source_uses_state_build_normalized_layout() {
        let root = Path::new("/tmp/root");
        let path = build_dir_from_artifact_source(root, "demo");
        assert_eq!(path, Path::new("/tmp/root/state/build/demo/normalized"));
    }
}