cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
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
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
//! Sync function implementations.
//!
//! Supports generating:
//! - Project files from CUE codegen templates
//! - CI pipelines from CUE configuration
//!
//! Note: Ignore files and CODEOWNERS are now handled via .rules.cue files.
//! Use `cuenv sync rules` for those.

use super::super::{CommandExecutor, relative_path_from_root};
use cuenv_core::DryRun;
use cuenv_core::manifest::Project;
use cuenv_core::{ModuleEvaluation, Result};
use cuenv_github::GitHubConfigExt;
use similar::TextDiff;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use tracing::instrument;

/// Project information for CI sync operations.
///
/// This is a local struct that holds the data needed for workflow generation,
/// derived from `ModuleEvaluation` and `Instance`.
struct ProjectInfo {
    /// Absolute path to the project directory.
    project_path: PathBuf,
    /// Relative path from module root to project directory.
    relative_path: PathBuf,
    /// Module root path.
    module_root: PathBuf,
    /// Parsed project configuration.
    config: Project,
}

impl ProjectInfo {
    /// Collect all projects from a module evaluation.
    fn collect_from_module(module: &ModuleEvaluation) -> Result<Vec<Self>> {
        let mut projects = Vec::new();
        for instance in module.projects() {
            let config = Project::try_from(instance)?;
            // instance.path is the relative path to the project directory (not env.cue)
            let relative_path = instance.path.clone();
            let project_path = module.root.join(&relative_path);
            projects.push(Self {
                project_path,
                relative_path,
                module_root: module.root.clone(),
                config,
            });
        }
        Ok(projects)
    }
}

/// Options controlling codegen sync behavior.
#[derive(Clone, Copy, Debug)]
pub struct CodegenSyncOptions {
    /// Show what would be generated without writing files.
    pub dry_run: DryRun,
    /// Check if files are in sync without making changes.
    pub check: bool,
    /// Show diff for files that would change.
    pub diff: bool,
}

impl CodegenSyncOptions {
    fn should_check(self) -> bool {
        self.check || self.diff
    }
}

/// Request for syncing codegen for a single path.
#[derive(Debug)]
pub struct CodegenSyncRequest<'a> {
    /// Path to the CUE module or project directory.
    pub path: &'a str,
    /// CUE package name to evaluate.
    pub package: &'a str,
    /// Sync options.
    pub options: CodegenSyncOptions,
}

struct CodegenSyncContext<'a> {
    dir_path: &'a Path,
    options: CodegenSyncOptions,
    executor: &'a CommandExecutor,
}

struct CodegenSyncFilesRequest<'a> {
    project_root: &'a Path,
    project_name: &'a str,
    codegen_config: &'a cuenv_core::manifest::CodegenConfig,
    options: CodegenSyncOptions,
}

struct CodegenFileSyncRequest<'a> {
    output_lines: &'a mut Vec<String>,
    output_path: &'a Path,
    file_path: &'a str,
    content: &'a str,
}

struct CodegenWriteRequest<'a> {
    output_path: &'a Path,
    file_path: &'a str,
    content: &'a str,
    mode: &'a str,
}

/// Options controlling CI sync behavior.
#[derive(Clone, Copy, Debug)]
pub struct CiSyncOptions<'a> {
    /// Show what would be generated without writing files.
    pub dry_run: DryRun,
    /// Check if files are in sync without making changes.
    pub check: bool,
    /// Optional provider override.
    pub provider: Option<&'a str>,
}

/// Request for syncing CI for a single path.
#[derive(Debug)]
pub struct CiSyncRequest<'a> {
    /// Path to the CUE module or project directory.
    pub path: &'a str,
    /// CUE package name to evaluate.
    pub package: &'a str,
    /// Sync options.
    pub options: CiSyncOptions<'a>,
}

/// Request for syncing CI across the workspace.
#[derive(Debug)]
pub struct CiWorkspaceSyncRequest<'a> {
    /// CUE package name to evaluate.
    pub package: &'a str,
    /// Sync options.
    pub options: CiSyncOptions<'a>,
}

struct GithubSyncRequest<'a> {
    repo_root: &'a Path,
    options: CiSyncOptions<'a>,
    projects: &'a [ProjectInfo],
}

struct BuildkiteSyncRequest<'a> {
    repo_root: &'a Path,
    options: CiSyncOptions<'a>,
}

/// Load Project configuration from CUE using module-wide evaluation.
fn load_project_config(path: &Path, executor: &CommandExecutor) -> Result<Project> {
    let (instance, _module_root) = load_instance_at_path(path, executor)?;
    instance.deserialize()
}

/// Load a CUE instance at the given path using module-wide evaluation.
/// Returns the instance and the module root path.
///
/// Uses the executor's cached module evaluation.
fn load_instance_at_path(
    path: &Path,
    executor: &CommandExecutor,
) -> Result<(cuenv_core::module::Instance, PathBuf)> {
    let target_path = path.canonicalize().map_err(|e| cuenv_core::Error::Io {
        source: e,
        path: Some(path.to_path_buf().into_boxed_path()),
        operation: "canonicalize path".to_string(),
    })?;

    tracing::debug!("Using cached module evaluation from executor");
    let module = executor.get_module(&target_path)?;
    let relative_path = relative_path_from_root(&module.root, &target_path);

    let instance = module.get(&relative_path).ok_or_else(|| {
        cuenv_core::Error::configuration(format!(
            "No CUE instance found at path: {} (relative: {})",
            target_path.display(),
            relative_path.display()
        ))
    })?;

    Ok((instance.clone(), module.root.clone()))
}

/// Execute the sync codegen command for a single project.
///
/// Syncs codegen-generated files for the project at the specified path.
/// Use `execute_sync_codegen_workspace` for workspace-wide syncing.
///
/// Uses the executor's cached module evaluation.
///
/// # Errors
///
/// Returns an error if CUE evaluation fails or file operations fail.
#[instrument(name = "sync_codegen", skip(executor))]
pub async fn execute_sync_codegen(
    request: CodegenSyncRequest<'_>,
    executor: &CommandExecutor,
) -> Result<String> {
    tracing::info!("Starting sync codegen command");

    let dir_path = Path::new(request.path);
    let context = CodegenSyncContext {
        dir_path,
        options: request.options,
        executor,
    };
    execute_sync_codegen_local(&context)
}

/// Sync codegen for the local project only
fn execute_sync_codegen_local(context: &CodegenSyncContext<'_>) -> Result<String> {
    let dir_path = context.dir_path;
    let options = context.options;
    let executor = context.executor;
    let manifest: Project = load_project_config(dir_path, executor)?;

    let Some(codegen_config) = &manifest.codegen else {
        return Ok("No codegen configuration found in this project.".to_string());
    };

    let sync_request = CodegenSyncFilesRequest {
        project_root: dir_path,
        project_name: &manifest.name,
        codegen_config,
        options,
    };
    let sync_result = sync_codegen_files(&sync_request)?;

    // Run formatters only on files that were actually written
    let format_result = if let Some(ref formatters) = manifest.formatters {
        if sync_result.written_files.is_empty() && !options.dry_run.is_dry_run() {
            // No files were written, skip formatting
            String::new()
        } else if options.dry_run.is_dry_run() {
            // In dry-run mode, show what would be formatted based on all configured files
            let file_paths: Vec<std::path::PathBuf> = codegen_config
                .files
                .keys()
                .map(|p| dir_path.join(p))
                .collect();
            let file_refs: Vec<&Path> = file_paths.iter().map(|p| p.as_path()).collect();
            super::formatters::format_generated_files(
                &file_refs,
                formatters,
                dir_path,
                options.dry_run,
                options.check,
            )?
        } else {
            // Format only the files that were actually written
            let file_refs: Vec<&Path> = sync_result
                .written_files
                .iter()
                .map(|p| p.as_path())
                .collect();
            super::formatters::format_generated_files(
                &file_refs,
                formatters,
                dir_path,
                options.dry_run,
                options.check,
            )?
        }
    } else {
        String::new()
    };

    // Combine results
    if format_result.is_empty() {
        Ok(sync_result.output)
    } else {
        Ok(format!("{}\n\n{format_result}", sync_result.output))
    }
}

/// Result of a codegen sync operation
struct SyncResult {
    /// Human-readable output
    output: String,
    /// Files that were actually written to disk
    written_files: Vec<PathBuf>,
}

/// Sync codegen files for a single project
fn sync_codegen_files(request: &CodegenSyncFilesRequest<'_>) -> Result<SyncResult> {
    use cuenv_core::manifest::FileMode;

    let project_root = request.project_root;
    let project_name = request.project_name;
    let codegen_config = request.codegen_config;
    let options = request.options;

    let mut output_lines = Vec::new();
    let mut written_files = Vec::new();

    for (file_path, file_def) in &codegen_config.files {
        let output_path = project_root.join(file_path);
        let mut file_request = CodegenFileSyncRequest {
            output_lines: &mut output_lines,
            output_path: &output_path,
            file_path,
            content: &file_def.content,
        };

        match file_def.mode {
            FileMode::Managed => {
                let was_written = sync_managed_file(&mut file_request, options)?;
                if was_written {
                    written_files.push(output_path);
                }
            }
            FileMode::Scaffold => {
                let was_written = sync_scaffold_file(&mut file_request, options)?;
                if was_written {
                    written_files.push(output_path);
                }
            }
        }
    }

    tracing::info!(
        project = project_name,
        files = codegen_config.files.len(),
        written = written_files.len(),
        "Codegen sync complete"
    );

    Ok(SyncResult {
        output: output_lines.join("\n"),
        written_files,
    })
}

/// Sync a managed codegen file (always overwritten to match expected content)
///
/// Returns `true` if the file was actually written to disk.
fn sync_managed_file(
    request: &mut CodegenFileSyncRequest<'_>,
    options: CodegenSyncOptions,
) -> Result<bool> {
    if options.should_check() {
        if request.output_path.exists() {
            let contents = std::fs::read_to_string(request.output_path).unwrap_or_default();
            if contents == request.content {
                request
                    .output_lines
                    .push(format!("  OK: {}", request.file_path));
            } else {
                request
                    .output_lines
                    .push(format!("  Out of sync: {}", request.file_path));
                maybe_push_diff(request, Some(&contents), options);
            }
        } else {
            request
                .output_lines
                .push(format!("  Missing: {}", request.file_path));
            maybe_push_diff(request, None, options);
        }
        Ok(false)
    } else if options.dry_run.is_dry_run() {
        if request.output_path.exists() {
            request
                .output_lines
                .push(format!("  Would update: {}", request.file_path));
        } else {
            request
                .output_lines
                .push(format!("  Would create: {}", request.file_path));
        }
        Ok(false)
    } else {
        let write_request = CodegenWriteRequest {
            output_path: request.output_path,
            file_path: request.file_path,
            content: request.content,
            mode: "managed",
        };
        write_codegen_file(&write_request)?;
        request
            .output_lines
            .push(format!("  Generated: {}", request.file_path));
        Ok(true)
    }
}

/// Sync a scaffold codegen file (only created if it doesn't exist)
///
/// Returns `true` if the file was actually written to disk.
fn sync_scaffold_file(
    request: &mut CodegenFileSyncRequest<'_>,
    options: CodegenSyncOptions,
) -> Result<bool> {
    if request.output_path.exists() {
        if !options.dry_run.is_dry_run() && !options.should_check() {
            tracing::debug!(
                "Skipping {} (scaffold mode, file exists)",
                request.file_path
            );
        }
        request
            .output_lines
            .push(format!("  Skipped (exists): {}", request.file_path));
        Ok(false)
    } else if options.should_check() {
        request
            .output_lines
            .push(format!("  Missing scaffold: {}", request.file_path));
        maybe_push_diff(request, None, options);
        Ok(false)
    } else if options.dry_run.is_dry_run() {
        request
            .output_lines
            .push(format!("  Would scaffold: {}", request.file_path));
        Ok(false)
    } else {
        let write_request = CodegenWriteRequest {
            output_path: request.output_path,
            file_path: request.file_path,
            content: request.content,
            mode: "scaffold",
        };
        write_codegen_file(&write_request)?;
        request
            .output_lines
            .push(format!("  Scaffolded: {}", request.file_path));
        Ok(true)
    }
}

/// Write a codegen file to disk, creating parent directories as needed
fn write_codegen_file(request: &CodegenWriteRequest<'_>) -> Result<()> {
    let CodegenWriteRequest {
        output_path,
        file_path,
        content,
        mode,
    } = *request;
    tracing::debug!(
        file_path = %file_path,
        output_path = %output_path.display(),
        content_len = content.len(),
        "Writing {mode} codegen file"
    );
    if let Some(parent) = output_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            tracing::error!(
                parent = %parent.display(),
                error = %e,
                "Failed to create parent directory"
            );
            cuenv_core::Error::Io {
                source: e,
                path: Some(parent.to_path_buf().into_boxed_path()),
                operation: format!("create parent directory for {mode} file: {file_path}"),
            }
        })?;
    }
    std::fs::write(output_path, content).map_err(|e| {
        tracing::error!(
            output_path = %output_path.display(),
            error = %e,
            "Failed to write {mode} file"
        );
        cuenv_core::Error::Io {
            source: e,
            path: Some(output_path.to_path_buf().into_boxed_path()),
            operation: format!("write {mode} file: {file_path}"),
        }
    })?;
    Ok(())
}

fn maybe_push_diff(
    request: &mut CodegenFileSyncRequest<'_>,
    existing: Option<&str>,
    options: CodegenSyncOptions,
) {
    if !options.diff {
        return;
    }
    let current = existing.unwrap_or("");
    if current == request.content {
        return;
    }
    request.output_lines.push(format_unified_diff(
        request.file_path,
        current,
        request.content,
    ));
}

fn format_unified_diff(path: &str, current: &str, expected: &str) -> String {
    let diff = TextDiff::from_lines(current, expected);
    let from = format!("a/{path}");
    let to = format!("b/{path}");
    diff.unified_diff().header(&from, &to).to_string()
}
// ============================================================================
// CI Workflow Sync
// ============================================================================

/// Known CI providers supported by cuenv sync.
const KNOWN_PROVIDERS: &[&str] = &["github", "buildkite", "gitlab"];

/// Validate provider names against known providers.
///
/// Returns a tuple of (valid_providers, warnings).
/// Unknown providers generate warnings but don't prevent sync from proceeding
/// with the valid ones.
fn validate_providers(providers: &[String]) -> (Vec<String>, Vec<String>) {
    let mut valid = Vec::new();
    let mut warnings = Vec::new();

    for p in providers {
        if KNOWN_PROVIDERS.contains(&p.as_str()) {
            valid.push(p.clone());
        } else {
            warnings.push(format!(
                "Unknown CI provider '{}'. Known providers: {}",
                p,
                KNOWN_PROVIDERS.join(", ")
            ));
        }
    }

    (valid, warnings)
}

/// Execute the sync ci command for a single project.
///
/// Syncs CI workflow files (GitHub Actions, Buildkite) based on CUE configuration.
///
/// # Errors
///
/// Returns an error if project discovery fails or workflow generation fails.
#[instrument(name = "sync_ci", skip_all)]
pub async fn execute_sync_ci(
    request: CiSyncRequest<'_>,
    executor: &CommandExecutor,
) -> Result<String> {
    tracing::info!("Starting sync ci command");

    let dir_path = Path::new(request.path);

    // Get cached module from executor and discover projects before async work
    // (ModuleGuard contains MutexGuard which is not Send)
    let (projects, repo_root, target_path) = {
        let target_path = dir_path.canonicalize().map_err(|e| cuenv_core::Error::Io {
            source: e,
            path: Some(dir_path.to_path_buf().into_boxed_path()),
            operation: "canonicalize path".to_string(),
        })?;
        let module = executor.get_module(&target_path)?;
        let projects = ProjectInfo::collect_from_module(&module)?;
        (projects, module.root.clone(), target_path)
    };

    let target_projects: Vec<_> = projects
        .into_iter()
        .filter(|project| {
            // project_path is absolute path to project directory
            project
                .project_path
                .canonicalize()
                .ok()
                .is_some_and(|path| path == target_path)
        })
        .collect();

    if target_projects.is_empty() {
        // Fallback: when invoked at the module root and no specific project
        // matches, do not error out. In CI we often run `cuenv sync ci` from
        // the repo root just to ensure workflows are in sync; returning a
        // benign message avoids a hard failure.
        if repo_root == target_path {
            return Ok("No CI configuration found.".to_string());
        }
        return Err(cuenv_core::Error::configuration(format!(
            "No cuenv project found at path: {}. Run 'cuenv info' to inspect project layout or use 'cuenv sync -A' to sync all projects.",
            dir_path.display()
        )));
    }

    // Determine which providers to sync (CLI flag takes precedence)
    let providers: Vec<String> = if let Some(p) = request.options.provider {
        vec![p.to_string()]
    } else {
        // Use configured providers from CUE
        let ci_config = target_projects.first().and_then(|p| p.config.ci.as_ref());

        match ci_config {
            Some(ci) if !ci.providers.is_empty() => ci.providers.clone(),
            _ => {
                // No providers configured = emit nothing (explicit configuration required)
                return Ok(
                    "No CI providers configured. Add 'providers: [\"github\"]' to your ci config."
                        .to_string(),
                );
            }
        }
    };

    // Validate providers
    let (valid_providers, warnings) = validate_providers(&providers);
    for warning in &warnings {
        tracing::warn!("{}", warning);
    }

    if valid_providers.is_empty() {
        return Err(cuenv_core::Error::configuration(format!(
            "No valid CI providers specified. Known providers: {}",
            KNOWN_PROVIDERS.join(", ")
        )));
    }

    let mut outputs = Vec::new();
    let mut errors: Vec<(String, cuenv_core::Error)> = Vec::new();

    for prov in &valid_providers {
        let result = match prov.as_str() {
            "github" => {
                let github_request = GithubSyncRequest {
                    repo_root: &repo_root,
                    options: request.options,
                    projects: &target_projects,
                };
                execute_sync_github(github_request).await
            }
            "buildkite" => {
                let buildkite_request = BuildkiteSyncRequest {
                    repo_root: &repo_root,
                    options: request.options,
                };
                execute_sync_buildkite(&buildkite_request)
            }
            "gitlab" => {
                tracing::debug!("GitLab CI sync not yet implemented");
                continue;
            }
            _ => Err(cuenv_core::Error::configuration(format!(
                "Unsupported CI provider: {prov}. Supported: {}",
                KNOWN_PROVIDERS.join(", ")
            ))),
        };

        match result {
            Ok(output) if !output.is_empty() => outputs.push(output),
            Ok(_) => {} // Skip empty output (no config for this provider)
            Err(e) => {
                if request.options.provider.is_some() {
                    return Err(e);
                }
                tracing::debug!("Skipping {prov}: {e}");
                errors.push((prov.clone(), e));
            }
        }
    }

    if outputs.is_empty() {
        if errors.is_empty() {
            Ok("No CI configuration found.".to_string())
        } else {
            // CI config exists but all providers had errors
            let error_summary: Vec<String> = errors
                .iter()
                .map(|(prov, e)| format!("{prov}: {e}"))
                .collect();
            Ok(format!(
                "CI sync failed for all providers:\n{}",
                error_summary.join("\n")
            ))
        }
    } else {
        Ok(outputs.join("\n"))
    }
}

/// Execute workspace-wide CI sync.
///
/// Syncs CI workflow files for all projects with CI configuration.
///
/// # Errors
///
/// Returns an error if module evaluation or workflow generation fails.
#[instrument(name = "sync_ci_workspace", skip_all)]
pub async fn execute_sync_ci_workspace(
    request: CiWorkspaceSyncRequest<'_>,
    executor: &CommandExecutor,
) -> Result<String> {
    // Get cached module from executor and discover projects before async work
    // (ModuleGuard contains MutexGuard which is not Send, must be dropped before await)
    let projects = {
        let cwd = std::env::current_dir().map_err(|e| {
            cuenv_core::Error::configuration(format!("Failed to get current directory: {e}"))
        })?;
        let module = executor.discover_all_modules(&cwd)?;
        ProjectInfo::collect_from_module(&module)?
    };

    if projects.is_empty() {
        return Ok("No projects with CI configuration found.".to_string());
    }

    let mut outputs = Vec::new();

    for project in &projects {
        // Use absolute path - relative_path is relative to module root, not CWD
        let project_path_str = project.project_path.to_string_lossy();

        let ci_request = CiSyncRequest {
            path: &project_path_str,
            package: request.package,
            options: request.options,
        };
        let result = execute_sync_ci(ci_request, executor).await;

        match result {
            Ok(output) if !output.is_empty() => {
                outputs.push(format!("[{}]\n{}", project.config.name, output));
            }
            Ok(_) => {}
            Err(e) => {
                outputs.push(format!("[{}] Error: {}", project.config.name, e));
            }
        }
    }

    if outputs.is_empty() {
        Ok("No CI workflows to sync.".to_string())
    } else {
        Ok(outputs.join("\n\n"))
    }
}

/// Sync GitHub Actions workflow files from CUE configuration.
#[allow(clippy::too_many_lines)]
#[instrument(name = "sync_github", skip_all)]
async fn execute_sync_github(request: GithubSyncRequest<'_>) -> Result<String> {
    let GithubSyncRequest {
        repo_root,
        options,
        projects,
    } = request;
    if projects.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "No cuenv projects found. Ensure env.cue files declare 'package cuenv'",
        ));
    }

    // Generate workflows per-project, per-pipeline
    // Each project with CI config gets its own workflow files
    let mut all_workflows: Vec<(String, String)> = Vec::new();
    for project in projects {
        let Some(ci) = &project.config.ci else {
            continue;
        };
        for (pipeline_name, pipeline) in &ci.pipelines {
            let workflows = generate_github_workflow_for_project(project, pipeline_name, pipeline)?;
            all_workflows.extend(workflows);
        }
    }

    if all_workflows.is_empty() {
        return Ok(String::new());
    }

    let workflows_dir = repo_root.join(".github/workflows");
    let mut output_lines = Vec::new();

    // Check mode: compare generated content with existing files
    if options.check {
        let mut out_of_sync = Vec::new();
        for (filename, content) in &all_workflows {
            let path = workflows_dir.join(filename);
            if path.exists() {
                let existing =
                    std::fs::read_to_string(&path).map_err(|e| cuenv_core::Error::Io {
                        source: e,
                        path: Some(path.clone().into_boxed_path()),
                        operation: "read workflow file".to_string(),
                    })?;
                if existing != *content {
                    out_of_sync.push(filename.clone());
                }
            } else {
                out_of_sync.push(format!("{filename} (missing)"));
            }
        }
        if !out_of_sync.is_empty() {
            return Err(cuenv_core::Error::configuration(format!(
                "GitHub workflows out of sync: {}. Run 'cuenv sync ci' to update.",
                out_of_sync.join(", ")
            )));
        }
        return Ok(format!(
            "GitHub: {} workflow(s) in sync",
            all_workflows.len()
        ));
    }

    // Dry-run or normal mode
    for (filename, content) in &all_workflows {
        let workflow_path = workflows_dir.join(filename);
        let exists = workflow_path.exists();

        // Check if content matches (skip if unchanged)
        if exists && !options.dry_run.is_dry_run() {
            let existing = std::fs::read_to_string(&workflow_path).unwrap_or_default();
            if existing == *content {
                output_lines.push(format!("GitHub: {filename} (unchanged)"));
                continue;
            }
        }

        if options.dry_run.is_dry_run() {
            if exists {
                output_lines.push(format!("GitHub: Would update {filename}"));
            } else {
                output_lines.push(format!("GitHub: Would create {filename}"));
            }
        } else {
            // Create directory if needed
            if !workflows_dir.exists() {
                std::fs::create_dir_all(&workflows_dir).map_err(|e| cuenv_core::Error::Io {
                    source: e,
                    path: Some(workflows_dir.clone().into_boxed_path()),
                    operation: "create directory".to_string(),
                })?;
            }

            std::fs::write(&workflow_path, content).map_err(|e| cuenv_core::Error::Io {
                source: e,
                path: Some(workflow_path.clone().into_boxed_path()),
                operation: "write workflow file".to_string(),
            })?;

            if exists {
                output_lines.push(format!("GitHub: Updated {filename}"));
            } else {
                output_lines.push(format!("GitHub: Created {filename}"));
            }
        }
    }

    Ok(output_lines.join("\n"))
}

/// Collected pipeline context from project discovery.
struct PipelineContext {
    is_release: bool,
    /// Pipeline generation mode (thin vs expanded)
    mode: cuenv_core::ci::PipelineMode,
    github_config: cuenv_github::config::GitHubConfig,
    trigger: cuenv_ci::ir::TriggerCondition,
    project_name: Option<String>,
    /// Relative path to project directory (for working-directory in monorepos)
    project_path: Option<String>,
    environment: Option<String>,
    runtimes: Vec<cuenv_ci::ir::Runtime>,
    /// All tasks including phase tasks (phase tasks have phase field set)
    tasks: Vec<cuenv_ci::ir::Task>,
    /// Original pipeline tasks (with matrix/artifacts/params info)
    pipeline_tasks: Vec<cuenv_core::ci::PipelineTask>,
}

impl PipelineContext {
    /// Build an IntermediateRepresentation from this context.
    fn to_ir(&self, pipeline_name: &str) -> cuenv_ci::ir::IntermediateRepresentation {
        cuenv_ci::ir::IntermediateRepresentation {
            version: "1.5".to_string(),
            pipeline: cuenv_ci::ir::PipelineMetadata {
                name: pipeline_name.to_string(),
                mode: self.mode,
                environment: self.environment.clone(),
                requires_onepassword: false,
                project_name: self.project_name.clone(),
                project_path: self.project_path.clone(),
                trigger: Some(self.trigger.clone()),
                pipeline_tasks: self
                    .pipeline_tasks
                    .iter()
                    .map(|t| t.task_name().to_string())
                    .collect(),
                pipeline_task_defs: self.pipeline_tasks.clone(),
            },
            runtimes: self.runtimes.clone(),
            tasks: self.tasks.clone(),
        }
    }

    /// Get regular (non-phase) tasks from this context.
    fn regular_tasks(&self) -> Vec<&cuenv_ci::ir::Task> {
        self.tasks.iter().filter(|t| t.phase.is_none()).collect()
    }
}

/// Check if any pipeline tasks have matrix configurations that require expansion.
///
/// Returns true only for tasks with actual matrix dimensions (non-empty matrix map).
/// Aggregation tasks (empty matrix with artifacts) return false.
fn has_matrix_tasks(pipeline_tasks: &[cuenv_core::ci::PipelineTask]) -> bool {
    pipeline_tasks
        .iter()
        .any(cuenv_core::ci::PipelineTask::has_matrix_dimensions)
}

/// Generate GitHub workflow files for a single project and pipeline.
fn generate_github_workflow_for_project(
    project: &ProjectInfo,
    pipeline_name: &str,
    pipeline: &cuenv_core::ci::Pipeline,
) -> Result<Vec<(String, String)>> {
    use cuenv_core::ci::PipelineMode;

    let ctx = build_project_pipeline_context(project, pipeline_name, pipeline)?;

    // Dispatch based on pipeline mode
    // Note: Matrix tasks ALWAYS require multi-job workflow regardless of mode,
    // since they need to run on different runners for each matrix dimension.
    match ctx.mode {
        PipelineMode::Thin => {
            // Thin mode with matrix tasks still needs multi-job workflow
            if has_matrix_tasks(&ctx.pipeline_tasks) {
                emit_matrix_workflow(pipeline_name, &ctx)
            } else {
                // Pure thin mode: single job with cuenv ci orchestration
                emit_thin_workflow(pipeline_name, &ctx)
            }
        }
        PipelineMode::Expanded => {
            // Expanded mode: all tasks as individual jobs with dependencies
            if has_matrix_tasks(&ctx.pipeline_tasks) {
                emit_matrix_workflow(pipeline_name, &ctx)
            } else if ctx.is_release {
                emit_release_workflow(pipeline_name, &ctx)
            } else if ctx.tasks.is_empty() {
                Ok(Vec::new())
            } else {
                emit_standard_workflow(pipeline_name, &ctx)
            }
        }
    }
}

/// Build pipeline context for a single project and pipeline.
fn build_project_pipeline_context(
    project: &ProjectInfo,
    pipeline_name: &str,
    pipeline: &cuenv_core::ci::Pipeline,
) -> Result<PipelineContext> {
    use cuenv_ci::compiler::{Compiler, CompilerOptions};

    let ci = project
        .config
        .ci
        .as_ref()
        .ok_or_else(|| cuenv_core::Error::configuration("Project has no CI configuration"))?;

    // Detect release pipelines by checking if they have release event triggers
    let is_release = pipeline.when.as_ref().is_some_and(|w| w.release.is_some());

    // Compute project_path for compiler (None if root, i.e., empty relative_path)
    let project_path_for_compiler = if project.relative_path.as_os_str().is_empty() {
        None
    } else {
        Some(project.relative_path.to_string_lossy().to_string())
    };

    let options = CompilerOptions {
        pipeline_name: Some(pipeline_name.to_string()),
        pipeline: Some(pipeline.clone()),
        ci_mode: true,
        module_root: Some(project.module_root.clone()),
        project_path: project_path_for_compiler.clone(),
        ..Default::default()
    };
    let compiler = Compiler::with_options(project.config.clone(), options);
    let ir = compiler
        .compile()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to compile project: {e}")))?;

    // Extract task names from pipeline tasks (which can be simple strings or matrix tasks)
    let pipeline_task_names: Vec<String> = pipeline
        .tasks
        .iter()
        .map(|t| t.task_name().to_string())
        .collect();

    // Get pipeline tasks (non-phase tasks)
    let filtered_tasks = cuenv_ci::pipeline::filter_tasks(&pipeline_task_names, ir.tasks.clone());

    // Combine phase tasks (bootstrap, setup, success, failure) with pipeline tasks
    let phase_tasks: Vec<cuenv_ci::ir::Task> =
        ir.tasks.into_iter().filter(|t| t.phase.is_some()).collect();
    let mut all_tasks = phase_tasks;
    all_tasks.extend(filtered_tasks);

    // Use the compiler-derived trigger which includes paths from task inputs
    let trigger = ir
        .pipeline
        .trigger
        .unwrap_or_else(|| build_github_trigger_condition(pipeline_name, pipeline, ci));

    Ok(PipelineContext {
        is_release,
        mode: pipeline.mode,
        github_config: ci.github_config_for_pipeline(pipeline_name),
        trigger,
        project_name: Some(project.config.name.clone()),
        project_path: project_path_for_compiler,
        environment: pipeline.environment.clone(),
        runtimes: ir.runtimes,
        tasks: all_tasks,
        pipeline_tasks: pipeline.tasks.clone(),
    })
}

/// Emit a release workflow using the `ReleaseWorkflowBuilder`.
fn emit_release_workflow(
    pipeline_name: &str,
    ctx: &PipelineContext,
) -> Result<Vec<(String, String)>> {
    use cuenv_github::workflow::{GitHubActionsEmitter, ReleaseWorkflowBuilder};

    let ir = ctx.to_ir(pipeline_name);

    let emitter = GitHubActionsEmitter::from_config(&ctx.github_config).with_nix();
    let workflow = ReleaseWorkflowBuilder::new(emitter).build(&ir);

    let workflow_name = match &ir.pipeline.project_name {
        Some(project) => format!("{project}-{}", ir.pipeline.name),
        None => ir.pipeline.name.clone(),
    };
    let filename = format!("{}.yml", sanitize_workflow_name(&workflow_name));

    let yaml = workflow.to_yaml().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to serialize workflow: {e}"))
    })?;

    Ok(vec![(filename, yaml)])
}

/// Emit a thin mode workflow by delegating to the GitHub Actions emitter.
fn emit_thin_workflow(pipeline_name: &str, ctx: &PipelineContext) -> Result<Vec<(String, String)>> {
    use cuenv_github::workflow::GitHubActionsEmitter;

    let ir = ctx.to_ir(pipeline_name);
    let emitter = GitHubActionsEmitter::from_config(&ctx.github_config).with_nix();

    let (filename, yaml) = emitter.emit_thin_workflow(&ir).map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to emit thin workflow: {e}"))
    })?;

    Ok(vec![(filename, yaml)])
}

fn runner_key(runs_on: &cuenv_github::workflow::schema::RunsOn) -> String {
    match runs_on {
        cuenv_github::workflow::schema::RunsOn::Label(label) => format!("label:{label}"),
        cuenv_github::workflow::schema::RunsOn::Labels(labels) => {
            format!("labels:{}", labels.join("|"))
        }
    }
}

fn runner_suffix(runs_on: &cuenv_github::workflow::schema::RunsOn) -> String {
    let raw = match runs_on {
        cuenv_github::workflow::schema::RunsOn::Label(label) => label.clone(),
        cuenv_github::workflow::schema::RunsOn::Labels(labels) => labels.join("-"),
    };

    raw.to_lowercase()
        .replace(['.', ' '], "-")
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect()
}

fn prepend_need(job: &mut cuenv_github::workflow::schema::Job, dependency: &str) {
    if job.needs.iter().any(|need| need == dependency) {
        return;
    }

    let mut needs = Vec::with_capacity(job.needs.len() + 1);
    needs.push(dependency.to_string());
    needs.extend(job.needs.clone());
    job.needs = needs;
}

fn inject_cuenv_bootstrap_jobs(
    jobs: &mut indexmap::IndexMap<String, cuenv_github::workflow::schema::Job>,
    ir: &cuenv_ci::ir::IntermediateRepresentation,
    emitter: &cuenv_github::workflow::GitHubActionsEmitter,
) {
    use cuenv_github::workflow::schema::RunsOn;
    use indexmap::IndexMap;

    if jobs.is_empty() {
        return;
    }

    let mut runners = IndexMap::<String, RunsOn>::new();
    for job in jobs.values() {
        runners
            .entry(runner_key(&job.runs_on))
            .or_insert_with(|| job.runs_on.clone());
    }

    let multiple_runners = runners.len() > 1;
    let mut runner_bootstrap_jobs = IndexMap::<String, String>::new();
    let mut bootstrap_jobs = IndexMap::<String, cuenv_github::workflow::schema::Job>::new();

    for (key, runs_on) in runners {
        let (bootstrap_job_id, display_name) = if multiple_runners {
            let suffix = runner_suffix(&runs_on);
            (
                format!("build-cuenv-{suffix}"),
                format!("build.cuenv ({suffix})"),
            )
        } else {
            ("build-cuenv".to_string(), "build.cuenv".to_string())
        };

        let Some(job) = emitter.build_cuenv_bootstrap_job(ir, runs_on, &display_name) else {
            return;
        };

        runner_bootstrap_jobs.insert(key, bootstrap_job_id.clone());
        bootstrap_jobs.insert(bootstrap_job_id, job);
    }

    for job in jobs.values_mut() {
        if let Some(bootstrap_job_id) = runner_bootstrap_jobs.get(&runner_key(&job.runs_on)) {
            prepend_need(job, bootstrap_job_id);
        }
    }

    let existing_jobs = std::mem::take(jobs);
    jobs.extend(bootstrap_jobs);
    jobs.extend(existing_jobs);
}

/// Emit a standard workflow using the `GitHubActionsEmitter`.
///
/// Builds jobs directly using `build_simple_job` which supports `project_path`
/// for setting working-directory in monorepo workflows.
fn simple_job_options<'a>(
    ctx: &'a PipelineContext,
    task: &cuenv_ci::ir::Task,
) -> cuenv_github::workflow::SimpleJobOptions<'a> {
    let is_direct_nix_job =
        !ctx.is_release && task.command.first().is_some_and(|command| command == "nix");

    if is_direct_nix_job {
        cuenv_github::workflow::SimpleJobOptions::direct(ctx.project_path.as_deref())
    } else {
        cuenv_github::workflow::SimpleJobOptions::orchestrated(
            ctx.environment.as_ref(),
            ctx.project_path.as_deref(),
        )
    }
}

fn emit_standard_workflow(
    pipeline_name: &str,
    ctx: &PipelineContext,
) -> Result<Vec<(String, String)>> {
    use cuenv_github::workflow::GitHubActionsEmitter;
    use cuenv_github::workflow::schema::{Concurrency, Workflow};
    use indexmap::IndexMap;

    let workflow_name = match &ctx.project_name {
        Some(project) => format!("{project}-{pipeline_name}"),
        None => pipeline_name.to_string(),
    };

    let ir = ctx.to_ir(pipeline_name);
    let emitter = GitHubActionsEmitter::from_config(&ctx.github_config).with_nix();

    // Build jobs using build_simple_job (which supports project_path for working-directory)
    // Only iterate over regular tasks (non-phase tasks) - phase tasks are handled internally
    let mut jobs = IndexMap::new();
    for task in ctx.regular_tasks() {
        let mut job = emitter.build_simple_job(task, &ir, simple_job_options(ctx, task));
        job.needs = task
            .depends_on
            .iter()
            .map(|d| d.replace(['.', ' '], "-"))
            .collect();
        jobs.insert(task.id.replace(['.', ' '], "-"), job);
    }

    inject_cuenv_bootstrap_jobs(&mut jobs, &ir, &emitter);

    let filename = format!("{}.yml", sanitize_workflow_name(&workflow_name));

    let workflow = Workflow {
        name: workflow_name.clone(),
        on: emitter.build_triggers(&ir, &filename),
        concurrency: Some(Concurrency {
            group: "${{ github.workflow }}-${{ github.head_ref || github.ref }}".to_string(),
            cancel_in_progress: Some(true),
        }),
        permissions: Some(emitter.build_permissions(&ir)),
        env: IndexMap::new(),
        jobs,
    };
    let yaml = workflow.to_yaml().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to serialize workflow: {e}"))
    })?;

    Ok(vec![(filename, yaml)])
}

/// Build jobs from expanded pipeline tasks, tracking artifact sources.
///
/// Uses `GitHubActionsEmitter` methods to build jobs, converting `PipelineTask`
/// info to IR `Task` fields as needed.
fn build_pipeline_jobs(
    expanded_tasks: &[cuenv_core::ci::PipelineTask],
    ctx: &PipelineContext,
    ir: &cuenv_ci::ir::IntermediateRepresentation,
    emitter: &cuenv_github::workflow::GitHubActionsEmitter,
) -> indexmap::IndexMap<String, cuenv_github::workflow::schema::Job> {
    use indexmap::IndexMap;

    let mut jobs = IndexMap::new();
    let mut artifact_source_jobs: HashSet<String> = HashSet::new();
    let mut processed_task_names: HashSet<String> = HashSet::new();

    for pipeline_task in expanded_tasks {
        let task_name = pipeline_task.task_name();
        processed_task_names.insert(task_name.to_string());
        let job_id = task_name.replace(['.', ' '], "-");

        match pipeline_task {
            cuenv_core::ci::PipelineTask::Simple(_) | cuenv_core::ci::PipelineTask::Node(_) => {
                if let Some(ir_task) = ctx.tasks.iter().find(|t| t.id == task_name) {
                    // Use emitter method directly
                    let mut job =
                        emitter.build_simple_job(ir_task, ir, simple_job_options(ctx, ir_task));
                    job.needs = ir_task
                        .depends_on
                        .iter()
                        .map(|dep| dep.replace(['.', ' '], "-"))
                        .collect();
                    jobs.insert(job_id, job);
                }
            }
            cuenv_core::ci::PipelineTask::Matrix(matrix_task) => {
                if matrix_task.matrix.is_empty() {
                    // Artifact aggregation task: create a synthetic IR Task with artifact_downloads
                    let ir_task = ctx.tasks.iter().find(|t| t.id == task_name);
                    let mut seen: HashSet<String> = artifact_source_jobs.clone();
                    let mut combined_needs: Vec<String> =
                        artifact_source_jobs.iter().cloned().collect();

                    if let Some(ir_task) = ir_task {
                        for dep in &ir_task.depends_on {
                            let dep_job_id = dep.replace(['.', ' '], "-");
                            if seen.insert(dep_job_id.clone()) {
                                combined_needs.push(dep_job_id);
                            }
                        }
                    }
                    // Sort for deterministic output
                    combined_needs.sort();

                    // Create synthetic IR Task with artifact_downloads and params
                    let synthetic_task = create_synthetic_aggregation_task(task_name, matrix_task);
                    let job = emitter.build_artifact_aggregation_job(
                        &synthetic_task,
                        ir,
                        ctx.environment.as_ref(),
                        &combined_needs,
                        ctx.project_path.as_deref(),
                    );
                    jobs.insert(job_id, job);
                } else {
                    // Matrix expansion task: create a synthetic IR Task with matrix config
                    // Look up the actual task to get its outputs for artifact upload paths
                    let ir_task = ctx.tasks.iter().find(|t| t.id == task_name);
                    let outputs = ir_task.map(|t| t.outputs.clone()).unwrap_or_default();
                    let synthetic_task =
                        create_synthetic_matrix_task(task_name, matrix_task, outputs);
                    let arch_runners = ctx
                        .github_config
                        .runners
                        .as_ref()
                        .and_then(|r| r.arch.clone());

                    let expanded_jobs = emitter.build_matrix_jobs(
                        &synthetic_task,
                        ir,
                        ctx.environment.as_ref(),
                        arch_runners.as_ref(),
                        &[],
                        ctx.project_path.as_deref(),
                    );

                    for (id, job) in expanded_jobs {
                        artifact_source_jobs.insert(id.clone());
                        jobs.insert(id, job);
                    }
                }
            }
        }
    }

    // Add transitive dependencies not in pipeline tasks
    // NOTE: We ONLY add non-phase tasks here. Phase tasks (bootstrap, setup, success, failure)
    // are rendered as STEPS within jobs via render_phase_steps(), NOT as separate jobs.
    for ir_task in &ctx.tasks {
        // Skip phase tasks - they're rendered as STEPS within jobs, not separate jobs
        if ir_task.phase.is_some() {
            continue;
        }

        // Skip if this task was explicitly in the pipeline (including as matrix task)
        if processed_task_names.contains(&ir_task.id) {
            continue;
        }

        let job_id = ir_task.id.replace(['.', ' '], "-");
        if jobs.contains_key(&job_id) {
            continue;
        }

        // Use emitter method directly
        let mut job = emitter.build_simple_job(ir_task, ir, simple_job_options(ctx, ir_task));
        job.needs = ir_task
            .depends_on
            .iter()
            .map(|dep| dep.replace(['.', ' '], "-"))
            .collect();
        jobs.insert(job_id, job);
    }

    jobs
}

/// Create a synthetic IR Task for artifact aggregation from a `MatrixTask`.
///
/// Converts `MatrixTask.artifacts` to IR `Task.artifact_downloads` and
/// `MatrixTask.params` to IR `Task.params`.
fn create_synthetic_aggregation_task(
    task_name: &str,
    matrix_task: &cuenv_core::ci::MatrixTask,
) -> cuenv_ci::ir::Task {
    use cuenv_ci::ir::{ArtifactDownload, CachePolicy, Task};

    let artifact_downloads = matrix_task
        .artifacts
        .as_ref()
        .map(|artifacts| {
            artifacts
                .iter()
                .map(|a| ArtifactDownload {
                    name: a.from.replace('.', "-"),
                    path: a.to.clone(),
                    filter: String::new(),
                })
                .collect()
        })
        .unwrap_or_default();

    // Convert HashMap to BTreeMap for IR compatibility
    let params: BTreeMap<String, String> = matrix_task
        .params
        .clone()
        .unwrap_or_default()
        .into_iter()
        .collect();

    Task {
        id: task_name.to_string(),
        runtime: None,
        command: vec![],
        shell: false,
        env: BTreeMap::new(),
        secrets: BTreeMap::new(),
        resources: None,
        concurrency_group: None,
        inputs: vec![],
        outputs: vec![],
        depends_on: vec![],
        cache_policy: CachePolicy::Normal,
        deployment: false,
        manual_approval: false,
        matrix: None,
        artifact_downloads,
        params,
        // Phase task fields (not applicable for sync tasks)
        phase: None,
        label: None,
        priority: None,
        contributor: None,
        condition: None,
        provider_hints: None,
    }
}

/// Create a synthetic IR Task for matrix expansion from a `MatrixTask`.
///
/// Converts `MatrixTask.matrix` to IR `Task.matrix`.
fn create_synthetic_matrix_task(
    task_name: &str,
    matrix_task: &cuenv_core::ci::MatrixTask,
    outputs: Vec<cuenv_ci::ir::OutputDeclaration>,
) -> cuenv_ci::ir::Task {
    use cuenv_ci::ir::{CachePolicy, MatrixConfig, Task};

    // Convert HashMap to BTreeMap for IR compatibility
    // Sort dimension values for deterministic output
    let dimensions: BTreeMap<String, Vec<String>> = matrix_task
        .matrix
        .iter()
        .map(|(k, v)| {
            let mut sorted_values = v.clone();
            sorted_values.sort();
            (k.clone(), sorted_values)
        })
        .collect();

    let matrix = MatrixConfig {
        dimensions,
        exclude: vec![],
        include: vec![],
        max_parallel: 0,
        fail_fast: true,
    };

    Task {
        id: task_name.to_string(),
        runtime: None,
        command: vec![],
        shell: false,
        env: BTreeMap::new(),
        secrets: BTreeMap::new(),
        resources: None,
        concurrency_group: None,
        inputs: vec![],
        outputs,
        depends_on: vec![],
        cache_policy: CachePolicy::Normal,
        deployment: false,
        manual_approval: false,
        matrix: Some(matrix),
        artifact_downloads: vec![],
        params: BTreeMap::new(),
        // Phase task fields (not applicable for matrix tasks)
        phase: None,
        label: None,
        priority: None,
        contributor: None,
        condition: None,
        provider_hints: None,
    }
}

/// Emit a workflow with matrix expansion for tasks that have matrix configurations.
fn emit_matrix_workflow(
    pipeline_name: &str,
    ctx: &PipelineContext,
) -> Result<Vec<(String, String)>> {
    use cuenv_github::workflow::GitHubActionsEmitter;
    use cuenv_github::workflow::schema::{Concurrency, Workflow};

    let workflow_name = match &ctx.project_name {
        Some(project) => format!("{project}-{pipeline_name}"),
        None => pipeline_name.to_string(),
    };

    let ir = ctx.to_ir(pipeline_name);
    let emitter = GitHubActionsEmitter::from_config(&ctx.github_config).with_nix();

    let explicit_task_names: HashSet<String> = ctx
        .pipeline_tasks
        .iter()
        .map(|pt| pt.task_name().to_string())
        .collect();

    let expanded_tasks = cuenv_ci::pipeline::expand_task_groups(
        &ctx.pipeline_tasks,
        &ctx.tasks,
        &explicit_task_names,
    );

    let jobs = build_pipeline_jobs(&expanded_tasks, ctx, &ir, &emitter);
    let mut jobs = jobs;
    inject_cuenv_bootstrap_jobs(&mut jobs, &ir, &emitter);

    let filename = format!("{}.yml", sanitize_workflow_name(&workflow_name));

    let workflow = Workflow {
        name: workflow_name.clone(),
        on: emitter.build_triggers(&ir, &filename),
        concurrency: Some(Concurrency {
            group: "${{ github.workflow }}-${{ github.head_ref || github.ref }}".to_string(),
            cancel_in_progress: Some(true),
        }),
        permissions: Some(emitter.build_permissions(&ir)),
        env: indexmap::IndexMap::new(),
        jobs,
    };
    let yaml = workflow.to_yaml().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to serialize workflow: {e}"))
    })?;

    Ok(vec![(filename, yaml)])
}

/// Sanitize a workflow name for use as a filename.
fn sanitize_workflow_name(name: &str) -> String {
    name.to_lowercase()
        .replace(' ', "-")
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect()
}

/// Build GitHub Actions trigger condition from pipeline config.
fn build_github_trigger_condition(
    _pipeline_name: &str,
    pipeline: &cuenv_core::ci::Pipeline,
    _ci_config: &cuenv_core::ci::CI,
) -> cuenv_ci::ir::TriggerCondition {
    use cuenv_ci::ir::{ManualTriggerConfig, TriggerCondition, WorkflowDispatchInputDef};
    use cuenv_core::ci::ManualTrigger;

    let when = pipeline.when.as_ref();

    let branches = when
        .and_then(|w| w.branch.as_ref())
        .map(cuenv_core::ci::StringOrVec::to_vec)
        .unwrap_or_default();

    let pull_request = when.and_then(|w| w.pull_request);

    let scheduled = when
        .and_then(|w| w.scheduled.as_ref())
        .map(cuenv_core::ci::StringOrVec::to_vec)
        .unwrap_or_default();

    let release = when.and_then(|w| w.release.clone()).unwrap_or_default();

    let manual = when.and_then(|w| w.manual.as_ref()).map(|m| match m {
        ManualTrigger::Enabled(enabled) => ManualTriggerConfig {
            enabled: *enabled,
            inputs: BTreeMap::new(),
        },
        ManualTrigger::WithInputs(inputs) => ManualTriggerConfig {
            enabled: true,
            inputs: inputs
                .iter()
                .map(|(k, v)| {
                    (
                        k.clone(),
                        WorkflowDispatchInputDef {
                            description: v.description.clone(),
                            required: v.required.unwrap_or(false),
                            default: v.default.clone(),
                            input_type: v.input_type.clone(),
                            options: v.options.clone().unwrap_or_default(),
                        },
                    )
                })
                .collect(),
        },
    });

    TriggerCondition {
        branches,
        pull_request,
        scheduled,
        release,
        manual,
        paths: Vec::new(),
    }
}

/// Sync Buildkite bootstrap pipeline file.
#[instrument(name = "sync_buildkite", skip_all)]
fn execute_sync_buildkite(request: &BuildkiteSyncRequest<'_>) -> Result<String> {
    let BuildkiteSyncRequest { repo_root, options } = *request;
    // Note: Using --dynamic instead of --format for the new CLI
    let pipeline_content = r#"# Buildkite bootstrap pipeline for cuenv
# This installs Nix, builds cuenv, then generates a dynamic pipeline
steps:
  - label: ":nix: Install Nix"
    key: install-nix
    command: |
      curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install linux --no-confirm --init none
      . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
      nix --version

  - label: ":package: Build cuenv"
    key: build-cuenv
    depends_on: install-nix
    command: |
      . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
      nix build .#cuenv --accept-flake-config
      echo "$(pwd)/result/bin" >> "$BUILDKITE_ENV_FILE"

  - label: ":pipeline: Generate Pipeline"
    depends_on: build-cuenv
    command: cuenv ci --dynamic buildkite | buildkite-agent pipeline upload
"#;

    let buildkite_dir = repo_root.join(".buildkite");
    let pipeline_path = buildkite_dir.join("pipeline.yml");

    // Check mode
    if options.check {
        if pipeline_path.exists() {
            let existing = std::fs::read_to_string(&pipeline_path).unwrap_or_default();
            if existing == pipeline_content {
                return Ok("Buildkite: pipeline.yml in sync".to_string());
            }
            return Err(cuenv_core::Error::configuration(
                "Buildkite pipeline.yml out of sync. Run 'cuenv sync ci --provider buildkite' to update.",
            ));
        }
        return Err(cuenv_core::Error::configuration(
            "Buildkite pipeline.yml missing. Run 'cuenv sync ci --provider buildkite' to create.",
        ));
    }

    let exists = pipeline_path.exists();

    // Check if file exists and matches (skip if unchanged)
    if exists && !options.dry_run.is_dry_run() {
        let existing = std::fs::read_to_string(&pipeline_path).unwrap_or_default();
        if existing == pipeline_content {
            return Ok("Buildkite: pipeline.yml (unchanged)".to_string());
        }
    }

    // Dry-run mode
    if options.dry_run.is_dry_run() {
        if exists {
            return Ok("Buildkite: Would update pipeline.yml".to_string());
        }
        return Ok("Buildkite: Would create pipeline.yml".to_string());
    }

    // Create directory if needed
    if !buildkite_dir.exists() {
        std::fs::create_dir_all(&buildkite_dir).map_err(|e| cuenv_core::Error::Io {
            source: e,
            path: Some(buildkite_dir.clone().into_boxed_path()),
            operation: "create directory".to_string(),
        })?;
    }

    // Write file
    std::fs::write(&pipeline_path, pipeline_content).map_err(|e| cuenv_core::Error::Io {
        source: e,
        path: Some(pipeline_path.clone().into_boxed_path()),
        operation: "write pipeline file".to_string(),
    })?;

    if exists {
        Ok("Buildkite: Updated pipeline.yml".to_string())
    } else {
        Ok("Buildkite: Created pipeline.yml".to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cuenv_core::ci::{MatrixTask, PipelineTask, TaskRef};
    use std::collections::BTreeMap;

    #[test]
    fn test_has_matrix_tasks_empty() {
        let tasks: Vec<PipelineTask> = vec![];
        assert!(!has_matrix_tasks(&tasks));
    }

    #[test]
    fn test_has_matrix_tasks_simple_only() {
        let tasks = vec![
            PipelineTask::Simple(TaskRef::from_name("build")),
            PipelineTask::Simple(TaskRef::from_name("test")),
        ];
        assert!(!has_matrix_tasks(&tasks));
    }

    #[test]
    fn test_has_matrix_tasks_with_matrix() {
        let mut matrix = BTreeMap::new();
        matrix.insert(
            "arch".to_string(),
            vec!["linux-x64".to_string(), "darwin-arm64".to_string()],
        );

        let tasks = vec![PipelineTask::Matrix(MatrixTask {
            task_type: Some("matrix".to_string()),
            task: TaskRef::from_name("cargo.build"),
            matrix,
            artifacts: None,
            params: None,
        })];
        assert!(has_matrix_tasks(&tasks));
    }

    #[test]
    fn test_has_matrix_tasks_aggregation_only() {
        // Aggregation task has empty matrix but artifacts
        let tasks = vec![PipelineTask::Matrix(MatrixTask {
            task_type: Some("matrix".to_string()),
            task: TaskRef::from_name("publish"),
            matrix: BTreeMap::new(),
            artifacts: Some(vec![]),
            params: None,
        })];
        // Aggregation tasks are NOT matrix tasks (they don't have matrix dimensions)
        assert!(!has_matrix_tasks(&tasks));
    }

    #[test]
    fn test_has_matrix_tasks_mixed() {
        let mut matrix = BTreeMap::new();
        matrix.insert("arch".to_string(), vec!["linux-x64".to_string()]);

        let tasks = vec![
            PipelineTask::Simple(TaskRef::from_name("check")),
            PipelineTask::Matrix(MatrixTask {
                task_type: Some("matrix".to_string()),
                task: TaskRef::from_name("build"),
                matrix,
                artifacts: None,
                params: None,
            }),
            PipelineTask::Simple(TaskRef::from_name("deploy")),
        ];
        assert!(has_matrix_tasks(&tasks));
    }
}