zlayer-builder 0.11.13

Dockerfile parsing and buildah-based container image building
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
//! Pipeline executor - Coordinates building multiple images with wave-based orchestration
//!
//! This module provides the [`PipelineExecutor`] which processes [`ZPipeline`] manifests,
//! resolving dependencies and building images in parallel waves.
//!
//! # Execution Model
//!
//! Images are grouped into "waves" based on their dependency depth:
//! - **Wave 0**: Images with no dependencies - can all run in parallel
//! - **Wave 1**: Images that depend only on Wave 0 images
//! - **Wave N**: Images that depend only on images from earlier waves
//!
//! Within each wave, all builds run concurrently, sharing the same
//! [`BuildahExecutor`] (and thus cache storage).
//!
//! # Example
//!
//! ```no_run
//! use zlayer_builder::pipeline::{PipelineExecutor, parse_pipeline};
//! use zlayer_builder::BuildahExecutor;
//! use std::path::PathBuf;
//!
//! # async fn example() -> Result<(), zlayer_builder::BuildError> {
//! let yaml = std::fs::read_to_string("ZPipeline.yaml")?;
//! let pipeline = parse_pipeline(&yaml)?;
//!
//! let executor = BuildahExecutor::new_async().await?;
//! let result = PipelineExecutor::new(pipeline, PathBuf::from("."), executor)
//!     .fail_fast(true)
//!     .run()
//!     .await?;
//!
//! println!("Built {} images in {}ms", result.succeeded.len(), result.total_time_ms);
//! # Ok(())
//! # }
//! ```

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

use tokio::sync::Mutex;
use tokio::task::JoinSet;
use tracing::{error, info, warn};

use serde::Deserialize;

use crate::backend::{detect_backend, BuildBackend, ImageOs};

/// Minimal struct to read `source_hash` from a cached image's `config.json`.
/// Separate from `SandboxImageConfig` which is macOS-only.
#[derive(Deserialize)]
struct CachedImageConfig {
    #[serde(default)]
    source_hash: Option<String>,
}
use crate::buildah::{BuildahCommand, BuildahExecutor};
use crate::builder::{BuiltImage, ImageBuilder};
use crate::error::{BuildError, Result};
use zlayer_paths::ZLayerDirs;

use super::types::{PipelineDefaults, PipelineImage, ZPipeline};

#[cfg(feature = "local-registry")]
use zlayer_registry::LocalRegistry;

/// Result of a pipeline execution
#[derive(Debug)]
pub struct PipelineResult {
    /// Images that were successfully built
    pub succeeded: HashMap<String, BuiltImage>,
    /// Images that failed to build (name -> error message)
    pub failed: HashMap<String, String>,
    /// Total execution time in milliseconds
    pub total_time_ms: u64,
}

impl PipelineResult {
    /// Returns true if all images were built successfully
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.failed.is_empty()
    }

    /// Returns the total number of images in the pipeline
    #[must_use]
    pub fn total_images(&self) -> usize {
        self.succeeded.len() + self.failed.len()
    }
}

/// Pipeline executor configuration and runtime
///
/// The executor processes a [`ZPipeline`] manifest, resolving dependencies
/// and building images in parallel waves.
pub struct PipelineExecutor {
    /// The pipeline configuration
    pipeline: ZPipeline,
    /// Base directory for resolving relative paths
    base_dir: PathBuf,
    /// Buildah executor (shared across all builds)
    executor: BuildahExecutor,
    /// Pluggable build backend (buildah, sandbox, etc.).
    ///
    /// When set, builds delegate to this backend instead of using the
    /// `executor` field directly. This is an *explicit* override: when
    /// present, the executor uses the same backend for every image in the
    /// pipeline regardless of the image's target OS.
    backend: Option<Arc<dyn BuildBackend>>,
    /// Per-target-OS backend cache used when `backend` is `None`.
    ///
    /// Each wave may contain images targeting different OSes (e.g. one Linux
    /// image + one Windows image). Rather than re-run `detect_backend()` for
    /// every image, we memoize the backend selected for each [`ImageOs`] the
    /// first time we see it in the pipeline. Shared via `Arc<Mutex<_>>` so
    /// spawned build tasks can resolve their backend concurrently.
    backend_cache: Arc<Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>>>,
    /// Whether to abort on first failure
    fail_fast: bool,
    /// Whether to push images after building
    push_enabled: bool,
    /// Optional local registry for sharing built images between pipeline stages
    #[cfg(feature = "local-registry")]
    local_registry: Option<Arc<LocalRegistry>>,
}

impl PipelineExecutor {
    /// Create a new pipeline executor
    ///
    /// # Arguments
    ///
    /// * `pipeline` - The parsed `ZPipeline` configuration
    /// * `base_dir` - Base directory for resolving relative paths in the pipeline
    /// * `executor` - The buildah executor to use for all builds
    #[must_use]
    pub fn new(pipeline: ZPipeline, base_dir: PathBuf, executor: BuildahExecutor) -> Self {
        // Determine push behavior from pipeline config
        let push_enabled = pipeline.push.after_all;

        Self {
            pipeline,
            base_dir,
            executor,
            backend: None,
            backend_cache: Arc::new(Mutex::new(HashMap::new())),
            fail_fast: true,
            push_enabled,
            #[cfg(feature = "local-registry")]
            local_registry: None,
        }
    }

    /// Create a new pipeline executor with an explicit [`BuildBackend`].
    ///
    /// The backend is used for all build, push, and manifest operations.
    /// A default `BuildahExecutor` is kept for backwards compatibility but
    /// is not used when a backend is set.
    ///
    /// # Arguments
    ///
    /// * `pipeline` - The parsed `ZPipeline` configuration
    /// * `base_dir` - Base directory for resolving relative paths in the pipeline
    /// * `backend`  - The build backend to use for all operations
    #[must_use]
    pub fn with_backend(
        pipeline: ZPipeline,
        base_dir: PathBuf,
        backend: Arc<dyn BuildBackend>,
    ) -> Self {
        let push_enabled = pipeline.push.after_all;

        Self {
            pipeline,
            base_dir,
            executor: BuildahExecutor::default(),
            backend: Some(backend),
            backend_cache: Arc::new(Mutex::new(HashMap::new())),
            fail_fast: true,
            push_enabled,
            #[cfg(feature = "local-registry")]
            local_registry: None,
        }
    }

    /// Set fail-fast mode (default: true)
    ///
    /// When enabled, the executor will abort immediately when any image
    /// fails to build. When disabled, it will continue building independent
    /// images even after failures.
    #[must_use]
    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
        self.fail_fast = fail_fast;
        self
    }

    /// Enable or disable pushing (overrides `pipeline.push.after_all`)
    ///
    /// When enabled and all builds succeed, images will be pushed to their
    /// configured registries.
    #[must_use]
    pub fn push(mut self, enabled: bool) -> Self {
        self.push_enabled = enabled;
        self
    }

    /// Set a local registry for sharing built images between pipeline stages.
    ///
    /// When set, each image build receives a fresh [`LocalRegistry`] handle
    /// pointing at the same on-disk root, so downstream images can resolve
    /// base images that were built by earlier waves.
    #[cfg(feature = "local-registry")]
    #[must_use]
    pub fn with_local_registry(mut self, registry: Arc<LocalRegistry>) -> Self {
        self.local_registry = Some(registry);
        self
    }

    /// Resolve execution order into waves
    ///
    /// Returns a vector of waves, where each wave contains image names
    /// that can be built in parallel. Images in wave N depend only on
    /// images from waves 0..N-1.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - An image depends on an unknown image
    /// - A circular dependency is detected
    fn resolve_execution_order(&self) -> Result<Vec<Vec<String>>> {
        let mut waves: Vec<Vec<String>> = Vec::new();
        let mut assigned: HashSet<String> = HashSet::new();
        let mut remaining: HashSet<String> = self.pipeline.images.keys().cloned().collect();

        // Validate: check for missing dependencies
        for (name, image) in &self.pipeline.images {
            for dep in &image.depends_on {
                if !self.pipeline.images.contains_key(dep) {
                    return Err(BuildError::invalid_instruction(
                        "pipeline",
                        format!("Image '{name}' depends on unknown image '{dep}'"),
                    ));
                }
            }
        }

        // Build waves iteratively
        while !remaining.is_empty() {
            let mut wave: Vec<String> = Vec::new();

            for name in &remaining {
                let image = &self.pipeline.images[name];
                // Can build if all dependencies are already assigned to previous waves
                let deps_satisfied = image.depends_on.iter().all(|d| assigned.contains(d));
                if deps_satisfied {
                    wave.push(name.clone());
                }
            }

            if wave.is_empty() {
                // No images could be added to this wave - circular dependency
                return Err(BuildError::CircularDependency {
                    stages: remaining.into_iter().collect(),
                });
            }

            // Move wave images from remaining to assigned
            for name in &wave {
                remaining.remove(name);
                assigned.insert(name.clone());
            }

            waves.push(wave);
        }

        Ok(waves)
    }

    /// Execute the pipeline
    ///
    /// Builds all images in dependency order, with images in the same wave
    /// running in parallel.
    ///
    /// # Returns
    ///
    /// A [`PipelineResult`] containing information about successful and failed builds.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The dependency graph is invalid (missing deps, cycles)
    /// - Any build fails and `fail_fast` is enabled
    pub async fn run(&self) -> Result<PipelineResult> {
        let start = std::time::Instant::now();
        let waves = self.resolve_execution_order()?;

        let mut succeeded: HashMap<String, BuiltImage> = HashMap::new();
        let mut failed: HashMap<String, String> = HashMap::new();

        info!(
            "Building {} images in {} waves",
            self.pipeline.images.len(),
            waves.len()
        );

        for (wave_idx, wave) in waves.iter().enumerate() {
            info!("Wave {}: {:?}", wave_idx, wave);

            // Check if we should abort due to previous failures
            if self.fail_fast && !failed.is_empty() {
                warn!("Aborting pipeline due to previous failures (fail_fast enabled)");
                break;
            }

            // Build all images in this wave concurrently
            let wave_results = self.build_wave(wave).await;

            // Process results
            for (name, result) in wave_results {
                match result {
                    Ok(image) => {
                        info!("[{}] Build succeeded: {}", name, image.image_id);
                        succeeded.insert(name, image);
                    }
                    Err(e) => {
                        error!("[{}] Build failed: {}", name, e);
                        failed.insert(name.clone(), e.to_string());

                        if self.fail_fast {
                            // Return early with the first error
                            return Err(e);
                        }
                    }
                }
            }
        }

        // Push phase (only if all succeeded and push enabled)
        if self.push_enabled && failed.is_empty() {
            info!("Pushing {} images", succeeded.len());

            // Ensure secondary tags have on-disk directories (sandbox backend
            // stores the rootfs under the first tag only; additional tags need
            // to be created before push can find them).
            if let Some(ref backend) = self.backend {
                for image in succeeded.values() {
                    if image.tags.len() > 1 {
                        let first = &image.tags[0];
                        for secondary in &image.tags[1..] {
                            if let Err(e) = backend.tag_image(first, secondary).await {
                                warn!("Failed to tag {} as {}: {}", first, secondary, e);
                            }
                        }
                    }
                }
            }

            for (name, image) in &succeeded {
                for tag in &image.tags {
                    let push_result = if image.is_manifest {
                        self.push_manifest(tag).await
                    } else {
                        self.push_image(tag).await
                    };

                    if let Err(e) = push_result {
                        warn!("[{}] Failed to push {}: {}", name, tag, e);
                        // Push failures don't fail the overall pipeline
                        // since the images were built successfully
                    } else {
                        info!("[{}] Pushed: {}", name, tag);
                    }
                }
            }
        }

        #[allow(clippy::cast_possible_truncation)]
        let total_time_ms = start.elapsed().as_millis() as u64;

        Ok(PipelineResult {
            succeeded,
            failed,
            total_time_ms,
        })
    }

    /// Build all images in a wave concurrently
    ///
    /// Each image is checked for multi-platform configuration. Images with
    /// 2+ platforms use `build_multiplatform_image` (manifest list), images
    /// with exactly 1 platform use `build_single_image` with that platform
    /// set, and images with no platforms use the native platform (existing
    /// behavior).
    ///
    /// # Per-image backend selection
    ///
    /// When the executor was built via [`PipelineExecutor::with_backend`]
    /// (i.e. `self.backend.is_some()`), that explicit backend is used for
    /// every image. Otherwise the target OS is parsed from each image's
    /// `platforms` field and a backend is resolved via [`detect_backend`],
    /// cached in `self.backend_cache` to avoid re-detection. An image that
    /// cannot resolve a backend (e.g. Windows image on a Linux host) fails
    /// only that image — other images in the wave continue.
    ///
    /// Returns a vector of (name, result) tuples for each image in the wave.
    async fn build_wave(&self, wave: &[String]) -> Vec<(String, Result<BuiltImage>)> {
        // Create shared data for spawned tasks
        let pipeline = Arc::new(self.pipeline.clone());
        let base_dir = Arc::new(self.base_dir.clone());
        let executor = self.executor.clone();
        let explicit_backend = self.backend.clone();
        let backend_cache = Arc::clone(&self.backend_cache);

        // Extract local registry root path (if configured) so spawned tasks
        // can create their own LocalRegistry handles pointing at the same store.
        #[cfg(feature = "local-registry")]
        let registry_root: Option<PathBuf> =
            self.local_registry.as_ref().map(|r| r.root().to_path_buf());
        #[cfg(not(feature = "local-registry"))]
        let registry_root: Option<PathBuf> = None;

        let mut set = JoinSet::new();

        for name in wave {
            let name = name.clone();
            let pipeline = Arc::clone(&pipeline);
            let base_dir = Arc::clone(&base_dir);
            let executor = executor.clone();
            let explicit_backend = explicit_backend.clone();
            let backend_cache = Arc::clone(&backend_cache);
            let registry_root = registry_root.clone();

            set.spawn(async move {
                let result = build_one_image(
                    &name,
                    &pipeline,
                    &base_dir,
                    executor,
                    explicit_backend,
                    &backend_cache,
                    registry_root.as_deref(),
                )
                .await;
                (name, result)
            });
        }

        // Collect all results
        let mut results = Vec::new();
        while let Some(join_result) = set.join_next().await {
            match join_result {
                Ok((name, result)) => {
                    results.push((name, result));
                }
                Err(e) => {
                    // Task panicked
                    error!("Build task panicked: {}", e);
                    results.push((
                        "unknown".to_string(),
                        Err(BuildError::invalid_instruction(
                            "pipeline",
                            format!("Build task panicked: {e}"),
                        )),
                    ));
                }
            }
        }

        results
    }

    /// Push a regular image to its registry
    async fn push_image(&self, tag: &str) -> Result<()> {
        if let Some(ref backend) = self.backend {
            return backend.push_image(tag, None).await;
        }
        let cmd = BuildahCommand::push(tag);
        self.executor.execute_checked(&cmd).await?;
        Ok(())
    }

    /// Push a manifest list (and all referenced images) to its registry
    async fn push_manifest(&self, tag: &str) -> Result<()> {
        if let Some(ref backend) = self.backend {
            let destination = format!("docker://{tag}");
            return backend.manifest_push(tag, &destination).await;
        }
        let destination = format!("docker://{tag}");
        let cmd = BuildahCommand::manifest_push(tag, &destination);
        self.executor.execute_checked(&cmd).await?;
        Ok(())
    }
}

/// Get the effective platforms for an image, considering defaults.
///
/// If the image specifies its own platforms, those take precedence.
/// Otherwise, the pipeline-level defaults are used. An empty result
/// means "native platform only" (no multi-arch).
fn effective_platforms(image: &PipelineImage, defaults: &PipelineDefaults) -> Vec<String> {
    if image.platforms.is_empty() {
        defaults.platforms.clone()
    } else {
        image.platforms.clone()
    }
}

/// Parse the target OS from an image's effective `platforms` list.
///
/// Rules:
/// - `explicit_os` (e.g. `PipelineImage.os:`) takes precedence — when
///   `Some(os)`, we also verify each `platforms` entry parses to the same
///   OS so a misconfigured platform list surfaces loudly rather than being
///   silently overridden.
/// - Empty list with no explicit OS → [`ImageOs::Linux`] (the historical default).
/// - All entries parse to the same OS → that OS.
/// - Any entry fails to parse → an error naming the bad entry.
/// - Entries parse to *different* OSes → an error, because buildah cannot
///   assemble a single manifest list across OSes and the user should split
///   the image into separate `PipelineImage` entries.
fn target_os_for_image(platforms: &[String], explicit_os: Option<ImageOs>) -> Result<ImageOs> {
    // Parse every entry so we still catch malformed strings even when an
    // explicit OS is supplied; the L-7 validation semantics stay intact.
    let mut selected: Option<ImageOs> = None;
    for platform in platforms {
        let os = ImageOs::from_str(platform).map_err(|e| {
            BuildError::invalid_instruction(
                "pipeline",
                format!("unrecognized platform '{platform}': {e}"),
            )
        })?;
        match selected {
            None => selected = Some(os),
            Some(existing) if existing == os => {}
            Some(existing) => {
                return Err(BuildError::invalid_instruction(
                    "pipeline",
                    format!(
                        "multi-platform images cannot mix OSes in a single entry \
                         (found {existing:?} and {os:?} in platforms={platforms:?}); \
                         split into separate PipelineImage entries"
                    ),
                ));
            }
        }
    }

    if let Some(explicit) = explicit_os {
        if let Some(from_platforms) = selected {
            if from_platforms != explicit {
                return Err(BuildError::invalid_instruction(
                    "pipeline",
                    format!(
                        "explicit os={explicit:?} conflicts with OS inferred from \
                         platforms={platforms:?} (got {from_platforms:?}); remove one \
                         or make them agree"
                    ),
                ));
            }
        }
        return Ok(explicit);
    }

    Ok(selected.unwrap_or(ImageOs::Linux))
}

/// Resolve a build backend for `target_os`, using `cache` to memoize prior
/// detections.
///
/// If `explicit` is `Some`, it is returned unconditionally — callers that
/// constructed the executor via [`PipelineExecutor::with_backend`] have opted
/// into a single backend and we do not second-guess them. Otherwise we check
/// the cache and fall back to [`detect_backend`] on a miss, storing the
/// result before returning.
async fn backend_for(
    target_os: ImageOs,
    cache: &Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>>,
    explicit: Option<Arc<dyn BuildBackend>>,
) -> Result<Arc<dyn BuildBackend>> {
    if let Some(backend) = explicit {
        return Ok(backend);
    }

    // Fast path: already detected.
    {
        let guard = cache.lock().await;
        if let Some(backend) = guard.get(&target_os) {
            return Ok(Arc::clone(backend));
        }
    }

    // Slow path: detect + memoize. Hold the lock across detection so two
    // concurrent images targeting the same OS share one detection call.
    let mut guard = cache.lock().await;
    if let Some(backend) = guard.get(&target_os) {
        return Ok(Arc::clone(backend));
    }
    let backend = detect_backend(target_os).await?;
    guard.insert(target_os, Arc::clone(&backend));
    Ok(backend)
}

/// Build a single pipeline image end-to-end.
///
/// Parses the target OS, resolves a backend (with caching), logs the build
/// intent, then dispatches to the single-platform or multi-platform path
/// based on the effective platform list.
#[allow(clippy::too_many_arguments)]
async fn build_one_image(
    name: &str,
    pipeline: &ZPipeline,
    base_dir: &Path,
    executor: BuildahExecutor,
    explicit_backend: Option<Arc<dyn BuildBackend>>,
    backend_cache: &Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>>,
    registry_root: Option<&Path>,
) -> Result<BuiltImage> {
    let image_config = &pipeline.images[name];
    let platforms = effective_platforms(image_config, &pipeline.defaults);

    // L-2: `PipelineImage.os:` takes precedence over OS parsed from platforms.
    let target_os = target_os_for_image(&platforms, image_config.os)?;
    info!(
        "Building image '{}' (target_os={:?}, platforms={:?}, explicit_os={:?})",
        name, target_os, platforms, image_config.os
    );

    let backend = backend_for(target_os, backend_cache, explicit_backend).await?;

    match platforms.len() {
        // No platforms specified — native build (existing behavior)
        0 => {
            build_single_image(
                name,
                pipeline,
                base_dir,
                executor,
                Some(backend),
                None,
                registry_root,
            )
            .await
        }
        // Single platform — use build_single_image with platform set
        1 => {
            let platform = platforms[0].clone();
            build_single_image(
                name,
                pipeline,
                base_dir,
                executor,
                Some(backend),
                Some(&platform),
                registry_root,
            )
            .await
        }
        // Multiple platforms — build each, then create manifest list
        _ => {
            build_multiplatform_image(
                name,
                pipeline,
                base_dir,
                executor,
                Some(backend),
                &platforms,
                registry_root,
            )
            .await
        }
    }
}

/// Extract architecture suffix from a platform string.
///
/// # Examples
///
/// - `"linux/amd64"` -> `"amd64"`
/// - `"linux/arm64"` -> `"arm64"`
/// - `"linux/arm64/v8"` -> `"arm64-v8"`
/// - `"linux"` -> `"linux"`
fn platform_to_suffix(platform: &str) -> String {
    let parts: Vec<&str> = platform.split('/').collect();
    match parts.len() {
        0 | 1 => platform.replace('/', "-"),
        2 => parts[1].to_string(),
        _ => format!("{}-{}", parts[1], parts[2]),
    }
}

/// Apply pipeline configuration (`build_args`, format, `cache_mounts`, retries, `no_cache`)
/// to an [`ImageBuilder`].
///
/// This merges default-level and per-image settings, with per-image values taking
/// precedence for scalar settings and being additive for collections.
fn apply_pipeline_config(
    mut builder: ImageBuilder,
    image_config: &PipelineImage,
    defaults: &PipelineDefaults,
) -> ImageBuilder {
    // Merge build_args: defaults + per-image (per-image overrides defaults)
    let mut args = defaults.build_args.clone();
    args.extend(image_config.build_args.clone());
    builder = builder.build_args(args);

    // Format (per-image overrides default)
    if let Some(fmt) = image_config.format.as_ref().or(defaults.format.as_ref()) {
        builder = builder.format(fmt);
    }

    // No cache (per-image overrides default)
    if image_config.no_cache.unwrap_or(defaults.no_cache) {
        builder = builder.no_cache();
    }

    // Cache mounts: defaults + per-image (per-image are additive)
    let mut cache_mounts = defaults.cache_mounts.clone();
    cache_mounts.extend(image_config.cache_mounts.clone());
    if !cache_mounts.is_empty() {
        let run_mounts: Vec<_> = cache_mounts
            .iter()
            .map(crate::zimage::convert_cache_mount)
            .collect();
        builder = builder.default_cache_mounts(run_mounts);
    }

    // Retries (per-image overrides default)
    let retries = image_config.retries.or(defaults.retries).unwrap_or(0);
    if retries > 0 {
        builder = builder.retries(retries);
    }

    builder
}

/// Detect whether a build file is a ZImagefile/YAML or a Dockerfile and
/// configure the builder accordingly.
fn apply_build_file(builder: ImageBuilder, file_path: &Path) -> ImageBuilder {
    let file_name = file_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
    let extension = file_path
        .extension()
        .map(|e| e.to_string_lossy().to_string())
        .unwrap_or_default();

    if extension == "yaml" || extension == "yml" || file_name.starts_with("ZImagefile") {
        builder.zimagefile(file_path)
    } else {
        builder.dockerfile(file_path)
    }
}

/// Compute a SHA-256 hash of a file's contents for content-based cache invalidation.
///
/// Returns `None` if the file cannot be read.
async fn compute_file_hash(path: &Path) -> Option<String> {
    use sha2::{Digest, Sha256};

    let content = tokio::fs::read(path).await.ok()?;
    let mut hasher = Sha256::new();
    hasher.update(&content);
    Some(format!("{:x}", hasher.finalize()))
}

/// Sanitize an image reference into a filesystem-safe directory name.
///
/// Mirrors the logic in `sandbox_builder::sanitize_image_name`.
fn sanitize_image_name_for_cache(image: &str) -> String {
    image.replace(['/', ':', '@'], "_")
}

/// Check if a cached sandbox image at `data_dir/images/{sanitized}/config.json`
/// has a `source_hash` matching `expected_hash`.
///
/// Returns the sanitized image name if a match is found.
async fn check_cached_image_hash(
    data_dir: &Path,
    tag: &str,
    expected_hash: &str,
) -> Option<String> {
    let sanitized = sanitize_image_name_for_cache(tag);
    let config_path = data_dir.join("images").join(&sanitized).join("config.json");
    let data = tokio::fs::read_to_string(&config_path).await.ok()?;
    let config: CachedImageConfig = serde_json::from_str(&data).ok()?;
    if config.source_hash.as_deref() == Some(expected_hash) {
        Some(sanitized)
    } else {
        None
    }
}

/// Build a single image from the pipeline
///
/// This is extracted as a separate function to make it easier to spawn
/// in a tokio task without borrowing issues.
///
/// When `platform` is `Some`, the builder is configured for that specific
/// platform (e.g. `"linux/arm64"`), enabling cross-architecture builds.
#[cfg_attr(not(feature = "local-registry"), allow(unused_variables))]
async fn build_single_image(
    name: &str,
    pipeline: &ZPipeline,
    base_dir: &Path,
    executor: BuildahExecutor,
    backend: Option<Arc<dyn BuildBackend>>,
    platform: Option<&str>,
    registry_root: Option<&Path>,
) -> Result<BuiltImage> {
    let image_config = &pipeline.images[name];
    let context = base_dir.join(&image_config.context);
    let file_path = base_dir.join(&image_config.file);

    // Content-based cache invalidation: hash the build file and check if the
    // output image was already built from identical source content.
    let file_hash = compute_file_hash(&file_path).await;
    if let Some(ref hash) = file_hash {
        let data_dir = ZLayerDirs::default_data_dir();

        let expanded_tags: Vec<String> = image_config
            .tags
            .iter()
            .map(|t| expand_tag_with_vars(t, &pipeline.vars))
            .collect();

        // Check the first tag — if it has a cached image with matching hash, skip the build
        if let Some(first_tag) = expanded_tags.first() {
            if let Some(cached_id) = check_cached_image_hash(&data_dir, first_tag, hash).await {
                info!(
                    "[{}] Skipping build — cached image hash matches ({})",
                    name, cached_id
                );
                return Ok(BuiltImage {
                    image_id: cached_id,
                    tags: expanded_tags,
                    layer_count: 1,
                    size: 0,
                    build_time_ms: 0,
                    is_manifest: false,
                });
            }
        }
    }

    let effective_backend: Arc<dyn BuildBackend> = backend
        .unwrap_or_else(|| Arc::new(crate::backend::BuildahBackend::with_executor(executor)));
    let mut builder = ImageBuilder::with_backend(&context, effective_backend)?;

    // Determine if this is a ZImagefile or Dockerfile based on extension/name
    builder = apply_build_file(builder, &file_path);

    // Pass the source hash so the sandbox builder stores it for future cache checks
    if let Some(hash) = file_hash {
        builder = builder.source_hash(hash);
    }

    // Set platform if specified
    if let Some(plat) = platform {
        builder = builder.platform(plat);
    }

    // Apply tags with variable expansion
    for tag in &image_config.tags {
        let expanded = expand_tag_with_vars(tag, &pipeline.vars);
        builder = builder.tag(expanded);
    }

    // Apply shared pipeline config (build_args, format, no_cache, cache_mounts, retries)
    builder = apply_pipeline_config(builder, image_config, &pipeline.defaults);

    // Wire up local registry so this build can resolve images from earlier waves
    #[cfg(feature = "local-registry")]
    if let Some(root) = registry_root {
        let shared_registry = LocalRegistry::new(root.to_path_buf()).await.map_err(|e| {
            BuildError::invalid_instruction(
                "pipeline",
                format!("failed to open local registry: {e}"),
            )
        })?;
        builder = builder.with_local_registry(shared_registry);
    }

    builder.build().await
}

/// Build an image for multiple platforms and create a manifest list.
///
/// Each platform is built sequentially (QEMU can be flaky with parallel
/// cross-arch builds), then a buildah manifest list is created that
/// references all per-platform images.
#[cfg_attr(not(feature = "local-registry"), allow(unused_variables))]
async fn build_multiplatform_image(
    name: &str,
    pipeline: &ZPipeline,
    base_dir: &Path,
    executor: BuildahExecutor,
    backend: Option<Arc<dyn BuildBackend>>,
    platforms: &[String],
    registry_root: Option<&Path>,
) -> Result<BuiltImage> {
    let image_config = &pipeline.images[name];
    let start_time = std::time::Instant::now();

    // Expand tags with variables
    let expanded_tags: Vec<String> = image_config
        .tags
        .iter()
        .map(|t| expand_tag_with_vars(t, &pipeline.vars))
        .collect();

    let manifest_name = expanded_tags
        .first()
        .cloned()
        .unwrap_or_else(|| format!("zlayer-manifest-{name}"));

    // Build for each platform sequentially (QEMU can be flaky with parallel cross-arch)
    let mut arch_tags: Vec<String> = Vec::new();
    let mut total_layers = 0usize;
    let mut total_size = 0u64;

    for platform in platforms {
        let suffix = platform_to_suffix(platform);
        let platform_tags: Vec<String> = expanded_tags
            .iter()
            .map(|t| format!("{t}-{suffix}"))
            .collect();

        info!("[{name}] Building for platform {platform}");

        // Build with platform-specific tags
        let context = base_dir.join(&image_config.context);
        let file_path = base_dir.join(&image_config.file);

        let effective_backend: Arc<dyn BuildBackend> = match backend {
            Some(ref b) => Arc::clone(b),
            None => Arc::new(crate::backend::BuildahBackend::with_executor(
                executor.clone(),
            )),
        };
        let mut builder = ImageBuilder::with_backend(&context, effective_backend)?;

        // Determine file type (same detection as build_single_image)
        builder = apply_build_file(builder, &file_path);

        // Set platform
        builder = builder.platform(platform);

        // Apply platform-specific tags
        for tag in &platform_tags {
            builder = builder.tag(tag);
        }

        // Apply shared config (build_args, format, no_cache, cache_mounts, retries)
        builder = apply_pipeline_config(builder, image_config, &pipeline.defaults);

        // Wire up local registry so this build can resolve images from earlier waves
        #[cfg(feature = "local-registry")]
        if let Some(root) = registry_root {
            let shared_registry = LocalRegistry::new(root.to_path_buf()).await.map_err(|e| {
                BuildError::invalid_instruction(
                    "pipeline",
                    format!("failed to open local registry: {e}"),
                )
            })?;
            builder = builder.with_local_registry(shared_registry);
        }

        let built = builder.build().await?;
        total_layers += built.layer_count;
        total_size += built.size;

        if let Some(first_tag) = platform_tags.first() {
            arch_tags.push(first_tag.clone());
        }
    }

    // Assemble the manifest list from per-platform images
    assemble_manifest(
        name,
        &manifest_name,
        &arch_tags,
        &expanded_tags,
        backend.as_ref(),
        &executor,
    )
    .await?;

    #[allow(clippy::cast_possible_truncation)]
    let build_time_ms = start_time.elapsed().as_millis() as u64;

    Ok(BuiltImage {
        image_id: manifest_name,
        tags: expanded_tags,
        layer_count: total_layers,
        size: total_size,
        build_time_ms,
        is_manifest: true,
    })
}

/// Create a manifest list, add per-platform images, and apply additional tags.
///
/// This is a helper extracted from [`build_multiplatform_image`] to keep that
/// function under the line-count limit.
async fn assemble_manifest(
    name: &str,
    manifest_name: &str,
    arch_tags: &[String],
    expanded_tags: &[String],
    backend: Option<&Arc<dyn BuildBackend>>,
    executor: &BuildahExecutor,
) -> Result<()> {
    // Create manifest list — delegate to backend if available
    info!("[{name}] Creating manifest: {manifest_name}");
    if let Some(backend) = backend {
        backend
            .manifest_create(manifest_name)
            .await
            .map_err(|e| BuildError::pipeline_error(format!("manifest create failed: {e}")))?;
    } else {
        executor
            .execute_checked(&BuildahCommand::manifest_create(manifest_name))
            .await
            .map_err(|e| BuildError::pipeline_error(format!("manifest create failed: {e}")))?;
    }

    // Add each arch image to the manifest
    for arch_tag in arch_tags {
        info!("[{name}] Adding to manifest: {arch_tag}");
        if let Some(backend) = backend {
            backend
                .manifest_add(manifest_name, arch_tag)
                .await
                .map_err(|e| BuildError::pipeline_error(format!("manifest add failed: {e}")))?;
        } else {
            executor
                .execute_checked(&BuildahCommand::manifest_add(manifest_name, arch_tag))
                .await
                .map_err(|e| BuildError::pipeline_error(format!("manifest add failed: {e}")))?;
        }
    }

    // Tag the manifest with additional tags
    for tag in expanded_tags.iter().skip(1) {
        if let Some(backend) = backend {
            backend
                .tag_image(manifest_name, tag)
                .await
                .map_err(|e| BuildError::pipeline_error(format!("manifest tag failed: {e}")))?;
        } else {
            executor
                .execute_checked(&BuildahCommand::tag(manifest_name, tag))
                .await
                .map_err(|e| BuildError::pipeline_error(format!("manifest tag failed: {e}")))?;
        }
    }

    Ok(())
}

/// Expand variables in a tag string
///
/// Standalone function for use in spawned tasks.
fn expand_tag_with_vars(tag: &str, vars: &HashMap<String, String>) -> String {
    let mut result = tag.to_string();
    for (key, value) in vars {
        result = result.replace(&format!("${{{key}}}"), value);
    }
    result
}

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

    #[test]
    fn test_resolve_execution_order_simple() {
        let yaml = r"
images:
  app:
    file: Dockerfile
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        );

        let waves = executor.resolve_execution_order().unwrap();
        assert_eq!(waves.len(), 1);
        assert_eq!(waves[0], vec!["app"]);
    }

    #[test]
    fn test_resolve_execution_order_with_deps() {
        let yaml = r"
images:
  base:
    file: Dockerfile.base
  app:
    file: Dockerfile.app
    depends_on: [base]
  test:
    file: Dockerfile.test
    depends_on: [app]
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        );

        let waves = executor.resolve_execution_order().unwrap();
        assert_eq!(waves.len(), 3);
        assert_eq!(waves[0], vec!["base"]);
        assert_eq!(waves[1], vec!["app"]);
        assert_eq!(waves[2], vec!["test"]);
    }

    #[test]
    fn test_resolve_execution_order_parallel() {
        let yaml = r"
images:
  base:
    file: Dockerfile.base
  app1:
    file: Dockerfile.app1
    depends_on: [base]
  app2:
    file: Dockerfile.app2
    depends_on: [base]
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        );

        let waves = executor.resolve_execution_order().unwrap();
        assert_eq!(waves.len(), 2);
        assert_eq!(waves[0], vec!["base"]);
        // app1 and app2 should be in the same wave (order may vary)
        assert_eq!(waves[1].len(), 2);
        assert!(waves[1].contains(&"app1".to_string()));
        assert!(waves[1].contains(&"app2".to_string()));
    }

    #[test]
    fn test_resolve_execution_order_missing_dep() {
        let yaml = r"
images:
  app:
    file: Dockerfile
    depends_on: [missing]
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        );

        let result = executor.resolve_execution_order();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("missing"));
    }

    #[test]
    fn test_resolve_execution_order_circular() {
        let yaml = r"
images:
  a:
    file: Dockerfile.a
    depends_on: [b]
  b:
    file: Dockerfile.b
    depends_on: [a]
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        );

        let result = executor.resolve_execution_order();
        assert!(result.is_err());
        match result.unwrap_err() {
            BuildError::CircularDependency { stages } => {
                assert!(stages.contains(&"a".to_string()));
                assert!(stages.contains(&"b".to_string()));
            }
            e => panic!("Expected CircularDependency error, got: {e:?}"),
        }
    }

    #[test]
    fn test_expand_tag() {
        let mut vars = HashMap::new();
        vars.insert("VERSION".to_string(), "1.0.0".to_string());
        vars.insert("REGISTRY".to_string(), "ghcr.io/myorg".to_string());

        let tag = "${REGISTRY}/app:${VERSION}";
        let expanded = expand_tag_with_vars(tag, &vars);
        assert_eq!(expanded, "ghcr.io/myorg/app:1.0.0");
    }

    #[test]
    fn test_expand_tag_partial() {
        let mut vars = HashMap::new();
        vars.insert("VERSION".to_string(), "1.0.0".to_string());

        // Unknown vars are left as-is
        let tag = "myapp:${VERSION}-${UNKNOWN}";
        let expanded = expand_tag_with_vars(tag, &vars);
        assert_eq!(expanded, "myapp:1.0.0-${UNKNOWN}");
    }

    #[test]
    fn test_pipeline_result_is_success() {
        let mut result = PipelineResult {
            succeeded: HashMap::new(),
            failed: HashMap::new(),
            total_time_ms: 100,
        };

        assert!(result.is_success());

        result.failed.insert("app".to_string(), "error".to_string());
        assert!(!result.is_success());
    }

    #[test]
    fn test_pipeline_result_total_images() {
        let mut result = PipelineResult {
            succeeded: HashMap::new(),
            failed: HashMap::new(),
            total_time_ms: 100,
        };

        result.succeeded.insert(
            "app1".to_string(),
            BuiltImage {
                image_id: "sha256:abc".to_string(),
                tags: vec!["app1:latest".to_string()],
                layer_count: 5,
                size: 0,
                build_time_ms: 50,
                is_manifest: false,
            },
        );
        result
            .failed
            .insert("app2".to_string(), "error".to_string());

        assert_eq!(result.total_images(), 2);
    }

    #[test]
    fn test_builder_methods() {
        let yaml = r"
images:
  app:
    file: Dockerfile
push:
  after_all: true
";
        let pipeline = parse_pipeline(yaml).unwrap();
        let executor = PipelineExecutor::new(
            pipeline,
            PathBuf::from("/tmp"),
            BuildahExecutor::with_path("/usr/bin/buildah"),
        )
        .fail_fast(false)
        .push(false);

        assert!(!executor.fail_fast);
        assert!(!executor.push_enabled);
    }

    /// Helper to create a minimal `PipelineImage` for tests.
    fn test_pipeline_image() -> PipelineImage {
        PipelineImage {
            file: PathBuf::from("Dockerfile"),
            context: PathBuf::from("."),
            tags: vec![],
            build_args: HashMap::new(),
            depends_on: vec![],
            no_cache: None,
            format: None,
            cache_mounts: vec![],
            retries: None,
            platforms: vec![],
            os: None,
        }
    }

    #[test]
    fn test_platform_to_suffix() {
        assert_eq!(platform_to_suffix("linux/amd64"), "amd64");
        assert_eq!(platform_to_suffix("linux/arm64"), "arm64");
        assert_eq!(platform_to_suffix("linux/arm64/v8"), "arm64-v8");
        assert_eq!(platform_to_suffix("linux"), "linux");
    }

    #[test]
    fn test_effective_platforms_image_overrides() {
        let defaults = PipelineDefaults {
            platforms: vec!["linux/amd64".into()],
            ..Default::default()
        };
        let image = PipelineImage {
            platforms: vec!["linux/arm64".into()],
            ..test_pipeline_image()
        };
        assert_eq!(effective_platforms(&image, &defaults), vec!["linux/arm64"]);
    }

    #[test]
    fn test_effective_platforms_inherits_defaults() {
        let defaults = PipelineDefaults {
            platforms: vec!["linux/amd64".into()],
            ..Default::default()
        };
        let image = test_pipeline_image();
        assert_eq!(effective_platforms(&image, &defaults), vec!["linux/amd64"]);
    }

    #[test]
    fn test_effective_platforms_empty() {
        let defaults = PipelineDefaults::default();
        let image = test_pipeline_image();
        assert!(effective_platforms(&image, &defaults).is_empty());
    }

    #[test]
    fn test_platform_to_suffix_edge_cases() {
        // Empty string
        assert_eq!(platform_to_suffix(""), "");
        // Single component
        assert_eq!(platform_to_suffix("linux"), "linux");
        // Four components (unusual but handle gracefully)
        assert_eq!(platform_to_suffix("linux/arm/v7/extra"), "arm-v7");
    }

    #[test]
    fn test_effective_platforms_multiple_defaults() {
        let defaults = PipelineDefaults {
            platforms: vec!["linux/amd64".into(), "linux/arm64".into()],
            ..Default::default()
        };
        let image = test_pipeline_image();
        assert_eq!(
            effective_platforms(&image, &defaults),
            vec!["linux/amd64", "linux/arm64"]
        );
    }

    #[test]
    fn test_effective_platforms_image_overrides_multiple() {
        let defaults = PipelineDefaults {
            platforms: vec!["linux/amd64".into(), "linux/arm64".into()],
            ..Default::default()
        };
        let image = PipelineImage {
            platforms: vec!["linux/s390x".into()],
            ..test_pipeline_image()
        };
        // Image platforms completely replace defaults, not merge
        assert_eq!(effective_platforms(&image, &defaults), vec!["linux/s390x"]);
    }

    // -----------------------------------------------------------------------
    // L-7: per-image backend selection
    // -----------------------------------------------------------------------

    #[test]
    fn test_target_os_for_image_empty_defaults_to_linux() {
        assert_eq!(target_os_for_image(&[], None).unwrap(), ImageOs::Linux);
    }

    #[test]
    fn test_target_os_for_image_single_linux() {
        assert_eq!(
            target_os_for_image(&["linux/amd64".to_string()], None).unwrap(),
            ImageOs::Linux
        );
    }

    #[test]
    fn test_target_os_for_image_single_windows() {
        assert_eq!(
            target_os_for_image(&["windows/amd64".to_string()], None).unwrap(),
            ImageOs::Windows
        );
    }

    #[test]
    fn test_target_os_for_image_multi_same_os() {
        // All-Linux entries should collapse to a single Linux backend.
        let plats = vec!["linux/amd64".to_string(), "linux/arm64".to_string()];
        assert_eq!(target_os_for_image(&plats, None).unwrap(), ImageOs::Linux);
    }

    #[test]
    fn test_target_os_for_image_mixed_os_is_rejected() {
        // Mixed OSes in a single entry must fail — there is no single backend
        // (or buildah manifest list) that can straddle Linux + Windows.
        let plats = vec!["linux/amd64".to_string(), "windows/amd64".to_string()];
        let err = target_os_for_image(&plats, None).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("cannot mix OSes"),
            "expected mix-of-OSes error, got: {msg}"
        );
        assert!(
            msg.contains("split into separate PipelineImage entries"),
            "expected remediation hint, got: {msg}"
        );
    }

    #[test]
    fn test_target_os_for_image_unrecognized_platform() {
        let plats = vec!["plan9/amd64".to_string()];
        let err = target_os_for_image(&plats, None).unwrap_err();
        assert!(err.to_string().contains("unrecognized platform"));
    }

    #[test]
    fn test_target_os_for_image_explicit_os_wins_empty_platforms() {
        // L-2: explicit os: on PipelineImage overrides the default Linux
        // inference when no platforms are set.
        assert_eq!(
            target_os_for_image(&[], Some(ImageOs::Windows)).unwrap(),
            ImageOs::Windows
        );
    }

    #[test]
    fn test_target_os_for_image_explicit_os_matches_platforms() {
        // Explicit os: agrees with the OS portion of platforms — totally fine.
        let plats = vec!["windows/amd64".to_string()];
        assert_eq!(
            target_os_for_image(&plats, Some(ImageOs::Windows)).unwrap(),
            ImageOs::Windows
        );
    }

    #[test]
    fn test_target_os_for_image_explicit_os_conflicts_with_platforms() {
        // Explicit os: disagrees with platforms — must fail loudly so we don't
        // silently override user intent.
        let plats = vec!["linux/amd64".to_string()];
        let err = target_os_for_image(&plats, Some(ImageOs::Windows)).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("explicit os=")
                && msg.contains("conflicts with OS inferred from platforms"),
            "expected conflict error, got: {msg}"
        );
    }

    /// A fake [`BuildBackend`] that records which tags it was asked to build
    /// and returns synthetic [`BuiltImage`] values. Used to exercise the
    /// per-image routing without invoking the real buildah CLI.
    struct FakeBackend {
        name: &'static str,
    }

    #[async_trait::async_trait]
    impl BuildBackend for FakeBackend {
        async fn build_image(
            &self,
            _context: &Path,
            _dockerfile: &crate::dockerfile::Dockerfile,
            options: &crate::builder::BuildOptions,
            _event_tx: Option<std::sync::mpsc::Sender<crate::tui::BuildEvent>>,
        ) -> Result<BuiltImage> {
            Ok(BuiltImage {
                image_id: format!("{}:fake-id", self.name),
                tags: options.tags.clone(),
                layer_count: 1,
                size: 0,
                build_time_ms: 1,
                is_manifest: false,
            })
        }

        async fn push_image(
            &self,
            _tag: &str,
            _auth: Option<&crate::builder::RegistryAuth>,
        ) -> Result<()> {
            Ok(())
        }

        async fn tag_image(&self, _image: &str, _new_tag: &str) -> Result<()> {
            Ok(())
        }

        async fn manifest_create(&self, _name: &str) -> Result<()> {
            Ok(())
        }

        async fn manifest_add(&self, _manifest: &str, _image: &str) -> Result<()> {
            Ok(())
        }

        async fn manifest_push(&self, _name: &str, _destination: &str) -> Result<()> {
            Ok(())
        }

        async fn is_available(&self) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            self.name
        }
    }

    #[tokio::test]
    async fn test_backend_for_uses_explicit_override() {
        // When `explicit` is supplied, `backend_for` must return that backend
        // regardless of target_os and must not touch the cache.
        let explicit: Arc<dyn BuildBackend> = Arc::new(FakeBackend { name: "explicit" });
        let cache: Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>> = Mutex::new(HashMap::new());
        let resolved = backend_for(ImageOs::Linux, &cache, Some(Arc::clone(&explicit)))
            .await
            .unwrap();
        assert_eq!(resolved.name(), "explicit");
        assert!(
            cache.lock().await.is_empty(),
            "explicit override should not populate cache"
        );
    }

    #[tokio::test]
    async fn test_backend_for_cache_hit_returns_cached() {
        // If the cache already has an entry for the target_os, `backend_for`
        // must return it verbatim without calling detect_backend.
        let fake: Arc<dyn BuildBackend> = Arc::new(FakeBackend { name: "cached" });
        let cache: Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>> = Mutex::new(HashMap::new());
        cache.lock().await.insert(ImageOs::Linux, Arc::clone(&fake));
        let resolved = backend_for(ImageOs::Linux, &cache, None).await.unwrap();
        assert_eq!(resolved.name(), "cached");
    }

    /// Mixed-OS wave: one Linux image (served by a seeded fake backend) and
    /// one Windows image. On a non-Windows host, `detect_backend(Windows)`
    /// returns an error from L-6; the Linux build should still succeed via
    /// the cached fake backend. This verifies per-image backend selection
    /// and per-image error isolation within a single wave.
    #[cfg(not(target_os = "windows"))]
    #[tokio::test]
    async fn test_build_one_image_isolates_windows_failure_on_linux_host() {
        use tempfile::TempDir;

        let tmp = TempDir::new().unwrap();
        let ctx = tmp.path();
        // A minimal Dockerfile is enough — the fake backend ignores its
        // contents, but the Dockerfile parser needs *something* to read.
        tokio::fs::write(ctx.join("Dockerfile"), "FROM scratch\n")
            .await
            .unwrap();

        let yaml = r#"
images:
  linux-app:
    file: Dockerfile
    platforms: ["linux/amd64"]
    tags: ["example/linux:dev"]
  win-app:
    file: Dockerfile
    platforms: ["windows/amd64"]
    tags: ["example/windows:dev"]
"#;
        let pipeline = parse_pipeline(yaml).unwrap();

        // Pre-seed the cache with a fake Linux backend so the Linux build
        // does not try to invoke real buildah.
        let cache: Arc<Mutex<HashMap<ImageOs, Arc<dyn BuildBackend>>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let fake_linux: Arc<dyn BuildBackend> = Arc::new(FakeBackend { name: "fake-linux" });
        cache
            .lock()
            .await
            .insert(ImageOs::Linux, Arc::clone(&fake_linux));

        // Linux image should succeed via the seeded fake backend.
        let linux_res = build_one_image(
            "linux-app",
            &pipeline,
            ctx,
            BuildahExecutor::with_path("/usr/bin/buildah"),
            None, // no explicit override — exercise per-target_os routing
            &cache,
            None,
        )
        .await;
        assert!(
            linux_res.is_ok(),
            "Linux image should succeed, got: {linux_res:?}"
        );
        assert_eq!(linux_res.unwrap().image_id, "fake-linux:fake-id");

        // Windows image should fail with the L-6 message — a Windows image
        // cannot be built on a non-Windows host.
        let win_res = build_one_image(
            "win-app",
            &pipeline,
            ctx,
            BuildahExecutor::with_path("/usr/bin/buildah"),
            None,
            &cache,
            None,
        )
        .await;
        let err = win_res.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("Windows host") || msg.contains("windows host"),
            "expected Windows-host error from detect_backend, got: {msg}"
        );

        // The Windows detection failure must not pollute the cache for
        // ImageOs::Windows, and the Linux backend must remain cached.
        let guard = cache.lock().await;
        assert!(guard.contains_key(&ImageOs::Linux));
        assert!(!guard.contains_key(&ImageOs::Windows));
    }
}