haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
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
1746
1747
//! End-to-end tests for `haz run` against per-scenario fixtures
//! under `tests/fixtures/run/`. Each fixture is a checked-in
//! workspace topology; each test copies its fixture into a fresh
//! tempdir before invoking the command, so any `.haz/cache/...`
//! the run writes does not leak into the source tree.
//!
//! Test names follow the `<rule>_<description>` convention from
//! CLAUDE.md so the rules a regression touches are visible from
//! the test name alone.
//!
//! Smoke-fixture-related tests live in `smoke.rs`; this file holds
//! the end-to-end run-coverage tests.

use std::fs;
use std::path::Path;
use std::process::Command;

use haz_cli::EXIT_INTERNAL_OR_CONFIG_ERROR;
use haz_cli::cli::{RunArgs, Scope, TaskRef};
use haz_cli::commands::run;
use haz_cli::context::Context;
use miette::Result;
use tempfile::TempDir;

/// Mimic the dispatch sequence for `haz run`: open a [`Context`]
/// against `cwd`, then execute. Mirrors `lib::dispatch`'s
/// `Cmd::Run` arm so the integration tests exercise the same
/// open-then-execute shape the binary uses.
fn run_run(args: &RunArgs, cwd: &Path) -> Result<i32> {
    run::execute(args, &Context::open(cwd)?)
}

/// Path to the compiled `haz` binary, provided to integration
/// tests by Cargo at compile time. Used by tests that need to
/// capture stdout (e.g. dry-run plan output) where calling
/// `commands::run::execute` directly is insufficient because the
/// function writes to `io::stdout().lock()`.
const HAZ_BIN: &str = env!("CARGO_BIN_EXE_haz");

/// Copy a static fixture directory into a fresh tempdir. The
/// caller passes the leaf name under `tests/fixtures/run/`; the
/// returned `TempDir` drops its contents at test end.
fn fixture_tempdir(name: &str) -> TempDir {
    let src = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/run")
        .join(name);
    let dst = TempDir::new().expect("tempdir creation failed");
    copy_dir_recursive(&src, dst.path());
    dst
}

fn copy_dir_recursive(src: &Path, dst: &Path) {
    fs::create_dir_all(dst).unwrap();
    for entry in fs::read_dir(src).unwrap() {
        let entry = entry.unwrap();
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if entry.file_type().unwrap().is_dir() {
            copy_dir_recursive(&src_path, &dst_path);
        } else {
            fs::copy(&src_path, &dst_path).unwrap();
        }
    }
}

fn bare_run_args() -> RunArgs {
    RunArgs {
        targets: Vec::new(),
        scope: Scope::Default,
        git_filter: None,
        dry_run: false,
        output_mode: None,
    }
}

fn task_ref(s: &str) -> TaskRef {
    TaskRef::parse(s).unwrap()
}

/// Walks $PATH looking for an executable file named `true`. Tests
/// whose tasks spawn `["true"]` skip themselves when the binary
/// is unavailable rather than fail.
fn true_on_path() -> bool {
    binary_on_path("true")
}

/// Walks $PATH looking for an executable file with the given
/// name. Tests whose fixtures depend on host binaries (`touch`,
/// `false`, ...) skip themselves when the binary is unavailable.
fn binary_on_path(name: &str) -> bool {
    let path = std::env::var_os("PATH").unwrap_or_default();
    std::env::split_paths(&path).any(|dir| dir.join(name).exists())
}

/// Write an implicit-mode `.git` marker (a regular file, valid per
/// DISC-001's "regular file (gitlink or submodule pointer)" arm)
/// at `<root>/.git`. The byte sequence is plausible but `haz`
/// does not parse it; only the file's existence as a marker
/// matters.
fn write_git_marker(root: &Path) {
    let contents = "gitdir: /nonexistent\n";
    fs::write(root.join(".git"), contents).expect("write .git marker");
}

// --- implicit-mode workspace (DISC-003) ---

#[test]
fn disc_003_implicit_mode_dry_run_emits_singleton_plan() {
    // DISC-001 / DISC-003: a workspace whose root carries `.git`
    // but no `.haz/` is implicit-mode. The single project is
    // loaded from `<root>/haz.yml`.
    // EXEC-022 / EXEC-023: with no positional and no scope flag,
    // the bearing project is the implicit-mode root project, and
    // the default target resolves to its `default` task.
    // EXEC-030: --dry-run computes the plan and exits 0 without
    // spawning any task. We don't need `true` on PATH for this.
    let tmp = fixture_tempdir("implicit_mode");
    write_git_marker(tmp.path());
    let args = RunArgs {
        dry_run: true,
        ..bare_run_args()
    };
    let code = run_run(&args, tmp.path()).unwrap();
    assert_eq!(code, 0);
    // Cache root MUST NOT be created by a dry-run (EXEC-030's
    // "no side effects" clause).
    assert!(
        !tmp.path().join(".haz").exists(),
        ".haz/ was created by a --dry-run run; EXEC-030 forbids side effects",
    );
}

#[test]
fn disc_003_implicit_mode_default_target_runs() {
    // Real-spawn counterpart of the dry-run test: DISC-003 +
    // EXEC-023 end-to-end with an actual task spawn. The fixture
    // declares `command: ["true"]` with `env.from_host: [PATH]`
    // (same pattern as the smoke fixture's `lib:build`), so the
    // task can resolve `true` from $PATH after env_clear.
    if !true_on_path() {
        eprintln!("skipping: `true` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("implicit_mode");
    write_git_marker(tmp.path());
    let args = bare_run_args();
    let code = run_run(&args, tmp.path()).unwrap();
    assert_eq!(code, 0);
    // A successful fresh run MUST have written a cache manifest
    // (CACHE-017). We don't read it; the `.haz/cache/` dir's
    // existence is enough to prove the engine ran the task to
    // success rather than skipping it.
    assert!(
        tmp.path().join(".haz/cache").is_dir(),
        ".haz/cache/ missing after a successful run of the default target",
    );
}

// --- tag-overlay merging (DAG-001 / DAG-005 / DAG-006) ---

#[test]
fn dag_001_overlay_task_attaches_to_matching_project() {
    // Workspace contains `/lib` (tag `backend`) and `/web` (no
    // tags). The overlay at `.haz/tasks/lint.yml` carries
    // `tagsFilter: [backend]`. DAG-001 attaches `lint` to `lib`
    // (and not to `web`). The positive case: `lib:lint` resolves
    // through `--dry-run`'s target-resolution path.
    let tmp = fixture_tempdir("tag_overlay/matching_and_unmatching");
    let args = RunArgs {
        targets: vec![task_ref("lib:lint")],
        dry_run: true,
        ..bare_run_args()
    };
    let code = run_run(&args, tmp.path()).unwrap();
    assert_eq!(code, 0);
}

#[test]
fn dag_001_overlay_task_not_attached_to_unmatching_project() {
    // Negative case: `web` does NOT carry `backend`, so the
    // overlay's `lint` is NOT in `web`'s effective task set per
    // DAG-001. Target resolution rejects `web:lint` as
    // unresolved (REF-003 against a non-existent task); the
    // execute call surfaces it as a typed error.
    let tmp = fixture_tempdir("tag_overlay/matching_and_unmatching");
    let args = RunArgs {
        targets: vec![task_ref("web:lint")],
        dry_run: true,
        ..bare_run_args()
    };
    let err = run_run(&args, tmp.path()).unwrap_err();
    let msg = format!("{err:?}");
    assert!(
        msg.contains("target resolution failed") || msg.to_lowercase().contains("unresolved"),
        "expected unresolved-target diagnostic, got: {msg}",
    );
}

#[test]
fn dag_005_project_level_source_wins_over_overlay() {
    // The overlay's `lint` body is `["false"]`; the project-
    // level `lint` body is `["true"]`. DAG-005 says project-
    // level wins, so a successful (exit 0) run of `lib:lint`
    // proves the project-level body was the winning source.
    if !true_on_path() {
        eprintln!("skipping: `true` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("tag_overlay/project_level_wins");
    let args = RunArgs {
        targets: vec![task_ref("lib:lint")],
        ..bare_run_args()
    };
    let code = run_run(&args, tmp.path()).unwrap();
    assert_eq!(
        code, 0,
        "lib:lint exited non-zero; the overlay's [\"false\"] body must have won, \
         violating DAG-005's project-level-wins rule",
    );
}

#[test]
fn dag_006_two_overlays_with_incomparable_filters_reject_load() {
    // Two overlays both attach a body for `t1` to `lib` with
    // tagsFilters that are incomparable under set inclusion
    // (one targets `[backend]`, the other targets
    // `[javascript]`, both matching exactly `{lib}`). With no
    // project-level source for `t1`, DAG-006 requires the
    // workspace to be rejected at load. `haz run` surfaces this
    // as a typed error before scheduling.
    let tmp = fixture_tempdir("tag_overlay/incomparable_filters_reject");
    // Target the default task; the failure happens at workspace
    // load and never reaches target resolution. Picking any
    // valid-looking positional makes the failure path the
    // workspace's, not the user's.
    let args = bare_run_args();
    let err = run_run(&args, tmp.path()).unwrap_err();
    let msg = format!("{err:?}").to_lowercase();
    assert!(
        msg.contains("workspace") || msg.contains("overlay") || msg.contains("collision"),
        "expected a workspace-load diagnostic mentioning the overlay collision, got: {msg}",
    );
}

// --- failure cascade and task-failure exit class
//             (EXEC-009 / EXEC-010 / EXEC-011 / EXEC-021) ---

/// Run the `failure_cascade` fixture with `--all` and return the
/// exit code plus the tempdir handle (so the caller can inspect
/// markers in `<tempdir>/lib/`).
fn run_failure_cascade_all() -> (i32, TempDir) {
    let tmp = fixture_tempdir("failure_cascade");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    // EXEC-024: `--all` from inside the bearing project selects
    // every task in that project. Running from `<tempdir>/lib`
    // makes `lib` the bearing project.
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    (code, tmp)
}

#[test]
fn exec_011_failed_predecessor_skips_descendant() {
    // EXEC-011: when `mid` fails, every task transitively
    // reachable from `mid` over hard edges enters the skipped
    // state and MUST NOT be started. `tip`'s command would touch
    // `marker_tip` if it ran; the marker's absence post-run
    // proves the skip.
    if !binary_on_path("touch") || !binary_on_path("false") {
        eprintln!("skipping: `touch` or `false` not on $PATH");
        return;
    }
    let (_code, tmp) = run_failure_cascade_all();
    assert!(
        !tmp.path().join("lib/marker_tip").exists(),
        "marker_tip exists; `tip` was not skipped after `mid`'s failure (EXEC-011)",
    );
}

#[test]
fn exec_010_failed_branch_does_not_skip_sibling() {
    // EXEC-010: `independent` has no hard-edge ancestry from
    // `mid`, so `mid`'s failure MUST NOT prevent it from
    // running. The marker proves it ran to success.
    if !binary_on_path("touch") || !binary_on_path("false") {
        eprintln!("skipping: `touch` or `false` not on $PATH");
        return;
    }
    let (_code, tmp) = run_failure_cascade_all();
    assert!(
        tmp.path().join("lib/marker_independent").exists(),
        "marker_independent missing; `independent` was not run despite \
         being on an unrelated branch from `mid`'s failure (EXEC-010)",
    );
    // `seed` ran upstream of the failure and succeeded; its
    // marker proves the engine got past the first hop.
    assert!(
        tmp.path().join("lib/marker_seed").exists(),
        "marker_seed missing; `seed` did not run before `mid`",
    );
}

#[test]
fn exec_021_task_failure_exit_code_distinct_from_success() {
    // EXEC-021 second class (task failure): non-zero exit code,
    // distinct from the success class (0) and from the config-
    // error / internal class (`EXIT_INTERNAL_OR_CONFIG_ERROR`).
    // A task-failure outcome reaches `run::execute` as
    // `Ok(non_zero)`, not as `Err`; an `Err` here would mean the
    // workspace failed to load, which is a different class.
    if !binary_on_path("touch") || !binary_on_path("false") {
        eprintln!("skipping: `touch` or `false` not on $PATH");
        return;
    }
    let (code, _tmp) = run_failure_cascade_all();
    assert_ne!(code, 0, "expected non-zero exit on task failure");
    assert_ne!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "task-failure exit code MUST distinguish itself from the \
         internal/config-error class per EXEC-021",
    );
}

// --- soft edges (EXEC-008 / EXEC-011 / DAG-010 / EXEC-030) ---

#[test]
fn exec_008_soft_edge_predecessor_not_pulled_by_consumer_alone() {
    // EXEC-008: a soft-edge predecessor (`producer`) is NOT
    // scheduled solely on behalf of the successor's readiness.
    // Running `haz run lib:consumer` MUST NOT run `producer`.
    // The fixture pre-stages `shared.txt` with the bytes
    // "initial\n"; if `producer` had run, its shell would have
    // overwritten the file with "from-producer". Comparing the
    // post-run content against the pre-staged content discriminates.
    if !binary_on_path("sh") || !binary_on_path("printf") {
        eprintln!("skipping: `sh` or `printf` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("soft_edges/trigger_via_cache_invalidation");
    let args = RunArgs {
        targets: vec![task_ref("lib:consumer")],
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_eq!(code, 0);
    let shared_after = fs::read_to_string(tmp.path().join("lib/shared.txt")).unwrap();
    assert_eq!(
        shared_after, "initial\n",
        "shared.txt was rewritten; `producer` ran despite being soft-only \
         (EXEC-008: soft predecessor MUST NOT be pulled by consumer's readiness)",
    );
}

#[test]
fn exec_008_soft_edge_triggers_via_cache_invalidation_across_runs() {
    // EXEC-008's underlying mechanism: file contents at the
    // consumer's `inputs` paths flow into its cache key per
    // CACHE-006, so a producer-driven mutation of those files
    // forces consumer's next lookup to miss and re-run.
    //
    // Sequence:
    //   1. haz run lib:consumer (producer NOT pulled; shared.txt
    //      = "initial\n"). consumer hashes "initial\n", misses,
    //      runs, appends "x" to marker_consumer.
    //   2. haz run lib:producer. producer runs, overwrites
    //      shared.txt with "from-producer".
    //   3. haz run lib:consumer again. consumer's inputs hash
    //      now differs. Cache miss, fresh run, appends another
    //      "x" to marker_consumer.
    // Discriminator: marker_consumer's byte length equals the
    // number of consumer fresh runs (a cache hit replays
    // captured streams but does NOT re-run the action).
    if !binary_on_path("sh") || !binary_on_path("printf") {
        eprintln!("skipping: `sh` or `printf` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("soft_edges/trigger_via_cache_invalidation");
    let lib_dir = tmp.path().join("lib");

    let consumer = RunArgs {
        targets: vec![task_ref("lib:consumer")],
        ..bare_run_args()
    };
    let producer = RunArgs {
        targets: vec![task_ref("lib:producer")],
        ..bare_run_args()
    };

    assert_eq!(run_run(&consumer, &lib_dir).unwrap(), 0);
    assert_eq!(run_run(&producer, &lib_dir).unwrap(), 0);
    assert_eq!(run_run(&consumer, &lib_dir).unwrap(), 0);

    let marker = fs::read(lib_dir.join("marker_consumer")).expect("marker_consumer missing");
    assert_eq!(
        marker.len(),
        2,
        "expected 2 fresh consumer runs (one per inputs-hash); \
         got {} byte(s) -- the second invocation likely hit cache, \
         violating CACHE-006 / EXEC-008's invalidation mechanism",
        marker.len(),
    );
}

#[test]
fn exec_030_dry_run_plan_excludes_soft_predecessor() {
    // EXEC-030 + EXEC-001/002: the dry-run plan enumerates the
    // selected tasks plus their transitive HARD predecessors.
    // Soft-edge predecessors are NOT pulled (EXEC-008). So
    // `haz run --dry-run lib:consumer` MUST list `lib:consumer`
    // and MUST NOT list `lib:producer`.
    //
    // Captured via subprocess because `commands::run::execute`
    // writes the plan to `io::stdout().lock()`.
    let tmp = fixture_tempdir("soft_edges/trigger_via_cache_invalidation");
    let output = Command::new(HAZ_BIN)
        .args(["run", "--dry-run", "lib:consumer"])
        .current_dir(tmp.path().join("lib"))
        .output()
        .expect("failed to spawn haz binary");
    assert!(
        output.status.success(),
        "haz run --dry-run exited non-zero: {:?}; stderr: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr),
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("lib:consumer"),
        "dry-run plan missing lib:consumer: {stdout}",
    );
    assert!(
        !stdout.contains("lib:producer"),
        "dry-run plan unexpectedly includes lib:producer; a soft-edge \
         predecessor was pulled (EXEC-008 / EXEC-030 violation): {stdout}",
    );
}

#[test]
fn exec_011_soft_edge_failure_does_not_cascade() {
    // EXEC-011 distinction: when `producer` (the soft-edge
    // predecessor) FAILS, consumer MUST NOT be skipped (no hard
    // cascade). `producer` is in the selected set so its
    // failure surfaces in the exit code; `consumer` is in the
    // selected set with only a soft edge to producer, so it
    // runs to success.
    if !binary_on_path("touch") || !binary_on_path("false") {
        eprintln!("skipping: `touch` or `false` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("soft_edges/non_cascade_on_failure");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_ne!(code, 0, "producer failed; expected non-zero exit code");
    assert!(
        tmp.path().join("lib/marker_consumer").exists(),
        "marker_consumer missing; consumer was skipped despite the \
         producer-consumer edge being soft (EXEC-011 violation)",
    );
}

#[test]
fn dag_010_same_node_in_deps_and_weakdeps_rejects_load() {
    // DAG-010: a node that resolves into BOTH `deps` and
    // `weakDeps` of the same bearing task is rejected at
    // workspace load. The CLI surfaces this through `execute()`
    // as an Err before any scheduling happens.
    let tmp = fixture_tempdir("soft_edges/deps_weakdeps_collision");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let err = run_run(&args, &tmp.path().join("lib")).unwrap_err();
    let msg = format!("{err:?}").to_lowercase();
    assert!(
        msg.contains("deps") && (msg.contains("weakdeps") || msg.contains("weak_deps")),
        "expected a DAG-010 diagnostic mentioning deps + weakDeps overlap, got: {msg}",
    );
}

// --- runtime invariants (DAG-015 / EXEC-019 / EXEC-020) ---

#[test]
fn dag_015_literal_output_uniqueness_rejects_workspace_load() {
    // DAG-015: two tasks declaring the same LITERAL output path
    // is rejected at workspace load. Literal collisions are
    // statically decidable, distinct from DAG-016 / EXEC-020's
    // runtime treatment of glob overlaps. `haz run` surfaces
    // the failure as Err before any scheduling.
    let tmp = fixture_tempdir("runtime_invariants/literal_output_collision");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let err = run_run(&args, &tmp.path().join("lib")).unwrap_err();
    let msg = format!("{err:?}").to_lowercase();
    assert!(
        msg.contains("collision.txt") || msg.contains("literal output"),
        "expected a DAG-015 diagnostic naming the colliding literal output, got: {msg}",
    );
}

#[test]
fn exec_020_glob_output_overlap_surfaces_at_runtime() {
    // Two tasks declare overlapping glob outputs (`out/*.txt`)
    // and both write `out/result.txt`. DAG-015 only addresses
    // literal collisions; DAG-016 defers glob overlaps to
    // runtime; EXEC-020 catches the runtime collision. The
    // workspace loads cleanly; the failure surfaces as the
    // EXEC-021 task-failure exit class.
    if !binary_on_path("sh") || !binary_on_path("mkdir") || !binary_on_path("printf") {
        eprintln!("skipping: required shell utilities not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("runtime_invariants/glob_output_overlap");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_ne!(
        code, 0,
        "expected a non-zero exit code; the runtime overlap of \
         out/result.txt across `a` and `b` was not surfaced (EXEC-020)",
    );
    assert_ne!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "EXEC-020 surfaces as task-failure class, not config-error class",
    );
}

#[test]
fn exec_019_glob_producer_matching_cycle_aborts_at_runtime() {
    // Two tasks form a glob-vs-glob producer-matching cycle
    // (gen consumes *.src + produces *.gen; src consumes *.gen
    // + produces *.src). The static checker in
    // libs/haz-dag/src/producer.rs does not add any
    // producer-matching edge for glob-vs-glob pairs, so the
    // workspace loads. At runtime the second task's
    // materialised outputs close the cycle and EXEC-019 fires.
    if !binary_on_path("sh") || !binary_on_path("printf") {
        eprintln!("skipping: `sh` or `printf` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("runtime_invariants/runtime_cycle");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_ne!(
        code, 0,
        "expected non-zero exit; runtime cycle (EXEC-019) was not detected",
    );
    assert_ne!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "EXEC-019 surfaces as task-failure class, not config-error class",
    );
}

// --- concurrency caps + mutex
//             (EXEC-004 / EXEC-005 / EXEC-007 / MUTEX-003 / MUTEX-004
//              + CFG-028 / CFG-029 round-trip) ---

/// Read a marker file produced by the shell snippet
/// `date +%s%N > marker && sleep ... && date +%s%N >> marker`.
/// Returns the `(start_ns, end_ns)` pair as wall-clock nanoseconds.
fn read_interval(marker_path: &Path) -> (u128, u128) {
    let raw = fs::read_to_string(marker_path)
        .unwrap_or_else(|e| panic!("read marker {}: {e}", marker_path.display()));
    let mut lines = raw.lines().map(str::trim).filter(|l| !l.is_empty());
    let start: u128 = lines
        .next()
        .expect("marker missing start line")
        .parse()
        .expect("marker start line not a u128");
    let end: u128 = lines
        .next()
        .expect("marker missing end line")
        .parse()
        .expect("marker end line not a u128");
    (start, end)
}

/// `true` iff the two half-open intervals `(start_ns, end_ns)` share
/// any common point.
fn intervals_overlap(a: (u128, u128), b: (u128, u128)) -> bool {
    a.0.max(b.0) < a.1.min(b.1)
}

/// Skip-helper: every concurrency/mutex fixture depends on the
/// same set of host utilities (`sh`, `date`, `sleep`).
fn timing_utils_available() -> bool {
    binary_on_path("sh") && binary_on_path("date") && binary_on_path("sleep")
}

#[test]
fn exec_007_exclusive_mutex_serialises_concurrent_db_writers() {
    // Two tasks declare the same workspace-global mutex `db` in
    // exclusive mode (MUTEX-002 bare-string shorthand). Per
    // MUTEX-003 + EXEC-007, their command intervals MUST be
    // disjoint even though the global cap (4) would otherwise
    // permit overlap.
    if !timing_utils_available() {
        eprintln!("skipping: sh/date/sleep not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("concurrency_and_mutex/mutex_modes");
    let args = RunArgs {
        targets: vec![task_ref("lib:writer1"), task_ref("lib:writer2")],
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_eq!(code, 0);
    let writer1 = read_interval(&tmp.path().join("lib/marker_writer1"));
    let writer2 = read_interval(&tmp.path().join("lib/marker_writer2"));
    assert!(
        !intervals_overlap(writer1, writer2),
        "writers' intervals overlap; exclusive mutex `db` failed to \
         serialise them (EXEC-007/MUTEX-003). writer1={writer1:?} writer2={writer2:?}",
    );
}

#[test]
fn mutex_004_shared_mode_allows_parallel_readers() {
    // Two tasks declare the workspace-global mutex `db` in
    // shared mode (MUTEX-002 object form, `mode: shared`). Per
    // MUTEX-004, concurrent shared holds are compatible, so the
    // engine (with global cap 4) MUST overlap them.
    if !timing_utils_available() {
        eprintln!("skipping: sh/date/sleep not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("concurrency_and_mutex/mutex_modes");
    let args = RunArgs {
        targets: vec![task_ref("lib:reader_a"), task_ref("lib:reader_b")],
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_eq!(code, 0);
    let reader_a = read_interval(&tmp.path().join("lib/marker_reader_a"));
    let reader_b = read_interval(&tmp.path().join("lib/marker_reader_b"));
    assert!(
        intervals_overlap(reader_a, reader_b),
        "readers' intervals do not overlap; shared-mode mutex SHOULD \
         have admitted concurrent holds (MUTEX-004). reader_a={reader_a:?} reader_b={reader_b:?}",
    );
}

#[test]
fn cfg_028_workspace_default_concurrency_round_trips() {
    // Workspace declares `concurrency.default: 1`. Two
    // independent tasks (no mutex, no tag interactions) MUST
    // serialise. If the workspace setting were not threaded
    // through to the engine, the default of `auto` would
    // (on a multi-core host) admit overlap.
    if !timing_utils_available() {
        eprintln!("skipping: sh/date/sleep not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("concurrency_and_mutex/default_cap_one");
    let args = RunArgs {
        scope: Scope::All,
        ..bare_run_args()
    };
    let code = run_run(&args, &tmp.path().join("lib")).unwrap();
    assert_eq!(code, 0);
    let task_a = read_interval(&tmp.path().join("lib/marker_task_a"));
    let task_b = read_interval(&tmp.path().join("lib/marker_task_b"));
    assert!(
        !intervals_overlap(task_a, task_b),
        "tasks overlapped despite `concurrency.default: 1`; \
         CFG-028 round-trip failed. a={task_a:?} b={task_b:?}",
    );
}

#[test]
fn exec_005_per_tag_cap_serialises_gpu_tasks() {
    // Two projects both carry `gpu`; each defines one task.
    // The workspace's `concurrency.tags.gpu: 1` is the only
    // binding constraint (global cap is 4). Per EXEC-005, the
    // two gpu-tagged tasks MUST NOT be in-flight concurrently.
    if !timing_utils_available() {
        eprintln!("skipping: sh/date/sleep not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("concurrency_and_mutex/per_tag_cap");
    let args = RunArgs {
        scope: Scope::Workspace,
        ..bare_run_args()
    };
    let code = run_run(&args, tmp.path()).unwrap();
    assert_eq!(code, 0);
    let task_a = read_interval(&tmp.path().join("lib_a/marker_task_a"));
    let task_b = read_interval(&tmp.path().join("lib_b/marker_task_b"));
    assert!(
        !intervals_overlap(task_a, task_b),
        "gpu-tagged tasks overlapped despite tag cap 1 (EXEC-005). \
         a={task_a:?} b={task_b:?}",
    );
}

// --- cancellation
//             (EXEC-013 / EXEC-014 / EXEC-021 signal class + CFG-031) ---

#[cfg(unix)]
mod cancellation_unix {
    use super::{HAZ_BIN, binary_on_path, fixture_tempdir};
    use nix::sys::signal::{Signal, kill};
    use nix::unistd::Pid;
    use std::process::{Command, Stdio};
    use std::thread;
    use std::time::{Duration, Instant};

    /// Spawn `haz run --workspace` against the cancellation
    /// fixture, deliver `signal` after a short startup delay,
    /// and wait for the process to exit. Returns
    /// `(exit_code, elapsed_after_signal)` where the exit code
    /// is whatever the haz process emitted and the elapsed time
    /// is wall-clock from signal delivery to process reap.
    fn run_and_signal(signal: Signal) -> (Option<i32>, Duration) {
        let tmp = fixture_tempdir("cancellation");
        let mut child = Command::new(HAZ_BIN)
            .args(["run", "--workspace"])
            .current_dir(tmp.path())
            // Drop stdout/stderr so the test logs are quiet; we
            // only care about the exit code and timing.
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("failed to spawn haz binary");

        // Let the engine reach the in-flight state (it must
        // load the workspace, build the graph, dispatch the
        // task, and start `sleep 10`). 250ms is comfortable on
        // CI; if the engine has not started the task yet, the
        // SIGINT still propagates through the haz process's
        // own handler and the test passes.
        thread::sleep(Duration::from_millis(250));

        let pid = Pid::from_raw(i32::try_from(child.id()).expect("pid fits i32"));
        kill(pid, signal).expect("failed to deliver signal");

        let signal_sent = Instant::now();

        // Poll for completion with a 5-second ceiling. The
        // workspace's `execution.cancel_grace: 0.5` plus
        // process-spawn slack should put real exits at well
        // under 2 seconds; the ceiling guards against a stuck
        // child.
        let deadline = signal_sent + Duration::from_secs(5);
        loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    let elapsed = signal_sent.elapsed();
                    return (status.code(), elapsed);
                }
                Ok(None) => {
                    if Instant::now() >= deadline {
                        child.kill().ok();
                        let _ = child.wait();
                        panic!(
                            "haz did not exit within 5s of {signal:?}; \
                             cancellation handling broken"
                        );
                    }
                    thread::sleep(Duration::from_millis(25));
                }
                Err(e) => panic!("try_wait failed: {e}"),
            }
        }
    }

    #[test]
    fn exec_013_sigint_during_run_cancels_in_flight_and_exits_130() {
        // EXEC-013 + EXEC-021 POSIX signal-class convention:
        // SIGINT to the haz process MUST cancel in-flight tasks
        // and exit with status 130 (= 128 + 2).
        if !binary_on_path("sleep") {
            eprintln!("skipping: `sleep` not on $PATH");
            return;
        }
        let (code, _elapsed) = run_and_signal(Signal::SIGINT);
        assert_eq!(
            code,
            Some(130),
            "expected exit code 130 (128 + SIGINT) per EXEC-021 POSIX convention",
        );
    }

    #[test]
    fn exec_014_grace_period_round_trips_from_workspace_yml() {
        // The workspace's `execution.cancel_grace: 0.5` MUST
        // be honored end-to-end. A successful round-trip means
        // the haz process exits well under the default of 5s
        // after the signal. Generous bound: 3s (covers the
        // 0.5s grace + SIGKILL + reap + scheduling slack on
        // loaded CI hosts without admitting the 5s default).
        if !binary_on_path("sleep") {
            eprintln!("skipping: `sleep` not on $PATH");
            return;
        }
        let (_code, elapsed) = run_and_signal(Signal::SIGINT);
        assert!(
            elapsed < Duration::from_secs(3),
            "cancellation took {elapsed:?}; the workspace's \
             execution.cancel_grace: 0.5 was not honored (CFG-031 round-trip failed)",
        );
    }

    #[test]
    fn exec_021_signal_class_distinct_from_task_failure() {
        // EXEC-021: the signal-interrupt class MUST be
        // distinguishable from the task-failure class and from
        // the internal/config-error class. SIGTERM should map
        // to 143 (= 128 + 15) under the POSIX convention.
        if !binary_on_path("sleep") {
            eprintln!("skipping: `sleep` not on $PATH");
            return;
        }
        let (code, _elapsed) = run_and_signal(Signal::SIGTERM);
        let code = code.expect("haz produced no exit code");
        assert_ne!(code, 0, "signal class is non-zero");
        assert_ne!(
            code,
            haz_cli::EXIT_INTERNAL_OR_CONFIG_ERROR,
            "signal class must differ from internal/config class",
        );
        assert_eq!(
            code, 143,
            "expected exit code 143 (128 + SIGTERM) per EXEC-021 POSIX convention",
        );
    }
}

// --- output-mode precedence (EXEC-016 / EXEC-017 / CFG-030) ---

/// Run `haz` against the given fixture root with the supplied
/// argv (after the `run` subcommand). Returns the captured
/// stdout. Panics if the binary exits non-zero.
fn capture_run_stdout(fixture: &str, run_args: &[&str]) -> String {
    let tmp = fixture_tempdir(fixture);
    capture_haz_stdout_in(tmp.path(), run_args)
}

fn capture_haz_stdout_in(workspace_root: &Path, run_args: &[&str]) -> String {
    let mut cmd = Command::new(HAZ_BIN);
    cmd.arg("run").args(run_args).current_dir(workspace_root);
    let output = cmd.output().expect("failed to spawn haz");
    assert!(
        output.status.success(),
        "haz run {run_args:?} exited non-zero: {:?}; stderr: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr),
    );
    String::from_utf8(output.stdout).expect("haz stdout was not utf-8")
}

#[test]
fn exec_016_live_mode_tags_lines_with_project_task_prefix() {
    // Default value of `output.mode` is `live` (CFG-030). The
    // fixture's workspace declares no `output:` mapping, so the
    // live default is exercised without any CLI override. Each
    // task's stdout line MUST be prefixed `[<project>:<task>] `.
    if !binary_on_path("sh") || !binary_on_path("echo") {
        eprintln!("skipping: sh/echo not on $PATH");
        return;
    }
    let stdout = capture_run_stdout("output_modes/default_live", &["lib:task_a", "lib:task_b"]);
    assert!(
        stdout.contains("[lib:task_a] hello-from-a"),
        "expected `[lib:task_a] hello-from-a` line in live mode; got: {stdout}",
    );
    assert!(
        stdout.contains("[lib:task_b] hello-from-b"),
        "expected `[lib:task_b] hello-from-b` line in live mode; got: {stdout}",
    );
}

#[test]
fn exec_016_buffered_mode_blocks_per_task_no_prefix() {
    // Workspace declares `output.mode: buffered` (CFG-030). The
    // CLI does NOT pass `--output-mode`, so the workspace value
    // takes effect. Each task's stdout MUST appear verbatim and
    // MUST NOT carry a `[project:task] ` prefix.
    if !binary_on_path("sh") || !binary_on_path("echo") {
        eprintln!("skipping: sh/echo not on $PATH");
        return;
    }
    let stdout = capture_run_stdout(
        "output_modes/workspace_buffered",
        &["lib:task_a", "lib:task_b"],
    );
    assert!(
        stdout.contains("hello-from-a"),
        "expected `hello-from-a` in buffered output; got: {stdout}",
    );
    assert!(
        stdout.contains("hello-from-b"),
        "expected `hello-from-b` in buffered output; got: {stdout}",
    );
    assert!(
        !stdout.contains("[lib:task_a]"),
        "buffered mode MUST NOT prefix lines with the project:task tag; got: {stdout}",
    );
    assert!(
        !stdout.contains("[lib:task_b]"),
        "buffered mode MUST NOT prefix lines with the project:task tag; got: {stdout}",
    );
}

#[test]
fn exec_016_cli_flag_overrides_workspace_default() {
    // Workspace declares `output.mode: buffered`. The CLI
    // override `--output-mode live` MUST win per the EXEC-016
    // precedence chain (CLI > workspace > default). Observable
    // signal: the live-mode `[project:task] ` line prefix.
    if !binary_on_path("sh") || !binary_on_path("echo") {
        eprintln!("skipping: sh/echo not on $PATH");
        return;
    }
    let stdout = capture_run_stdout(
        "output_modes/workspace_buffered",
        &["--output-mode", "live", "lib:task_a", "lib:task_b"],
    );
    assert!(
        stdout.contains("[lib:task_a] hello-from-a"),
        "CLI --output-mode live did not override workspace `buffered`; got: {stdout}",
    );
}

#[test]
fn exec_017_cache_hit_emits_recorded_streams_under_active_mode() {
    // EXEC-017: a cache hit replays the recorded stdout under
    // the currently-active output mode. Sequence:
    //   1. Cold run captures stdout and stores manifest.
    //   2. Warm run is a hit; stdout is replayed.
    // Same tempdir for both runs so the cache from the first
    // is visible to the second.
    if !binary_on_path("sh") || !binary_on_path("echo") {
        eprintln!("skipping: sh/echo not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("output_modes/default_live");
    let cold = capture_haz_stdout_in(tmp.path(), &["lib:task_a"]);
    assert!(
        cold.contains("[lib:task_a] hello-from-a"),
        "cold run missing live-tagged line: {cold}",
    );
    let warm = capture_haz_stdout_in(tmp.path(), &["lib:task_a"]);
    assert!(
        warm.contains("[lib:task_a] hello-from-a"),
        "warm (cache-hit) run did not re-emit the recorded stdout under \
         the active live mode: {warm}",
    );
}

// --- git-changeset modes (EXEC-026 / EXEC-028 / EXEC-029) ---

/// Run `git <args>` from `cwd`. Panics on non-zero exit so a
/// broken setup fails the test loudly rather than silently
/// corrupting the scenario.
fn git_in(cwd: &Path, args: &[&str]) {
    let output = Command::new("git")
        .args(args)
        .current_dir(cwd)
        // Keep the test environment minimal and deterministic.
        // GIT_AUTHOR_* / GIT_COMMITTER_* avoid depending on the
        // host's git config.
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@example.com")
        .env_remove("GIT_DIR")
        .env_remove("GIT_WORK_TREE")
        .output()
        .unwrap_or_else(|e| panic!("git {args:?}: {e}"));
    assert!(
        output.status.success(),
        "git {args:?} failed: {}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// Capture `git <args>` stdout and return it. Panics on non-zero.
fn git_capture(cwd: &Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .env("GIT_AUTHOR_NAME", "test")
        .env("GIT_AUTHOR_EMAIL", "test@example.com")
        .env("GIT_COMMITTER_NAME", "test")
        .env("GIT_COMMITTER_EMAIL", "test@example.com")
        .output()
        .unwrap_or_else(|e| panic!("git {args:?}: {e}"));
    assert!(
        output.status.success(),
        "git {args:?} failed: {}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    String::from_utf8(output.stdout).expect("git stdout not utf-8")
}

/// Initialise a git repo at `repo_root`, configure local
/// identity, and commit every existing file as the initial
/// HEAD. The repo's working tree is `repo_root` itself.
fn init_repo_and_commit_initial(repo_root: &Path) {
    git_in(repo_root, &["init", "--quiet", "--initial-branch=main"]);
    git_in(repo_root, &["add", "-A"]);
    git_in(repo_root, &["commit", "--quiet", "-m", "initial"]);
}

#[test]
fn exec_028_git_staged_includes_only_index_diff_files() {
    // EXEC-028: `--git-staged` selects only files whose content
    // differs between HEAD and the index. Tasks whose `inputs`
    // match those files are affected; tasks whose inputs only
    // match unstaged or untracked changes are NOT.
    //
    // Setup in `<tempdir>` (repo root):
    //   1. `git init` + commit the fixture verbatim.
    //   2. Modify staged.txt and `git add` it (staged).
    //   3. Modify unstaged.txt without staging (unstaged).
    //
    // Then `haz run --workspace --git-staged --dry-run` from
    // `<tempdir>/work` lists tasks whose inputs reach the
    // staged set: task_staged is in, task_unstaged is not.
    if !binary_on_path("git") {
        eprintln!("skipping: `git` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("git_changeset_modes");
    init_repo_and_commit_initial(tmp.path());
    let staged_file = tmp.path().join("work/lib/src/staged.txt");
    let unstaged_file = tmp.path().join("work/lib/src/unstaged.txt");
    fs::write(&staged_file, "modified-staged\n").unwrap();
    git_in(tmp.path(), &["add", "work/lib/src/staged.txt"]);
    fs::write(&unstaged_file, "modified-unstaged\n").unwrap();

    let stdout = capture_haz_stdout_in(
        &tmp.path().join("work"),
        &["--workspace", "--git-staged", "--dry-run"],
    );
    assert!(
        stdout.contains("lib:task_staged"),
        "lib:task_staged missing from --git-staged plan; got: {stdout}",
    );
    assert!(
        !stdout.contains("lib:task_unstaged"),
        "lib:task_unstaged unexpectedly present in --git-staged plan; \
         only staged diffs should count. got: {stdout}",
    );
    assert!(
        !stdout.contains("lib:task_committed"),
        "lib:task_committed should not be affected; got: {stdout}",
    );
}

#[test]
fn exec_029_git_changed_since_rev_includes_diff_from_rev() {
    // EXEC-029: `--git-changed-since <REV>` selects every file
    // whose state differs between <REV> and the working tree.
    // That covers both committed changes since <REV> AND
    // current uncommitted modifications.
    //
    // Setup:
    //   1. init + commit -> rev_base.
    //   2. Modify committed.txt and commit (HEAD beyond rev_base).
    //   3. Stage a change to staged.txt.
    //   4. Modify unstaged.txt without staging.
    //
    // `--git-changed-since <rev_base>` should yield all three
    // tasks.
    if !binary_on_path("git") {
        eprintln!("skipping: `git` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("git_changeset_modes");
    init_repo_and_commit_initial(tmp.path());
    let rev_base = git_capture(tmp.path(), &["rev-parse", "HEAD"])
        .trim()
        .to_string();

    // Step 2: committed change.
    fs::write(
        tmp.path().join("work/lib/src/committed.txt"),
        "modified-committed\n",
    )
    .unwrap();
    git_in(tmp.path(), &["add", "work/lib/src/committed.txt"]);
    git_in(tmp.path(), &["commit", "--quiet", "-m", "committed-change"]);

    // Step 3: staged change.
    fs::write(
        tmp.path().join("work/lib/src/staged.txt"),
        "modified-staged\n",
    )
    .unwrap();
    git_in(tmp.path(), &["add", "work/lib/src/staged.txt"]);

    // Step 4: unstaged change.
    fs::write(
        tmp.path().join("work/lib/src/unstaged.txt"),
        "modified-unstaged\n",
    )
    .unwrap();

    let stdout = capture_haz_stdout_in(
        &tmp.path().join("work"),
        &["--workspace", "--git-changed-since", &rev_base, "--dry-run"],
    );
    for task in ["lib:task_staged", "lib:task_unstaged", "lib:task_committed"] {
        assert!(
            stdout.contains(task),
            "{task} missing from --git-changed-since {rev_base} plan; got: {stdout}",
        );
    }
}

#[test]
fn exec_029_unresolvable_rev_surfaces_as_typed_cli_error() {
    // EXEC-029: an unresolvable `<REV>` MUST be reported as a
    // typed CLI error BEFORE any task runs.
    if !binary_on_path("git") {
        eprintln!("skipping: `git` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("git_changeset_modes");
    init_repo_and_commit_initial(tmp.path());

    let output = Command::new(HAZ_BIN)
        .args([
            "run",
            "--workspace",
            "--git-changed-since",
            "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
            "--dry-run",
        ])
        .current_dir(tmp.path().join("work"))
        .output()
        .expect("failed to spawn haz binary");
    assert!(
        !output.status.success(),
        "expected non-zero exit on unresolvable rev",
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("deadbeef")
            || stderr.to_lowercase().contains("rev")
            || stderr.to_lowercase().contains("git"),
        "expected a diagnostic naming the unresolvable rev; got stderr: {stderr}",
    );
}

#[test]
fn exec_026_changeset_outside_workspace_root_is_dropped() {
    // EXEC-026: paths in the git changeset whose canonical
    // location is outside the workspace root MUST be ignored.
    //
    // Setup: the workspace is at `<tempdir>/work/`, but the git
    // repo root is `<tempdir>/`. A file at `<tempdir>/outside/foo.txt`
    // lives in the repo but outside the workspace.
    //
    //   1. Pre-stage `<tempdir>/outside/foo.txt` so it exists
    //      before `git init`.
    //   2. init + commit (HEAD now includes both work/ and outside/).
    //   3. Modify outside/foo.txt only.
    //
    // `haz run --workspace --git-changed --dry-run` should
    // report a zero-task plan (no workspace-internal change).
    if !binary_on_path("git") {
        eprintln!("skipping: `git` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("git_changeset_modes");
    fs::create_dir_all(tmp.path().join("outside")).unwrap();
    fs::write(tmp.path().join("outside/foo.txt"), "initial\n").unwrap();
    init_repo_and_commit_initial(tmp.path());

    fs::write(tmp.path().join("outside/foo.txt"), "modified\n").unwrap();

    let stdout = capture_haz_stdout_in(
        &tmp.path().join("work"),
        &["--workspace", "--git-changed", "--dry-run"],
    );
    // The plan output for an empty selection is "would run 0 tasks."
    // per `commands::run::print_dry_run_plan`.
    assert!(
        stdout.contains("0 task"),
        "expected zero-task plan when only outside-workspace files \
         changed; EXEC-026 should have dropped them. got: {stdout}",
    );
}

// --- positional reference forms
//             (REF-004 / REF-005 / REF-008 + EXEC-001 multi-positional) ---

#[test]
fn ref_004_positional_fan_out_includes_every_project_with_task() {
    // REF-004: `^:build` resolves to every task named `build`
    // across every project in the workspace. The fixture has
    // `build` in lib_backend and lib_frontend; lib_other has
    // no `build`. The plan MUST include both `build` tasks and
    // MUST NOT include lib_other.
    let tmp = fixture_tempdir("references");
    let stdout = capture_haz_stdout_in(tmp.path(), &["^:build", "--dry-run"]);
    assert!(
        stdout.contains("lib_backend:build"),
        "lib_backend:build missing from fan-out plan: {stdout}",
    );
    assert!(
        stdout.contains("lib_frontend:build"),
        "lib_frontend:build missing from fan-out plan: {stdout}",
    );
    assert!(
        !stdout.contains("lib_other:"),
        "lib_other unexpectedly present in fan-out plan; \
         REF-004 should iterate only projects that define `build`: {stdout}",
    );
}

#[test]
fn ref_005_positional_tag_reference_filters_by_tag() {
    // REF-005: `[backend]:build` resolves to every task named
    // `build` whose owning project carries tag `backend`.
    // Only lib_backend carries `backend`; lib_frontend carries
    // `frontend`; lib_other has no tag.
    let tmp = fixture_tempdir("references");
    let stdout = capture_haz_stdout_in(tmp.path(), &["[backend]:build", "--dry-run"]);
    assert!(
        stdout.contains("lib_backend:build"),
        "lib_backend:build missing from tag-reference plan: {stdout}",
    );
    assert!(
        !stdout.contains("lib_frontend:build"),
        "lib_frontend:build unexpectedly present; REF-005 should \
         exclude projects without tag `backend`: {stdout}",
    );
    assert!(
        !stdout.contains("lib_other:"),
        "lib_other unexpectedly present: {stdout}",
    );
}

#[test]
fn ref_008_positional_sibling_fan_out_excludes_bearing() {
    // REF-008: `^~:build` is the sibling-fan-out form. From
    // cwd `<tempdir>/lib_backend`, the bearing project is
    // lib_backend, so the resolved set is every `build` task
    // *except* lib_backend's. lib_frontend has `build`;
    // lib_other does not. Expected plan: lib_frontend:build
    // only.
    let tmp = fixture_tempdir("references");
    let stdout = capture_haz_stdout_in(&tmp.path().join("lib_backend"), &["^~:build", "--dry-run"]);
    assert!(
        stdout.contains("lib_frontend:build"),
        "lib_frontend:build missing from sibling-fan-out plan: {stdout}",
    );
    assert!(
        !stdout.contains("lib_backend:build"),
        "lib_backend:build unexpectedly present; the sibling \
         modifier `~` MUST exclude the bearing project: {stdout}",
    );
    assert!(
        !stdout.contains("lib_other:"),
        "lib_other unexpectedly present: {stdout}",
    );
}

#[test]
fn exec_001_multi_positional_union_pulls_each_closure() {
    // Multiple positional task references on a single
    // invocation form a union: every named task's closure
    // (per EXEC-001/002) lands in the plan. The two
    // project-references here have empty hard-predecessor
    // closures (no `deps`), so the plan is exactly the two
    // named tasks.
    let tmp = fixture_tempdir("references");
    let stdout = capture_haz_stdout_in(
        tmp.path(),
        &["lib_backend:build", "lib_frontend:build", "--dry-run"],
    );
    assert!(
        stdout.contains("lib_backend:build"),
        "lib_backend:build missing from multi-positional plan: {stdout}",
    );
    assert!(
        stdout.contains("lib_frontend:build"),
        "lib_frontend:build missing from multi-positional plan: {stdout}",
    );
}

// --- task-body shapes
//             (CFG-021/022/032/033 + CACHE-005/008 + PATH-009..016) ---

/// Spawn `haz run <args>` from `workspace_root` with an
/// additional environment variable set on the child process.
/// Returns the captured stdout; panics on non-zero exit.
fn capture_haz_stdout_with_env(
    workspace_root: &Path,
    env_var: (&str, &str),
    run_args: &[&str],
) -> String {
    let output = Command::new(HAZ_BIN)
        .arg("run")
        .args(run_args)
        .current_dir(workspace_root)
        .env(env_var.0, env_var.1)
        .output()
        .expect("failed to spawn haz");
    assert!(
        output.status.success(),
        "haz run {run_args:?} (env {}={}) exited non-zero: {:?}; stderr: {}",
        env_var.0,
        env_var.1,
        output.status,
        String::from_utf8_lossy(&output.stderr),
    );
    String::from_utf8(output.stdout).expect("haz stdout not utf-8")
}

/// Count the well-formed `manifest.json` files under
/// `<cache_root>/<shard>/<key>/`. Returns 0 if the cache root
/// is missing.
fn count_cache_manifests(workspace_root: &Path) -> usize {
    let cache_root = workspace_root.join(".haz/cache");
    if !cache_root.is_dir() {
        return 0;
    }
    let mut count = 0;
    let Ok(shards) = fs::read_dir(&cache_root) else {
        return 0;
    };
    for shard in shards.flatten() {
        if !shard.file_type().is_ok_and(|t| t.is_dir()) {
            continue;
        }
        let Ok(entries) = fs::read_dir(shard.path()) else {
            continue;
        };
        for entry in entries.flatten() {
            if !entry.file_type().is_ok_and(|t| t.is_dir()) {
                continue;
            }
            if entry.path().join("manifest.json").is_file() {
                count += 1;
            }
        }
    }
    count
}

#[test]
fn cfg_022_shell_action_with_shell_type_executes_through_named_shell() {
    // CFG-022 + CACHE-005: `shell_type: bash` tags the action
    // and runs the script body under bash. A successful exit
    // proves the named shell was actually invoked.
    if !binary_on_path("bash") {
        eprintln!("skipping: `bash` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("task_bodies");
    let stdout = capture_haz_stdout_in(
        tmp.path(),
        &["lib:task_shell_bash", "--output-mode", "buffered"],
    );
    assert!(
        stdout.contains("bash-ok"),
        "expected `bash-ok` in stdout; the bash-typed shell action did not run: {stdout}",
    );
}

#[test]
fn cache_008_from_host_value_change_invalidates_cache() {
    // CACHE-008: an env.from_host name's VALUE contributes to
    // the cache key. Running the task twice with different
    // MY_HOST_VAR values MUST miss the cache the second time
    // and re-execute. The shell appends a single byte per
    // fresh run to marker_from_host.
    if !binary_on_path("sh") || !binary_on_path("printf") {
        eprintln!("skipping: `sh`/`printf` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("task_bodies");

    capture_haz_stdout_with_env(tmp.path(), ("MY_HOST_VAR", "v1"), &["lib:task_from_host"]);
    capture_haz_stdout_with_env(tmp.path(), ("MY_HOST_VAR", "v2"), &["lib:task_from_host"]);

    let marker =
        fs::read(tmp.path().join("lib/marker_from_host")).expect("marker_from_host missing");
    assert_eq!(
        marker.len(),
        2,
        "expected 2 fresh runs (one per MY_HOST_VAR value); \
         got {} byte(s) -- env.from_host VALUE did not enter the cache key",
        marker.len(),
    );
}

#[test]
fn cache_008_override_value_appears_in_cache_key() {
    // CACHE-008: `env.override` entries contribute to the cache
    // key. Two tasks identical in command + inputs + every
    // other key component, differing ONLY in their override
    // value, MUST produce distinct cache keys (different shard/
    // key directories under `.haz/cache/`).
    if !binary_on_path("sh") {
        eprintln!("skipping: `sh` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("task_bodies");
    capture_haz_stdout_in(
        tmp.path(),
        &["lib:task_override_v1", "lib:task_override_v2"],
    );

    let manifests = count_cache_manifests(tmp.path());
    assert!(
        manifests >= 2,
        "expected at least two distinct cache entries (one per \
         distinct env.override value); found {manifests} manifest(s). \
         CACHE-008 override key contribution failed.",
    );
}

#[test]
fn path_011_glob_inputs_match_files_under_src_recursively() {
    // PATH-009..016 glob expansion + CACHE-006: `inputs:
    // ["src/**/*.rs"]` matches every .rs file at any depth
    // under `src/`. Modifying any matched file MUST change
    // the task's cache key.
    //
    // Sequence:
    //   1. Cold run -> marker has 1 byte.
    //   2. Mutate `src/a.rs` (which the glob matches).
    //   3. Warm run -> cache key differs -> miss, re-run ->
    //      marker has 2 bytes.
    if !binary_on_path("sh") || !binary_on_path("printf") {
        eprintln!("skipping: `sh`/`printf` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("task_bodies");
    capture_haz_stdout_in(tmp.path(), &["lib:task_glob_inputs"]);
    fs::write(
        tmp.path().join("lib/src/a.rs"),
        "// modified-a\nfn a() {}\n",
    )
    .expect("rewrite a.rs");
    capture_haz_stdout_in(tmp.path(), &["lib:task_glob_inputs"]);

    let marker = fs::read(tmp.path().join("lib/marker_glob")).expect("marker_glob missing");
    assert_eq!(
        marker.len(),
        2,
        "expected 2 fresh runs after mutating a glob-matched input; \
         got {} byte(s). The glob may not have been expanded into \
         the cache key contribution.",
        marker.len(),
    );

    // Also verify the nested file is matched: mutating
    // src/nested/b.rs should invalidate the cache too. The
    // marker grows to 3 bytes on the third fresh run.
    fs::write(
        tmp.path().join("lib/src/nested/b.rs"),
        "// modified-b\nfn b() {}\n",
    )
    .expect("rewrite b.rs");
    capture_haz_stdout_in(tmp.path(), &["lib:task_glob_inputs"]);
    let marker = fs::read(tmp.path().join("lib/marker_glob"))
        .expect("marker_glob missing after nested mutation");
    assert_eq!(
        marker.len(),
        3,
        "nested src/nested/b.rs mutation did not invalidate the \
         cache; `src/**/*.rs` glob did not match recursively. \
         marker now has {} byte(s).",
        marker.len(),
    );
}

// --- `--all` two arms + composition with `--git-changed`
//             (EXEC-024 + EXEC-026) ---

#[test]
fn exec_024_all_inside_project_selects_bearing_project_tasks() {
    // EXEC-024 arm 1: cwd inside a project root makes that
    // project the bearing project; `--all` then selects every
    // task in JUST that project.
    let tmp = fixture_tempdir("all_scopes/two_projects");
    let stdout = capture_haz_stdout_in(&tmp.path().join("lib_a"), &["--all", "--dry-run"]);
    assert!(
        stdout.contains("lib_a:build") && stdout.contains("lib_a:lint"),
        "expected both lib_a tasks in the plan; got: {stdout}",
    );
    assert!(
        !stdout.contains("lib_b:"),
        "lib_b tasks unexpectedly present; --all from inside lib_a \
         should NOT widen to other projects (EXEC-024 arm 1): {stdout}",
    );
}

#[test]
fn exec_024_all_outside_every_project_selects_every_workspace_task() {
    // EXEC-024 arm 2: cwd at workspace root (outside every
    // project root) makes `--all` select every task in every
    // project of the workspace.
    let tmp = fixture_tempdir("all_scopes/two_projects");
    let stdout = capture_haz_stdout_in(tmp.path(), &["--all", "--dry-run"]);
    for task in ["lib_a:build", "lib_a:lint", "lib_b:build", "lib_b:lint"] {
        assert!(
            stdout.contains(task),
            "{task} missing from --all plan run from workspace root \
             (EXEC-024 arm 2): {stdout}",
        );
    }
}

#[test]
fn exec_026_all_plus_git_changed_intersects_candidate_set_with_changeset() {
    // EXEC-026: when `--all` accompanies `--git-changed`, the
    // candidate set is what `--all` would pick; the filter
    // narrows to tasks whose inputs match the changeset.
    //
    // Setup: init repo at `<tempdir>`, commit work/, then
    // modify only `work/lib_a/a.txt`. The intersection leaves
    // lib_a:lint (its inputs match a.txt) and excludes
    // lib_b:lint (b.txt unchanged).
    if !binary_on_path("git") {
        eprintln!("skipping: `git` not on $PATH");
        return;
    }
    let tmp = fixture_tempdir("all_scopes/changed_with_all");
    init_repo_and_commit_initial(tmp.path());
    fs::write(tmp.path().join("work/lib_a/a.txt"), "modified-a\n").unwrap();

    let stdout = capture_haz_stdout_in(
        &tmp.path().join("work"),
        &["--all", "--git-changed", "--dry-run"],
    );
    assert!(
        stdout.contains("lib_a:lint"),
        "lib_a:lint missing from --all --git-changed plan after \
         mutating a.txt: {stdout}",
    );
    assert!(
        !stdout.contains("lib_b:lint"),
        "lib_b:lint unexpectedly present; the changeset filter \
         should have excluded it (b.txt was not modified): {stdout}",
    );
}

// --- workspace-load errors surface as EXEC-021 fourth class
//             (DAG-011 / DAG-012 / DAG-015 / CFG-021) ---

/// Run `haz run --workspace --dry-run` against `workspace_root`
/// and return the exit code. Stdout / stderr are discarded;
/// callers are interested in the numeric exit class.
fn haz_exit_code(workspace_root: &Path) -> Option<i32> {
    Command::new(HAZ_BIN)
        .args(["run", "--workspace", "--dry-run"])
        .current_dir(workspace_root)
        .output()
        .expect("failed to spawn haz")
        .status
        .code()
}

#[test]
fn dag_011_unresolved_ref_accumulates_and_surfaces_exit_class_four() {
    // DAG-011 + EXEC-021 fourth class: an unresolved reference
    // surfaces through the binary as exit code
    // EXIT_INTERNAL_OR_CONFIG_ERROR (=2).
    let tmp = fixture_tempdir("workspace_load_errors/unresolved_ref");
    let code = haz_exit_code(tmp.path()).expect("haz produced no exit code");
    assert_eq!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "expected internal/config-error class for unresolved reference",
    );
}

#[test]
fn dag_012_self_reference_surfaces_exit_class_four() {
    // DAG-012 + EXEC-021 fourth class.
    let tmp = fixture_tempdir("workspace_load_errors/self_reference");
    let code = haz_exit_code(tmp.path()).expect("haz produced no exit code");
    assert_eq!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "expected internal/config-error class for self-reference",
    );
}

#[test]
fn dag_015_literal_output_uniqueness_surfaces_exit_class_four() {
    // DAG-015 + EXEC-021 fourth class. Counterpart of the
    // literal-output-collision in-process Err assertion; this one
    // verifies the numeric exit code emitted by main.rs.
    let tmp = fixture_tempdir("workspace_load_errors/literal_output_collision");
    let code = haz_exit_code(tmp.path()).expect("haz produced no exit code");
    assert_eq!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "expected internal/config-error class for literal output collision",
    );
}

#[test]
fn cfg_021_malformed_command_surfaces_exit_class_four() {
    // CFG-021 + EXEC-021 fourth class. An empty command sequence
    // is rejected at config validation.
    let tmp = fixture_tempdir("workspace_load_errors/cfg_malformed_command");
    let code = haz_exit_code(tmp.path()).expect("haz produced no exit code");
    assert_eq!(
        code, EXIT_INTERNAL_OR_CONFIG_ERROR,
        "expected internal/config-error class for malformed command",
    );
}

// --- Parse-error rendering: a malformed YAML / DTO value at one
//     of the three config-file kinds (project, workspace, overlay)
//     surfaces a rich miette diagnostic carrying a stable
//     `haz::cfg::*` code, the YAML key path, a labelled snippet,
//     and a hand-crafted help block. The CFG code MUST appear
//     exactly once per render (no duplicated error block, per
//     CFG-005's "diagnostic pointing at the offending value").

/// Run `haz run <ref>` against `workspace_root` and capture the
/// binary's stderr alongside its exit code. The reference is
/// arbitrary as long as it is syntactically valid (`REF-001`..
/// `REF-008`): it is parsed at the CLI surface but never resolved,
/// because workspace load fails first.
fn haz_run_capture_stderr(workspace_root: &Path) -> (String, Option<i32>) {
    let output = Command::new(HAZ_BIN)
        .args(["run", "p:anything"])
        .current_dir(workspace_root)
        .output()
        .expect("failed to spawn haz");
    let stderr = String::from_utf8(output.stderr).expect("haz stderr was not utf-8");
    (stderr, output.status.code())
}

#[test]
fn cfg_021_command_scalar_renders_rich_diagnostic() {
    let tmp = fixture_tempdir("workspace_load_errors/parse_errors/cfg_021_command_scalar");
    let (stderr, code) = haz_run_capture_stderr(tmp.path());
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "expected internal/config-error class; stderr: {stderr}",
    );
    assert!(
        stderr.contains("haz::cfg::021"),
        "stderr must surface the CFG-021 code; got: {stderr}",
    );
    assert!(
        stderr.contains("tasks.build.command"),
        "stderr must surface the resolved YAML key path; got: {stderr}",
    );
    assert!(
        stderr.contains("echo hi"),
        "stderr must include the offending source snippet; got: {stderr}",
    );
    assert!(
        stderr.contains("command:") && stderr.contains("shell:"),
        "stderr must surface the argv-vs-shell help text; got: {stderr}",
    );
    assert_eq!(
        stderr.matches("haz::cfg::021").count(),
        1,
        "CFG code must appear exactly once; got: {stderr}",
    );
}

#[test]
fn cfg_009_projects_scalar_renders_rich_diagnostic() {
    let tmp = fixture_tempdir("workspace_load_errors/parse_errors/cfg_009_projects_scalar");
    let (stderr, code) = haz_run_capture_stderr(tmp.path());
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "expected internal/config-error class; stderr: {stderr}",
    );
    assert!(
        stderr.contains("haz::cfg::009"),
        "stderr must surface the CFG-009 code; got: {stderr}",
    );
    // The closing `` `projects`) `` is unique to the
    // where-clause (`(at `projects`)`); the help text uses
    // `` `projects` `` only as a noun, never followed by a
    // closing paren. miette may wrap the line, so we don't
    // require the opening `(at` here.
    assert!(
        stderr.contains("`projects`)"),
        "stderr must surface the resolved YAML key path; got: {stderr}",
    );
    assert!(
        stderr.contains("lib_core"),
        "stderr must include the offending source snippet; got: {stderr}",
    );
    assert!(
        stderr.contains("projects: []"),
        "stderr must surface the empty-sequence example from the help; got: {stderr}",
    );
    assert_eq!(
        stderr.matches("haz::cfg::009").count(),
        1,
        "CFG code must appear exactly once; got: {stderr}",
    );
}

#[test]
fn cfg_025_overlay_missing_tasks_renders_rich_diagnostic() {
    let tmp = fixture_tempdir("workspace_load_errors/parse_errors/cfg_025_overlay_missing_tasks");
    let (stderr, code) = haz_run_capture_stderr(tmp.path());
    assert_eq!(
        code,
        Some(EXIT_INTERNAL_OR_CONFIG_ERROR),
        "expected internal/config-error class; stderr: {stderr}",
    );
    assert!(
        stderr.contains("haz::cfg::025"),
        "stderr must surface the CFG-025 code; got: {stderr}",
    );
    assert!(
        stderr.contains("tasks"),
        "stderr must mention the missing `tasks` key; got: {stderr}",
    );
    assert!(
        stderr.contains(".haz/tasks/lint.yml"),
        "stderr must include the offending overlay file path; got: {stderr}",
    );
    assert!(
        stderr.contains("must contain a top-level `tasks` key")
            || stderr.contains("MUST contain a top-level `tasks` key"),
        "stderr must surface the overlay help text; got: {stderr}",
    );
    assert_eq!(
        stderr.matches("haz::cfg::025").count(),
        1,
        "CFG code must appear exactly once; got: {stderr}",
    );
}