zhao-cli 0.5.3

Deterministic, offline change-review and CI gate for data transformation projects.
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
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
//! Integration tests for the `zhao check` command boundary: invokes the
//! actual compiled binary (via `assert_cmd`) against fixture dbt project
//! states and asserts on stdout and exit code -- the seam the rest of the
//! test suite is built on.

use assert_cmd::Command;
use predicates::prelude::*;
use std::path::Path;

fn fixture(name: &str) -> std::path::PathBuf {
    Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures")).join(name)
}

/// Writes the marker file adapter auto-detection looks for
/// (`dbt_project.yml`) into `dir`, with its mtime pinned to the Unix
/// epoch -- far older than any manifest a test writes or copies in
/// afterward, so it can never trip the unrelated current-manifest-
/// freshness check. Pinning matters specifically because `std::fs::copy`
/// (used by several fixtures below to bring in a real manifest) can
/// preserve the *source* file's original mtime on some platforms/
/// filesystems (e.g. an APFS `clonefile` copy) rather than stamping
/// "now" -- an ordinary "write the marker first" ordering isn't reliably
/// enough on its own to guarantee the marker looks older.
fn write_dbt_project_marker(dir: &Path) {
    let path = dir.join("dbt_project.yml");
    std::fs::write(&path, "name: fixture\nversion: '1.0.0'\n")
        .expect("should write dbt_project.yml marker");
    std::fs::File::options()
        .write(true)
        .open(&path)
        .expect("should reopen dbt_project.yml")
        .set_modified(std::time::SystemTime::UNIX_EPOCH)
        .expect("should set an old mtime on dbt_project.yml");
}

/// Acceptance criteria 1, 2, 4, 5 together: with no `--format json`,
/// `zhao check` produces the three-part human-readable report, the
/// "Changed" section lists exactly the Nodes that changed with the
/// precise change described, the summary line's counts match the
/// underlying data, and every reference uses dbt's vocabulary
/// ("model"), never zhao's internal "Node"/"Origin" terms.
#[test]
fn default_text_output_produces_the_three_part_human_readable_report() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .output()
        .expect("command should run");

    assert_eq!(output.status.code(), Some(1));
    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");

    assert!(stdout.contains("Changed:\n"), "{stdout}");
    assert!(stdout.contains("Downstream impact:\n"), "{stdout}");
    assert!(stdout.contains("Summary:"), "{stdout}");

    // "Changed" lists exactly the two Nodes with real Changes, each with
    // its precise change described (not just a generic "something
    // changed").
    assert!(
        stdout.contains("model model.zhao_dbt_test.stg_customers:"),
        "{stdout}"
    );
    assert!(
        stdout.contains("model model.zhao_dbt_test.dim_customers:"),
        "{stdout}"
    );
    assert!(
        stdout.contains("~ column type changed: customer_id (bigint -> int)"),
        "{stdout}"
    );
    assert!(
        stdout.contains("+ column added: marketing_source"),
        "{stdout}"
    );
    assert!(stdout.contains("- column removed: last_name"), "{stdout}");
    assert!(
        stdout.contains("~ join changed at position 0: left -> inner"),
        "{stdout}"
    );

    // Summary counts match the fixture's known 5 Changes / 3 Findings
    // exactly (see `all_applicable_rules_fire_together_on_a_fixture_with_simultaneous_changes`
    // for the same fixture's JSON-shaped equivalent of these counts): 2
    // Nodes changed, 4 of the 5 Changes are column-level (the join
    // change isn't), 1 error-severity Finding, 1 warn-severity Finding
    // (the pass-severity `column-added` Finding isn't counted here).
    assert!(
        stdout.contains("Summary: 2 model(s) changed, 4 column(s) changed, 1 breaking, 1 warning"),
        "{stdout}"
    );

    // Vocabulary: "model", never zhao's internal terms.
    assert!(!stdout.contains("Node "), "{stdout}");
    assert!(!stdout.contains("Origin "), "{stdout}");
}

/// Acceptance criterion 3: "Downstream impact" lists only Nodes actually
/// reached by a breaking/warning Finding (not the whole DAG, and not a
/// Node that merely changed without producing a Finding), each with the
/// specific reference and Rule name -- and a `pass`-severity Finding
/// (informational, not impact) must not appear there at all, even though
/// its underlying Change does appear in "Changed".
#[test]
fn downstream_impact_lists_only_nodes_actually_reached_with_reason_and_rule() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .output()
        .expect("command should run");

    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
    let downstream_impact = stdout
        .split("Downstream impact:\n")
        .nth(1)
        .expect("Downstream impact section should be present")
        .split("\nSummary:")
        .next()
        .expect("Summary should follow Downstream impact");

    assert!(
        downstream_impact.contains(
            "[BREAKING] last_name removed from model model.zhao_dbt_test.stg_customers \
             breaks reference via last_name (column-removed-with-active-references)"
        ),
        "{downstream_impact}"
    );
    assert!(
        downstream_impact
            .contains("[WARN] customer_id type narrowed from bigint to int (column-type-narrowed)"),
        "{downstream_impact}"
    );
    // `marketing_source` (the pass-severity `column-added` Change) must
    // not appear in this section at all -- it's informational, not
    // downstream impact.
    assert!(
        !downstream_impact.contains("marketing_source"),
        "a pass-severity finding must not appear in Downstream impact: {downstream_impact}"
    );
}

/// Acceptance criterion 3's "not the whole DAG" half, proven directly:
/// `breaking_project`'s manifest has six models total, but only
/// `stg_customers` and `dim_customers` are actually changed or reached.
/// The other four -- `stg_payments`, `stg_orders`, `fct_orders`,
/// `fct_orders_incremental` -- are unrelated and must appear in neither
/// "Changed" nor "Downstream impact", even though they're real models in
/// the same project's dependency graph.
#[test]
fn unrelated_models_in_the_same_project_do_not_appear_in_either_section() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .output()
        .expect("command should run");

    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
    // Scoped to "Changed"/"Downstream impact" (everything before the
    // Summary line) -- unlike those two sections, the later Defer plan
    // section legitimately names upstream dependencies of the build set
    // (e.g. stg_orders, which dim_customers depends on) that were never
    // changed or reached themselves, so it's expected to mention Nodes
    // this test's "unrelated" list intentionally excludes from Changed/
    // Downstream impact.
    let changed_and_downstream_impact = stdout
        .split("\nSummary:")
        .next()
        .expect("Summary should follow Changed/Downstream impact");

    for unrelated in [
        "stg_payments",
        "stg_orders",
        "fct_orders",
        "fct_orders_incremental",
    ] {
        assert!(
            !changed_and_downstream_impact.contains(unrelated),
            "{unrelated} is unrelated to this diff and must not appear in Changed or \
             Downstream impact, but it did: {changed_and_downstream_impact}"
        );
    }
}

/// `--no-color`, verified byte-for-byte against a plain-text snapshot (not
/// just "doesn't contain an escape somewhere") -- the exact stdout must be
/// exactly the plain-text rendering, nothing more. Deliberately uses
/// `breaking_project` (a fixture with real `BREAKING`/`WARN` findings,
/// same as the other text-report tests above) rather than a no-changes
/// fixture: the no-changes path returns early before ever reaching the
/// only code that calls `colorize()`, so a snapshot of *that* path would
/// pass identically even if `--no-color` were silently ignored. This one
/// actually exercises the colored code path and proves color was
/// genuinely suppressed on it, not merely absent because it was never
/// going to be there.
#[test]
fn no_color_flag_produces_byte_for_byte_plain_text() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            "Changed:\n\
             \x20 model model.zhao_dbt_test.stg_customers:\n\
             \x20   ~ column type changed: customer_id (bigint -> int)\n\
             \x20   + column added: marketing_source\n\
             \x20   - column removed: last_name\n\
             \x20 model model.zhao_dbt_test.dim_customers:\n\
             \x20   - column removed: last_name\n\
             \x20   ~ join changed at position 0: left -> inner\n\
             \n\
             Downstream impact:\n\
             \x20 model model.zhao_dbt_test.stg_customers:\n\
             \x20   [WARN] customer_id type narrowed from bigint to int (column-type-narrowed)\n\
             \x20 model model.zhao_dbt_test.dim_customers:\n\
             \x20   [BREAKING] last_name removed from model model.zhao_dbt_test.stg_customers \
             breaks reference via last_name (column-removed-with-active-references)\n\
             \n\
             Summary: 2 model(s) changed, 4 column(s) changed, 1 breaking, 1 warning\n\
             \n\
             Impacted models: stg_customers, dim_customers\n\
             \n\
             Defer plan:\n\
             \x20 Build: stg_customers, dim_customers\n\
             \x20 Defer (assumed available): stg_orders\n",
        );
}

/// Auto-detection: with no `--no-color` flag and no CI environment
/// variable forcing color on, stdout being piped (as it always is when
/// captured by `assert_cmd`, exactly like being piped to a file) must
/// suppress color on its own. `GITHUB_ACTIONS`/`NO_COLOR` are explicitly
/// removed from the child's environment first, since this test itself may
/// be running inside zhao-cli's own GitHub Actions CI, which would
/// otherwise force color on and mask a real auto-detection regression.
#[test]
fn auto_detection_suppresses_color_when_stdout_is_not_a_tty() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .env_remove("GITHUB_ACTIONS")
        .env_remove("NO_COLOR")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .output()
        .expect("command should run");

    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
    assert!(
        !stdout.contains('\u{1b}'),
        "piped (non-TTY) stdout outside any CI environment should auto-suppress color: \
         {stdout:?}"
    );
}

/// Acceptance criterion 1: color codes are emitted in a color-capable
/// environment -- simulated via `GITHUB_ACTIONS=true` (assert_cmd's
/// captured stdout is never a real TTY, so this is the only reliable way
/// to exercise the "color enabled" path through the actual binary rather
/// than only through `report.rs`'s unit tests).
#[test]
fn color_codes_are_emitted_in_a_color_capable_environment() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .env("GITHUB_ACTIONS", "true")
        .env_remove("NO_COLOR")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .output()
        .expect("command should run");

    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
    assert!(
        stdout.contains('\u{1b}'),
        "a color-capable environment (GITHUB_ACTIONS=true) should emit ANSI escapes: {stdout:?}"
    );
}

#[test]
fn exits_non_zero_and_reports_the_breaking_change_as_json() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"rule\": \"column-removed-with-active-references\"")
                .and(predicate::str::contains("\"severity\": \"error\""))
                .and(predicate::str::contains(
                    "\"reached\": \"model.zhao_dbt_test.dim_customers\"",
                )),
        );
}

/// Exercises all four v1 Rules together against one realistic fixture:
/// `column-removed-with-active-references` (error), `column-type-narrowed`
/// (warn, `bigint` -> `int`), and `column-added` (pass) all fire; the
/// fixture's join change (`LEFT` -> `INNER`) is a *tightening*, so
/// `join-cardinality-loosened` correctly produces no Finding at all --
/// proving the negative case alongside the three positive ones, not just
/// asserting a count.
#[test]
fn all_applicable_rules_fire_together_on_a_fixture_with_simultaneous_changes() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--format")
        .arg("json")
        .output()
        .expect("command should run");

    let parsed: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    let changes = parsed["changes"]
        .as_array()
        .expect("changes should be an array");
    let findings = parsed["findings"]
        .as_array()
        .expect("findings should be an array");

    // 5 Changes: type change, column added, two column removals, one join change.
    assert_eq!(changes.len(), 5);

    let rules: Vec<&str> = findings
        .iter()
        .map(|f| f["rule"].as_str().unwrap())
        .collect();
    assert_eq!(
        rules.len(),
        3,
        "expected exactly 3 findings, got: {findings:#?}"
    );
    assert!(rules.contains(&"column-removed-with-active-references"));
    assert!(rules.contains(&"column-type-narrowed"));
    assert!(rules.contains(&"column-added"));
    assert!(
        !rules.contains(&"join-cardinality-loosened"),
        "the fixture's join change is LEFT -> INNER, a tightening -- it must not fire"
    );

    let severities: Vec<&str> = findings
        .iter()
        .map(|f| f["severity"].as_str().unwrap())
        .collect();
    assert!(severities.contains(&"error"));
    assert!(severities.contains(&"warn"));
    assert!(severities.contains(&"pass"));
}

#[test]
fn exits_zero_when_nothing_breaking_is_found() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(fixture("clean_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(predicate::str::contains("\"findings\": []"));
}

/// A `--dbt-args "--target-path <dir>"` override changes where the
/// *current* manifest is read from too, not just `zhao lineage`'s --
/// this is what lets `zhao diff` read back a manifest `zhao lineage
/// --compile` isolated away from the project's real `target/`, for
/// `zhao-vscode-ext`'s diff-highlight feature. Uses `--state` (no git
/// Baseline resolution) so this needs no `dbt`/git at all: only the
/// current-manifest read path is under test here.
#[test]
fn a_target_path_override_changes_where_the_current_manifest_is_read_from() {
    let dir = tempfile::tempdir().expect("should create temp dir");
    let project_dir = dir.path();
    write_dbt_project_marker(project_dir);
    std::fs::create_dir_all(project_dir.join("custom_target")).expect("should create dir");
    std::fs::copy(
        fixture("clean_project")
            .join("target")
            .join("manifest.json"),
        project_dir.join("custom_target").join("manifest.json"),
    )
    .expect("should copy fixture manifest into the custom target-path dir");

    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(project_dir)
        .arg("--dbt-args")
        .arg("--target-path custom_target")
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(predicate::str::contains("\"findings\": []"));

    assert!(
        !project_dir.join("target").join("manifest.json").exists(),
        "the current manifest should be read from custom_target/, never written to target/"
    );
}

/// Acceptance criterion 1: the impacted-models list exactly matches the
/// Nodes named in the Downstream impact section.
#[test]
fn impacted_models_matches_the_downstream_impact_nodes() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(predicate::str::contains(
            "\"impacted_models\": [\n    \"stg_customers\",\n    \"dim_customers\"\n  ]",
        ));
}

/// `recommended-command.subcommand` in `zhao.yml` produces a
/// ready-to-run command naming exactly the impacted models -- the
/// zhao-vscode-ext "Copy dbt command"/"Run in Terminal" feature's whole
/// premise: zhao-cli computes it, the extension only displays it.
#[test]
fn recommended_command_is_built_from_impacted_models_when_configured() {
    let dir = tempfile::tempdir().expect("should create temp dir");
    let project_dir = dir.path();
    write_dbt_project_marker(project_dir);
    std::fs::create_dir_all(project_dir.join("target")).expect("should create target dir");
    std::fs::copy(
        fixture("breaking_project")
            .join("target")
            .join("manifest.json"),
        project_dir.join("target").join("manifest.json"),
    )
    .expect("should copy fixture manifest");
    std::fs::write(
        project_dir.join("zhao.yml"),
        "tool: dbt\nrecommended-command:\n  subcommand: run\n",
    )
    .expect("should write zhao.yml");

    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(project_dir)
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(predicate::str::contains(
            "\"recommended_command\": \"dbt run --select stg_customers dim_customers\"",
        ));
}

/// Without `recommended-command.subcommand` configured, no
/// `recommended_command` field appears at all -- zhao never assumes a
/// subcommand, same reasoning as `defer.state`.
#[test]
fn recommended_command_is_absent_from_json_when_not_configured() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(predicate::str::contains("\"recommended_command\"").not());
}

/// A run with zero Changes surfaces `impacted_models`, but empty. A run whose
/// only Change is pass-severity (a column added) still lists the changed
/// model itself, since it has to be rebuilt for the new column to exist, but
/// nothing downstream of it.
#[test]
fn impacted_models_is_empty_with_no_changes_and_names_only_the_changed_model_for_a_pass_change() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(fixture("clean_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(predicate::str::contains("\"impacted_models\": []"));

    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(fixture("non_matching_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(predicate::str::contains(
            "\"impacted_models\": [\n    \"stg_orders\"\n  ]",
        ));
}

/// Acceptance criterion 1: given a fixture project and a Change reaching a
/// subset of Nodes, the computed `--defer` plan correctly identifies
/// which Nodes need building (`stg_customers`, `dim_customers` -- the same
/// set the recommended command selects) versus which can be deferred to
/// an existing state (`stg_orders`, a real upstream dependency of
/// `dim_customers` that was never itself changed or reached).
#[test]
fn defer_plan_identifies_build_and_defer_sets_correctly() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"defer_plan\":")
                .and(predicate::str::contains("\"stg_customers\","))
                .and(predicate::str::contains("\"dim_customers\""))
                .and(predicate::str::contains(
                    "\"defer\": [\n      \"stg_orders\"\n    ]",
                )),
        );
}

/// Acceptance criterion 2: exposed in human-readable output too, same as
/// `--format json`.
#[test]
fn defer_plan_appears_in_human_readable_output() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("Defer plan:\n")
                .and(predicate::str::contains(
                    "Build: stg_customers, dim_customers",
                ))
                .and(predicate::str::contains(
                    "Defer (assumed available): stg_orders",
                )),
        );
}

/// `--defer-target`/`--defer-state` (no `zhao.yml` involved -- the
/// config-cascading behavior itself is covered at the `zhao_core::config`
/// unit level) surface the configured state path on the plan, in both
/// output formats.
#[test]
fn defer_target_and_state_flags_surface_the_state_path() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--defer-target")
        .arg("prod")
        .arg("--defer-state")
        .arg("artifacts/prod/manifest.json")
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("Target: prod").and(predicate::str::contains(
                "State: artifacts/prod/manifest.json",
            )),
        );
}

/// The same flags in `--format json` land on the `defer_plan.state`/
/// `defer_plan.target` keys.
#[test]
fn defer_target_and_state_flags_appear_in_json_output() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--defer-target")
        .arg("prod")
        .arg("--defer-state")
        .arg("artifacts/prod/manifest.json")
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"target\": \"prod\"").and(predicate::str::contains(
                "\"state\": \"artifacts/prod/manifest.json\"",
            )),
        );
}

/// Without either flag (and no `zhao.yml` `defer:` section in this
/// fixture), the plan carries neither a target label nor a state path --
/// exactly the pre-existing behavior.
#[test]
fn no_defer_flags_produce_no_target_or_state() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("breaking_project"))
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("Defer plan:\n")
                .and(predicate::str::contains("Target:").not())
                .and(predicate::str::contains("State:").not()),
        );
}

/// `zhao.yml`'s own `defer:` section (with no CLI flag given) surfaces
/// its configured target/state, proving the config path itself -- not
/// just the CLI-flag path -- reaches the plan.
#[test]
fn zhao_yml_defer_config_surfaces_without_any_cli_flag() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("defer_config_project"))
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("Target: staging").and(predicate::str::contains(
                "State: artifacts/staging/manifest.json",
            )),
        );
}

/// A `--defer-target`/`--defer-state` CLI flag overrides a *conflicting*
/// `zhao.yml` `defer:` value -- not just producing a state path when
/// `zhao.yml` has none at all (`defer_target_and_state_flags_surface_the_state_path`
/// already covers that weaker case).
#[test]
fn defer_flags_override_a_conflicting_zhao_yml_defer_config() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("defer_config_project"))
        .arg("--defer-target")
        .arg("prod")
        .arg("--defer-state")
        .arg("artifacts/prod/manifest.json")
        .arg("--no-color")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("Target: prod")
                .and(predicate::str::contains(
                    "State: artifacts/prod/manifest.json",
                ))
                .and(predicate::str::contains("staging").not())
                .and(predicate::str::contains("artifacts/staging").not()),
        );
}

/// A run with zero impacted Nodes produces no defer plan (nothing to
/// build, so no plan makes sense) -- mirrors
/// `impacted_models_is_empty_when_nothing_is_impactful`.
#[test]
fn no_defer_plan_when_nothing_is_impactful() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(fixture("clean_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(predicate::str::contains("defer_plan").not());
}

/// Distinct from `exits_zero_when_nothing_breaking_is_found`: that test
/// has zero Changes at all. This one has a real Change (a column added)
/// that does produce a Finding -- just a `pass`-severity, informational
/// one -- confirming a non-`error` Finding doesn't fail the gate, rather
/// than exiting zero only because nothing happened.
#[test]
fn exits_zero_when_the_only_finding_is_pass_severity() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(fixture("non_matching_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(
            predicate::str::contains("\"type\": \"column_added\"")
                .and(predicate::str::contains("\"rule\": \"column-added\""))
                .and(predicate::str::contains("\"severity\": \"pass\"")),
        );
}

/// A dedicated golden fixture pair (a real dbt-compiled manifest, not
/// synthetic data) for `column-type-narrowed`'s and
/// `join-cardinality-loosened`'s *positive*/*negative* cases the other
/// fixtures don't happen to cover: `customer_id` documented type widens
/// (`int` -> `bigint`, must NOT fire the narrowing Rule) while
/// `dim_customers`' join loosens (`INNER` -> `LEFT`, must fire).
#[test]
fn type_widening_does_not_fire_while_join_loosening_does() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("rules_project"))
        .arg("--format")
        .arg("json")
        .output()
        .expect("command should run");

    let parsed: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    let findings = parsed["findings"]
        .as_array()
        .expect("findings should be an array");

    assert_eq!(
        findings.len(),
        1,
        "expected only the join-loosening finding, got: {findings:#?}"
    );
    assert_eq!(findings[0]["rule"], "join-cardinality-loosened");
    assert_eq!(findings[0]["from_kind"], "inner");
    assert_eq!(findings[0]["to_kind"], "left");
    assert!(
        !findings.iter().any(|f| f["rule"] == "column-type-narrowed"),
        "a type widening (int -> bigint) must not fire column-type-narrowed"
    );
}

/// A project with no `zhao.yml` at all must behave identically to the v1
/// hardcoded defaults -- this fixture is the same manifest pair as
/// `type_widening_does_not_fire_while_join_loosening_does`, just without
/// a config file, so the two tests together prove the "no config" and
/// "with config" paths diverge only when a `zhao.yml` is actually present.
#[test]
fn no_zhao_yml_behaves_identically_to_v1_defaults() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("rules_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(0) // join-cardinality-loosened defaults to `warn`, not `error`
        .stdout(
            predicate::str::contains("\"rule\": \"join-cardinality-loosened\"")
                .and(predicate::str::contains("\"severity\": \"warn\"")),
        );
}

/// A `zhao.yml` selecting the `strict` Preset must change at least one
/// Rule's outcome from `warn` to `error` versus no config at all -- same
/// fixture as the no-config test above, but with `preset: strict` in
/// `zhao.yml`, changing the exit code from 0 to 1.
#[test]
fn strict_preset_changes_a_warn_rule_to_error() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("config_strict_project"))
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"rule\": \"join-cardinality-loosened\"")
                .and(predicate::str::contains("\"severity\": \"error\"")),
        );
}

/// A per-Rule override in `zhao.yml` must win over the Preset for that
/// Rule only, leaving every other Rule at the Preset's value: `preset:
/// strict` plus an override pinning `column-added` back to `pass` --
/// `column-type-narrowed` (not overridden) must still become `error`
/// under strict, while `column-added` stays `pass` despite strict.
#[test]
fn per_rule_override_wins_only_for_that_rule() {
    let output = Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(fixture("config_override_project"))
        .arg("--format")
        .arg("json")
        .output()
        .expect("command should run");

    let parsed: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    let findings = parsed["findings"]
        .as_array()
        .expect("findings should be an array");

    let type_narrowed = findings
        .iter()
        .find(|f| f["rule"] == "column-type-narrowed")
        .expect("column-type-narrowed should fire");
    assert_eq!(
        type_narrowed["severity"], "error",
        "not overridden -- should follow the strict Preset"
    );

    let column_added = findings
        .iter()
        .find(|f| f["rule"] == "column-added")
        .expect("column-added should fire");
    assert_eq!(
        column_added["severity"], "pass",
        "overridden -- should stay pass despite the strict Preset"
    );
}

/// Builds a fake monorepo under a fresh temp dir: a `.git` marker at the
/// root (so `Config::load_for_project` recognizes it as a repo root) and a
/// nested dbt project directory, with the given fixture's manifest copied
/// in as the project's `target/manifest.json`.
fn fake_monorepo(project_manifest_fixture: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("should create temp dir");
    std::fs::create_dir_all(dir.path().join(".git")).expect("should create .git marker");

    let project_dir = dir.path().join("services").join("analytics");
    std::fs::create_dir_all(project_dir.join("target")).expect("should create project target dir");
    // The marker adapter auto-detection looks for -- written before the
    // manifest copy below so its mtime never trips the unrelated
    // current-manifest-freshness check.
    write_dbt_project_marker(&project_dir);
    std::fs::copy(
        fixture(project_manifest_fixture)
            .join("target")
            .join("manifest.json"),
        project_dir.join("target").join("manifest.json"),
    )
    .expect("should copy fixture manifest");

    (dir, project_dir)
}

/// A root-level `zhao.yml`, with no project-local file at all, must still
/// apply to a nested dbt project -- the monorepo case with only one policy
/// for the whole repo.
#[test]
fn a_root_only_zhao_yml_applies_to_a_nested_dbt_project() {
    let (repo, project_dir) = fake_monorepo("rules_project");
    std::fs::write(repo.path().join("zhao.yml"), "preset: strict\n")
        .expect("should write root zhao.yml");

    // Under the default Preset this Rule is `warn` (see
    // `strict_preset_changes_a_warn_rule_to_error`); the root `zhao.yml`'s
    // `strict` Preset must still raise it to `error` for the nested
    // project, purely from the root file.
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(&project_dir)
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"rule\": \"join-cardinality-loosened\"")
                .and(predicate::str::contains("\"severity\": \"error\"")),
        );
}

/// A project-local `zhao.yml` must win over the root `zhao.yml` for the
/// keys it sets, while the root's Preset still governs everything else --
/// the same override relationship a Preset already has to an individual
/// Rule override, one layer higher.
#[test]
fn a_project_local_zhao_yml_overrides_the_root_one_per_key() {
    let (repo, project_dir) = fake_monorepo("rules_project");
    std::fs::write(repo.path().join("zhao.yml"), "preset: strict\n")
        .expect("should write root zhao.yml");
    std::fs::write(
        project_dir.join("zhao.yml"),
        "rules:\n  join-cardinality-loosened: warn\n",
    )
    .expect("should write project-local zhao.yml");

    // The project-local override pins this one Rule back to `warn` despite
    // the root's `strict` Preset, so the gate passes.
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(&project_dir)
        .arg("--format")
        .arg("json")
        .assert()
        .code(0)
        .stdout(
            predicate::str::contains("\"rule\": \"join-cardinality-loosened\"")
                .and(predicate::str::contains("\"severity\": \"warn\"")),
        );
}

/// A single-project repo (a `.git` at the same level as the dbt project,
/// no monorepo nesting) must keep behaving exactly as it did in #8: its
/// own `zhao.yml` applies, nothing more.
#[test]
fn a_single_project_repo_behaves_exactly_as_before_monorepo_support() {
    let dir = tempfile::tempdir().expect("should create temp dir");
    std::fs::create_dir_all(dir.path().join(".git")).expect("should create .git marker");
    std::fs::create_dir_all(dir.path().join("target")).expect("should create target dir");
    write_dbt_project_marker(dir.path());
    std::fs::copy(
        fixture("rules_project")
            .join("target")
            .join("manifest.json"),
        dir.path().join("target").join("manifest.json"),
    )
    .expect("should copy fixture manifest");
    std::fs::write(dir.path().join("zhao.yml"), "preset: strict\n").expect("should write zhao.yml");

    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("rules_baseline_manifest.json"))
        .arg("--project-dir")
        .arg(dir.path())
        .arg("--format")
        .arg("json")
        .assert()
        .code(1)
        .stdout(
            predicate::str::contains("\"rule\": \"join-cardinality-loosened\"")
                .and(predicate::str::contains("\"severity\": \"error\"")),
        );
}

/// An unknown Rule name or invalid Severity value in `zhao.yml` must
/// produce a clear, actionable error (exit code 2, the same "zhao itself
/// failed" code other config/IO errors use) rather than silently
/// ignoring the mistake.
#[test]
fn invalid_zhao_yml_produces_a_clear_error() {
    // A guaranteed-unique, RAII-cleaned-up temp directory via `tempfile`,
    // not a hand-rolled PID-based name -- the same fix applied to
    // zhao-core's own config tests after a hand-rolled name collided
    // under parallel test execution; this test needs the identical fix,
    // not just a similar one.
    let dir = tempfile::tempdir().expect("should create temp dir");
    std::fs::create_dir_all(dir.path().join("target")).expect("should create target dir");
    std::fs::copy(
        fixture("clean_project")
            .join("target")
            .join("manifest.json"),
        dir.path().join("target").join("manifest.json"),
    )
    .expect("should copy fixture manifest");
    std::fs::write(
        dir.path().join("zhao.yml"),
        "rules:\n  not-a-real-rule: error\n",
    )
    .expect("should write zhao.yml");

    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("diff_baseline_manifest_clean.json"))
        .arg("--project-dir")
        .arg(dir.path())
        .assert()
        .code(2)
        .stderr(
            predicate::str::contains("unknown rule")
                .and(predicate::str::contains("not-a-real-rule")),
        );
}

#[test]
fn exits_with_error_code_on_a_missing_baseline_path() {
    Command::cargo_bin("zhao")
        .expect("binary should build")
        .arg("check")
        .arg("--state")
        .arg(fixture("does_not_exist.json"))
        .arg("--project-dir")
        .arg(fixture("clean_project"))
        .assert()
        .code(2)
        .stderr(predicate::str::contains("error:"));
}

// ---------------------------------------------------------------------
// --check-relations: upgrades or drops the conditional schema-evolution
// flag by actually checking relation existence, via a stub `dbt` on
// `PATH` standing in for `dbt run-operation` -- exercised via `--state`
// (no git needed), since the live check runs against the *current*
// project regardless of how the Baseline was resolved.
// ---------------------------------------------------------------------

#[cfg(unix)]
mod check_relations {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    fn incremental_manifest(select_sql: &str) -> String {
        format!(
            r#"{{
                "metadata": {{"adapter_type": "duckdb"}},
                "sources": {{}},
                "nodes": {{
                    "model.p.m": {{
                        "unique_id": "model.p.m",
                        "resource_type": "model",
                        "name": "m",
                        "database": "db",
                        "schema": "public",
                        "alias": "m",
                        "compiled_code": "{select_sql}",
                        "config": {{"materialized": "incremental"}}
                    }}
                }}
            }}"#
        )
    }

    /// A throwaway project directory: a baseline manifest file (single
    /// column) plus a current `target/manifest.json` (baseline's column
    /// plus one added) -- the schema-changing Change every test in this
    /// module exercises.
    fn project_with_a_schema_change() -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let baseline_path = dir.path().join("baseline_manifest.json");
        std::fs::write(&baseline_path, incremental_manifest("select 1 as id"))
            .expect("should write baseline manifest");
        // The marker adapter auto-detection looks for -- written before
        // the current manifest below so its mtime never trips the
        // unrelated current-manifest-freshness check.
        write_dbt_project_marker(dir.path());

        std::fs::create_dir_all(dir.path().join("target")).expect("should create target dir");
        std::fs::write(
            dir.path().join("target").join("manifest.json"),
            incremental_manifest("select 1 as id, 2 as new_col"),
        )
        .expect("should write current manifest");

        (dir, baseline_path)
    }

    /// A stub `dbt` whose `run-operation` subcommand always echoes the
    /// given result marker line, standing in for a real
    /// `zhao_relation_exists` macro run against a live warehouse.
    fn stub_dbt_run_operation(result: &str) -> tempfile::TempDir {
        let stub_dir = tempfile::tempdir().expect("should create temp dir");
        let path = stub_dir.path().join("dbt");
        std::fs::write(
            &path,
            format!("#!/bin/sh\necho 'ZHAO_RELATION_EXISTS_RESULT:{result}'\n"),
        )
        .expect("should write stub dbt script");
        let mut perms = std::fs::metadata(&path)
            .expect("should stat stub script")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("should chmod stub script");
        // A brief pause: writing then immediately exec'ing a fresh script
        // can spuriously hit `ETXTBSY` on CI's overlayfs -- see the
        // detailed comment on zhao-core's own `stub_dbt_command`.
        std::thread::sleep(std::time::Duration::from_millis(50));
        stub_dir
    }

    /// Acceptance criterion: confirmed existing upgrades the flag to
    /// definitive wording.
    #[test]
    fn upgrades_the_flag_to_definitive_when_the_relation_is_confirmed_to_exist() {
        let (project, baseline) = project_with_a_schema_change();
        let stub_dir = stub_dbt_run_operation("true");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env(
                "PATH",
                format!(
                    "{}:{}",
                    stub_dir.path().display(),
                    std::env::var("PATH").unwrap_or_default()
                ),
            )
            .arg("check")
            .arg("--state")
            .arg(&baseline)
            .arg("--project-dir")
            .arg(project.path())
            .arg("--check-relations")
            .arg("--no-color")
            .output()
            .expect("command should run");

        let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
        assert!(stdout.contains("Schema evolution:"), "{stdout}");
        assert!(!stdout.contains("if this"), "{stdout}");
        assert!(
            stdout.contains("exists in your target environment"),
            "{stdout}"
        );
    }

    /// Acceptance criterion: confirmed absent drops the flag entirely.
    #[test]
    fn drops_the_flag_when_the_relation_is_confirmed_absent() {
        let (project, baseline) = project_with_a_schema_change();
        let stub_dir = stub_dbt_run_operation("false");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env(
                "PATH",
                format!(
                    "{}:{}",
                    stub_dir.path().display(),
                    std::env::var("PATH").unwrap_or_default()
                ),
            )
            .arg("check")
            .arg("--state")
            .arg(&baseline)
            .arg("--project-dir")
            .arg(project.path())
            .arg("--check-relations")
            .arg("--no-color")
            .output()
            .expect("command should run");

        let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
        assert!(!stdout.contains("Schema evolution:"), "{stdout}");
    }

    /// Acceptance criterion: without `--check-relations`, behavior is
    /// unchanged -- the flag stays conditionally worded.
    #[test]
    fn without_the_flag_the_wording_stays_conditional() {
        let (project, baseline) = project_with_a_schema_change();

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--state")
            .arg(&baseline)
            .arg("--project-dir")
            .arg(project.path())
            .arg("--no-color")
            .output()
            .expect("command should run");

        let stdout = String::from_utf8(output.stdout).expect("stdout should be utf8");
        assert!(stdout.contains("Schema evolution:"), "{stdout}");
        assert!(stdout.contains("if this"), "{stdout}");
    }
}

// ---------------------------------------------------------------------
// Git-native Baseline resolution (no `--state`): a throwaway git repo
// with a real merge-base, and a stub `dbt` on `PATH` standing in for a
// real dbt install -- these tests exercise zhao's own merge-base
// resolution, worktree creation, and `dbt compile` invocation end to end,
// without depending on whether a real `dbt` happens to be installed
// wherever they run.
// ---------------------------------------------------------------------

#[cfg(unix)]
mod git_native_baseline {
    use super::*;
    use std::os::unix::fs::PermissionsExt;
    use std::process::Command as StdCommand;

    /// A throwaway git repository, with helpers for the handful of git
    /// operations these tests need.
    struct TestRepo {
        _dir: tempfile::TempDir,
        path: std::path::PathBuf,
    }

    impl TestRepo {
        fn git(&self, args: &[&str]) {
            let output = StdCommand::new("git")
                .current_dir(&self.path)
                .args(args)
                .output()
                .expect("git should be runnable in tests");
            assert!(
                output.status.success(),
                "git {args:?} should succeed: {output:?}"
            );
        }

        fn write(&self, relative_path: &str, contents: &str) {
            let path = self.path.join(relative_path);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("should create parent dir");
            }
            std::fs::write(path, contents).expect("should write file");
        }

        fn commit(&self, message: &str) {
            self.git(&["add", "."]);
            self.git(&["commit", "-m", message]);
        }
    }

    fn new_test_repo() -> TestRepo {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().to_path_buf();
        let repo = TestRepo { _dir: dir, path };

        repo.git(&["init", "--initial-branch=master"]);
        repo.git(&["config", "user.email", "test@zhao.invalid"]);
        repo.git(&["config", "user.name", "zhao test"]);
        // The marker adapter auto-detection looks for -- written before
        // the caller's first commit, so it's tracked (and thus present in
        // every checked-out commit/worktree) from the very start. Written
        // ahead of `target/manifest.json` (always written later, after at
        // least one commit) so its mtime never trips the unrelated
        // current-manifest-freshness check.
        repo.write("dbt_project.yml", "name: fixture\nversion: '1.0.0'\n");
        repo
    }

    /// Writes an executable stub `dbt` to a fresh temp dir: `dbt compile`
    /// just copies `dbt_manifest_source.json` (committed alongside the
    /// project, so its content differs per commit) into
    /// `target/manifest.json` -- close enough to real `dbt compile`'s
    /// contract (produce `target/manifest.json` reflecting the checked-out
    /// state) for these tests, without needing a real dbt install.
    fn stub_dbt_dir() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().join("dbt");
        std::fs::write(
            &path,
            "#!/bin/sh\nmkdir -p target\ncp dbt_manifest_source.json target/manifest.json\n",
        )
        .expect("should write stub dbt script");
        let mut perms = std::fs::metadata(&path)
            .expect("should stat stub script")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("should chmod stub script");
        // A brief pause: writing then immediately exec'ing a fresh script
        // can spuriously hit `ETXTBSY` on CI's overlayfs -- see the
        // detailed comment on zhao-core's own `stub_dbt_command`.
        std::thread::sleep(std::time::Duration::from_millis(50));
        dir
    }

    fn path_with_stub_dbt_prepended(stub_dir: &tempfile::TempDir) -> String {
        let existing = std::env::var("PATH").unwrap_or_default();
        format!("{}:{existing}", stub_dir.path().display())
    }

    /// A stub `dbt` that additionally records every invocation (subcommand
    /// plus args, one line per call) to `invocation_log`, an ABSOLUTE path
    /// outside the git worktree Baseline resolution runs inside --
    /// `git::create_worktree`'s `Worktree` is cleaned up (`Drop`) before
    /// `resolve()` returns, so a log file written to a path relative to the
    /// worktree wouldn't survive for the test to inspect afterwards.
    ///
    /// Only `compile` produces `target/manifest.json` (from
    /// `dbt_manifest_source.json`, as `stub_dbt_dir` does); `deps` and any
    /// other subcommand just log and exit 0.
    fn logging_stub_dbt_dir(invocation_log: &Path) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().join("dbt");
        std::fs::write(
            &path,
            format!(
                "#!/bin/sh\necho \"$@\" >> {log}\nif [ \"$1\" = \"compile\" ]; then\n  mkdir -p target\n  cp dbt_manifest_source.json target/manifest.json\nfi\n",
                log = invocation_log.display()
            ),
        )
        .expect("should write logging stub dbt script");
        let mut perms = std::fs::metadata(&path)
            .expect("should stat stub script")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("should chmod stub script");
        // A brief pause: writing then immediately exec'ing a fresh script
        // can spuriously hit `ETXTBSY` on CI's overlayfs -- see the
        // detailed comment on zhao-core's own `stub_dbt_command`.
        std::thread::sleep(std::time::Duration::from_millis(50));
        dir
    }

    /// Builds a repo with one commit on `master` (whose
    /// `dbt_manifest_source.json` is `baseline_manifest`) and a `feature`
    /// branch one commit ahead (so `master`'s tip is the merge-base), with
    /// `current_manifest` written directly as the working tree's
    /// `target/manifest.json` -- the file `zhao check` reads for "current"
    /// state regardless of Baseline resolution mode.
    fn repo_with_baseline_and_current(baseline_manifest: &str, current_manifest: &str) -> TestRepo {
        let repo = new_test_repo();
        repo.write("dbt_manifest_source.json", baseline_manifest);
        repo.commit("baseline state");

        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of master");

        repo.write("target/manifest.json", current_manifest);
        repo
    }

    fn rules_baseline_manifest_json() -> String {
        std::fs::read_to_string(fixture("rules_baseline_manifest.json"))
            .expect("should read fixture")
    }

    fn rules_project_current_manifest_json() -> String {
        std::fs::read_to_string(
            fixture("rules_project")
                .join("target")
                .join("manifest.json"),
        )
        .expect("should read fixture")
    }

    /// Acceptance criterion 1 & 2: with no `--state`, inside a git repo
    /// with a real merge-base, `zhao check` resolves and compiles that
    /// commit as the Baseline, and the resulting output matches what an
    /// equivalent `--state <manifest>` run produces for the same diff --
    /// this is the same fixture pair `type_widening_does_not_fire_while_join_loosening_does`
    /// uses via `--state`, so the two tests' assertions being identical
    /// *is* the equivalence proof.
    #[test]
    fn resolves_and_compiles_the_merge_base_commit_as_the_baseline() {
        let stub_dir = stub_dbt_dir();
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");

        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1, got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );

        let parsed: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
        let findings = parsed["findings"]
            .as_array()
            .expect("findings should be an array");

        assert_eq!(
            findings.len(),
            1,
            "expected only the join-loosening finding, got: {findings:#?}"
        );
        assert_eq!(findings[0]["rule"], "join-cardinality-loosened");
        assert_eq!(findings[0]["from_kind"], "inner");
        assert_eq!(findings[0]["to_kind"], "left");
        assert!(
            !findings.iter().any(|f| f["rule"] == "column-type-narrowed"),
            "a type widening (int -> bigint) must not fire column-type-narrowed"
        );
    }

    /// A `dbt` stub that honors `--target-path <dir>` (or defaults to
    /// `target`) the same way real `dbt compile` does -- unlike
    /// `stub_dbt_dir`, which always writes to the literal `target/`
    /// regardless of any passthrough args.
    fn target_path_aware_stub_dbt_dir() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().join("dbt");
        std::fs::write(
            &path,
            "#!/bin/sh\n\
             target_dir=target\n\
             prev=\"\"\n\
             for arg in \"$@\"; do\n\
             \x20\x20if [ \"$prev\" = \"--target-path\" ]; then target_dir=\"$arg\"; fi\n\
             \x20\x20prev=\"$arg\"\n\
             done\n\
             if [ \"$1\" = \"compile\" ]; then\n\
             \x20\x20mkdir -p \"$target_dir\"\n\
             \x20\x20cp dbt_manifest_source.json \"$target_dir/manifest.json\"\n\
             fi\n",
        )
        .expect("should write stub dbt script");
        let mut perms = std::fs::metadata(&path)
            .expect("should stat stub script")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("should chmod stub script");
        // A brief pause: writing then immediately exec'ing a fresh script
        // can spuriously hit `ETXTBSY` on CI's overlayfs -- see the
        // detailed comment on zhao-core's own `stub_dbt_command`.
        std::thread::sleep(std::time::Duration::from_millis(50));
        dir
    }

    /// The bug a `zhao-vscode-ext` diff-highlight refresh would hit
    /// otherwise: `--dbt-args "--target-path <dir>"` isolates the
    /// *current* manifest read (see `crate::dbt_target::resolve_target_dir`,
    /// used by `engine.rs`), but the exact same passthrough args also
    /// reach the Baseline's own worktree compile -- so the override must
    /// redirect *that* compile's manifest read too, or Baseline
    /// resolution fails with a spurious "manifest not found" even though
    /// the compile itself actually succeeded, just not where the read
    /// was still looking.
    #[test]
    fn a_target_path_override_isolates_the_baseline_compile_too_and_is_read_back_from_there() {
        let stub_dir = target_path_aware_stub_dbt_dir();
        let repo = new_test_repo();
        repo.write("dbt_manifest_source.json", &rules_baseline_manifest_json());
        repo.commit("baseline state");
        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of master");

        // The *current* side, isolated the same way `zhao lineage
        // --compile` would have already isolated it -- written directly
        // here (matching `repo_with_baseline_and_current`'s convention)
        // since this test is about Baseline resolution, not re-proving
        // the current-side fix issue #68 already covers.
        let current_target_path = tempfile::tempdir().expect("should create temp dir");
        std::fs::write(
            current_target_path.path().join("manifest.json"),
            rules_project_current_manifest_json(),
        )
        .expect("should write current manifest");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--format")
            .arg("json")
            .arg("--dbt-arg")
            .arg("--target-path")
            .arg("--dbt-arg")
            .arg(current_target_path.path())
            .output()
            .expect("command should run");

        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1 (Baseline resolution should succeed), got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
        let parsed: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
        assert_eq!(
            parsed["findings"]
                .as_array()
                .expect("findings should be an array")
                .len(),
            1,
            "expected the same single finding resolves_and_compiles_the_merge_base_commit_as_the_baseline asserts: {parsed:#?}"
        );

        assert!(
            !repo.path.join("target").join("manifest.json").exists(),
            "the project's real target/manifest.json should never be written"
        );
    }

    /// Same shape as `repo_with_baseline_and_current`, but the default
    /// branch is named `main` (not `master`) -- since zhao's own
    /// hardcoded default is `"master"`, a merge-base resolution that
    /// only succeeds against `main` can only be working because
    /// `zhao.yml`'s `against` (or an explicit `--against`) was actually
    /// read, not because it happened to coincide with the built-in
    /// default.
    fn repo_with_main_branch_and_current(
        baseline_manifest: &str,
        current_manifest: &str,
    ) -> TestRepo {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().to_path_buf();
        let repo = TestRepo { _dir: dir, path };
        repo.git(&["init", "--initial-branch=main"]);
        repo.git(&["config", "user.email", "test@zhao.invalid"]);
        repo.git(&["config", "user.name", "zhao test"]);

        // See `new_test_repo`'s identical write for why.
        repo.write("dbt_project.yml", "name: fixture\nversion: '1.0.0'\n");
        repo.write("dbt_manifest_source.json", baseline_manifest);
        repo.commit("baseline state");

        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of main");

        repo.write("target/manifest.json", current_manifest);
        repo
    }

    /// Acceptance criterion: `zhao.yml`'s `against` is honored for
    /// git-native Baseline resolution when no `--against` flag is given.
    #[test]
    fn zhao_yml_against_is_honored_with_no_cli_flag() {
        let stub_dir = stub_dbt_dir();
        let repo = repo_with_main_branch_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );
        repo.write("zhao.yml", "against: main\n");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");

        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1 (a real merge-base was found and diffed), got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// Acceptance criterion: an explicit `--against` flag overrides a
    /// conflicting `zhao.yml` value.
    #[test]
    fn cli_against_flag_overrides_a_conflicting_zhao_yml_value() {
        let stub_dir = stub_dbt_dir();
        let repo = repo_with_main_branch_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );
        // A deliberately wrong zhao.yml value -- the CLI flag should win,
        // not this.
        repo.write("zhao.yml", "against: does-not-exist\n");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--against")
            .arg("main")
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");

        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1 (--against main should win over zhao.yml's bogus value), got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// After a git-native Baseline resolution, the Baseline's compiled
    /// manifest is captured to `target/zhao/baseline_manifest.json` in
    /// the *current* project directory (not the temporary worktree,
    /// which has already been deleted by the time this file is checked).
    #[test]
    fn captures_the_baseline_manifest_after_git_native_resolution() {
        let stub_dir = stub_dbt_dir();
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");
        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1, got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );

        let captured_path = repo.path.join("target/zhao/baseline_manifest.json");
        assert!(
            captured_path.exists(),
            "expected {} to exist after a git-native Baseline run",
            captured_path.display()
        );
        let captured =
            std::fs::read_to_string(&captured_path).expect("should read captured manifest");
        assert_eq!(
            captured,
            rules_baseline_manifest_json(),
            "the captured file should match exactly what the Baseline actually compiled to"
        );
    }

    /// `--state <path>` never compiles anything, so there's nothing to
    /// capture -- no `baseline_manifest.json` should be written.
    #[test]
    fn state_flag_does_not_write_a_baseline_manifest_capture() {
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--state")
            .arg(fixture("diff_baseline_manifest.json"))
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");
        assert!(
            output.status.success() || output.status.code() == Some(1),
            "expected exit 0 or 1, got {:?}; stderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );

        let captured_path = repo.path.join("target/zhao/baseline_manifest.json");
        assert!(
            !captured_path.exists(),
            "a --state run should never write baseline_manifest.json (nothing was compiled)"
        );
    }

    /// Acceptance criterion 3: a clear, actionable error (exit 2) when
    /// `dbt` isn't invokable. `PATH` is overridden to a directory holding
    /// only a `git` symlink -- deterministic regardless of whether a real
    /// `dbt` happens to be installed on the machine running this test.
    #[test]
    fn produces_a_clear_error_when_dbt_is_not_invokable() {
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        let git_path = String::from_utf8(
            StdCommand::new("sh")
                .arg("-c")
                .arg("command -v git")
                .output()
                .expect("should locate git")
                .stdout,
        )
        .expect("git path should be utf8")
        .trim()
        .to_string();
        let git_only_dir = tempfile::tempdir().expect("should create temp dir");
        std::os::unix::fs::symlink(&git_path, git_only_dir.path().join("git"))
            .expect("should symlink git");

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", git_only_dir.path())
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .assert()
            .code(2)
            .stderr(predicate::str::contains("dbt").and(predicate::str::contains("PATH")));
    }

    /// Acceptance criterion 4: a clear, actionable error (exit 2) when a
    /// merge-base can't be determined -- here, because `--against` names a
    /// ref that doesn't exist at all.
    #[test]
    fn produces_a_clear_error_when_a_merge_base_cannot_be_determined() {
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--against")
            .arg("this-branch-does-not-exist")
            .assert()
            .code(2)
            .stderr(predicate::str::contains("merge-base"));
    }

    /// Acceptance criterion 1 (issue #26): `dbt deps` runs, before `dbt
    /// compile`, whenever the merge-base commit's project directory has a
    /// `packages.yml`.
    #[test]
    fn dbt_deps_runs_before_compile_when_packages_yml_is_present_at_the_baseline() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = new_test_repo();
        repo.write("packages.yml", "packages: []\n");
        repo.write("dbt_manifest_source.json", &rules_baseline_manifest_json());
        repo.commit("baseline state, with packages.yml");
        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of master");
        repo.write(
            "target/manifest.json",
            &rules_project_current_manifest_json(),
        );

        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .output()
            .expect("command should run");
        assert!(
            output.status.code() == Some(0) || output.status.code() == Some(1),
            "zhao itself should run to completion: {output:?}"
        );

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        let subcommands: Vec<&str> = log
            .lines()
            .map(|line| line.split(' ').next().unwrap_or(""))
            .collect();
        assert_eq!(
            subcommands,
            // `--version` is the compile step's own Fusion-vs-core probe
            // (see `command_reports_dbt_fusion`) -- unrelated to deps/
            // compile ordering, but it does precede the real compile call.
            vec!["deps", "--version", "compile"],
            "dbt deps should run, before dbt compile, when packages.yml is present: {log}"
        );
    }

    /// Acceptance criterion 2 (issue #26): no `packages.yml` at the
    /// merge-base commit means `dbt deps` never runs at all.
    #[test]
    fn dbt_deps_is_skipped_entirely_when_no_packages_yml_exists() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );
        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .output()
            .expect("command should run");
        assert!(
            output.status.code() == Some(0) || output.status.code() == Some(1),
            "zhao itself should run to completion: {output:?}"
        );

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        let subcommands: Vec<&str> = log
            .lines()
            .map(|line| line.split(' ').next().unwrap_or(""))
            .collect();
        assert_eq!(
            subcommands,
            // `--version` is the compile step's own Fusion-vs-core probe
            // (see `command_reports_dbt_fusion`), not a `deps` call.
            vec!["--version", "compile"],
            "dbt deps should not run at all when no packages.yml exists: {log}"
        );
    }

    /// Acceptance criterion 1 (issue #26), `dependencies.yml` variant: the
    /// same trigger condition, but via the other filename `resolve()`
    /// checks for.
    #[test]
    fn dbt_deps_runs_before_compile_when_dependencies_yml_is_present_at_the_baseline() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = new_test_repo();
        repo.write("dependencies.yml", "packages: []\n");
        repo.write("dbt_manifest_source.json", &rules_baseline_manifest_json());
        repo.commit("baseline state, with dependencies.yml");
        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of master");
        repo.write(
            "target/manifest.json",
            &rules_project_current_manifest_json(),
        );

        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .output()
            .expect("command should run");
        assert!(
            output.status.code() == Some(0) || output.status.code() == Some(1),
            "zhao itself should run to completion: {output:?}"
        );

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        let subcommands: Vec<&str> = log
            .lines()
            .map(|line| line.split(' ').next().unwrap_or(""))
            .collect();
        assert_eq!(
            subcommands,
            // `--version` is the compile step's own Fusion-vs-core probe
            // (see `command_reports_dbt_fusion`) -- unrelated to deps/
            // compile ordering, but it does precede the real compile call.
            vec!["deps", "--version", "compile"],
            "dbt deps should run, before dbt compile, when dependencies.yml is present: {log}"
        );
    }

    /// Acceptance criteria 1 & 3 (issue #26) together: `--dbt-arg` values
    /// reach `dbt deps` too, not just `dbt compile` -- exercised with
    /// `packages.yml` present so `deps` actually runs.
    #[test]
    fn dbt_arg_values_are_appended_to_both_deps_and_compile_invocations() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = new_test_repo();
        repo.write("packages.yml", "packages: []\n");
        repo.write("dbt_manifest_source.json", &rules_baseline_manifest_json());
        repo.commit("baseline state, with packages.yml");
        repo.git(&["checkout", "-b", "feature"]);
        repo.write("README.md", "an unrelated change on the feature branch\n");
        repo.commit("feature work, ahead of master");
        repo.write(
            "target/manifest.json",
            &rules_project_current_manifest_json(),
        );

        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--dbt-arg")
            .arg("--target=ci")
            .assert()
            .code(predicate::in_iter([0, 1]));

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        assert_eq!(
            log.lines().collect::<Vec<_>>(),
            // `--version` (the compile step's own Fusion-vs-core probe --
            // called with no extra args at all, see
            // `command_reports_dbt_fusion`) precedes the real compile
            // invocation; `deps` never gets it, since `deps()` never calls
            // `with_fusion_index_flags`.
            vec!["deps --target=ci", "--version", "compile --target=ci"],
            "--dbt-arg values should be appended to both the deps and compile invocations: {log}"
        );
    }

    /// Acceptance criterion 3 (issue #26): repeated `--dbt-arg` values are
    /// appended, in order, to the `dbt compile` invocation (and would be to
    /// `dbt deps` too, were it running -- there's no `packages.yml` here,
    /// so it isn't, matching `dbt_deps_is_skipped_entirely_when_no_packages_yml_exists`
    /// above).
    #[test]
    fn dbt_arg_values_are_appended_in_order_to_the_compile_invocation() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );
        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--dbt-arg")
            .arg("--target=ci")
            .arg("--dbt-arg")
            .arg("--vars={\"foo\": \"bar\"}")
            .assert()
            .code(predicate::in_iter([0, 1]));

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        assert_eq!(
            log.lines().collect::<Vec<_>>(),
            // `--version` (the compile step's own Fusion-vs-core probe,
            // unrelated to --dbt-arg -- see `command_reports_dbt_fusion`)
            // precedes the real compile invocation.
            vec!["--version", "compile --target=ci --vars={\"foo\": \"bar\"}"],
            "both --dbt-arg values should be appended, in order, to the compile invocation: {log}"
        );
    }

    /// Acceptance criterion 4 (issue #26): `--dbt-args` produces the
    /// identical result via `shell-words` splitting -- proving the quoted
    /// `--vars` value survives as one argument, not split on its internal
    /// whitespace.
    #[test]
    fn dbt_args_shell_splits_into_the_identical_result_as_dbt_arg() {
        let log_dir = tempfile::tempdir().expect("should create temp dir");
        let invocation_log = log_dir.path().join("invocations.log");

        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );
        let stub_dir = logging_stub_dbt_dir(&invocation_log);

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .env("PATH", path_with_stub_dbt_prepended(&stub_dir))
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--dbt-args")
            .arg("--target ci --vars '{\"foo\": \"bar\"}'")
            .assert()
            .code(predicate::in_iter([0, 1]));

        let log = std::fs::read_to_string(&invocation_log).expect("should read invocation log");
        assert_eq!(
            log.lines().collect::<Vec<_>>(),
            // `--version` (the compile step's own Fusion-vs-core probe,
            // unrelated to --dbt-args) precedes the real compile invocation.
            vec!["--version", "compile --target ci --vars {\"foo\": \"bar\"}"],
            "--dbt-args should shell-word-split into the same argument boundaries \
             --dbt-arg would have produced by hand: {log}"
        );
    }

    /// Acceptance criterion 5 (issue #26): using both `--dbt-arg` and
    /// `--dbt-args` together is a clap-level usage error (exit 2) --
    /// nothing runs at all, not even the merge-base resolution, let alone
    /// `dbt`.
    #[test]
    fn using_both_dbt_arg_and_dbt_args_together_is_a_clear_cli_error() {
        let repo = repo_with_baseline_and_current(
            &rules_baseline_manifest_json(),
            &rules_project_current_manifest_json(),
        );

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--dbt-arg")
            .arg("--target=ci")
            .arg("--dbt-args")
            .arg("--target ci")
            .assert()
            .code(2)
            .stderr(predicate::str::contains("cannot be used with"));
    }
}

// ---------------------------------------------------------------------
// Staleness warning: a non-blocking notice when the target branch has
// moved on since the Baseline's merge-base. Exercised via `--state` (not
// git-native Baseline resolution) so these tests only need a real git
// repo, not a `dbt` install of any kind -- staleness is orthogonal to how
// the Baseline itself was resolved.
// ---------------------------------------------------------------------

#[cfg(unix)]
mod staleness_warning {
    use super::*;
    use std::process::Command as StdCommand;

    struct TestRepo {
        _dir: tempfile::TempDir,
        path: std::path::PathBuf,
    }

    impl TestRepo {
        fn git(&self, args: &[&str]) {
            let output = StdCommand::new("git")
                .current_dir(&self.path)
                .args(args)
                .output()
                .expect("git should be runnable in tests");
            assert!(
                output.status.success(),
                "git {args:?} should succeed: {output:?}"
            );
        }

        fn commit(&self, relative_path: &str, contents: &str, message: &str) {
            std::fs::write(self.path.join(relative_path), contents).expect("should write file");
            self.git(&["add", "."]);
            self.git(&["commit", "-m", message]);
        }
    }

    /// A repo with one commit on `master`, and a `feature` branch (left
    /// checked out) one commit ahead -- not yet stale, since `master`
    /// hasn't moved since `feature` diverged from it.
    fn up_to_date_repo() -> TestRepo {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().to_path_buf();
        let repo = TestRepo { _dir: dir, path };

        repo.git(&["init", "--initial-branch=master"]);
        repo.git(&["config", "user.email", "test@zhao.invalid"]);
        repo.git(&["config", "user.name", "zhao test"]);
        // Ignored up front so a later `git add .` (e.g. when committing on
        // `master` in `stale_repo`) never accidentally sweeps up the
        // untracked `target/manifest.json` written below -- a real dbt
        // project gitignores `target/` for the same reason.
        repo.commit(".gitignore", "target/\n", "ignore target/");
        // The marker adapter auto-detection looks for -- committed ahead
        // of `target/manifest.json` (copied in below, untracked). Its
        // mtime is then pinned to the Unix epoch, same as
        // `write_dbt_project_marker`: `std::fs::copy` below can preserve
        // the *source* fixture's own original mtime on some platforms
        // (e.g. an APFS `clonefile` copy) rather than stamping "now", so
        // committing it first isn't reliably enough on its own to
        // guarantee it looks older than the copied-in manifest.
        repo.commit(
            "dbt_project.yml",
            "name: fixture\nversion: '1.0.0'\n",
            "add dbt_project.yml",
        );
        std::fs::File::options()
            .write(true)
            .open(repo.path.join("dbt_project.yml"))
            .expect("should reopen dbt_project.yml")
            .set_modified(std::time::SystemTime::UNIX_EPOCH)
            .expect("should set an old mtime on dbt_project.yml");
        repo.commit("README.md", "on master\n", "on master");
        repo.git(&["checkout", "-b", "feature"]);
        repo.commit("README.md", "on feature\n", "feature work, ahead of master");

        std::fs::create_dir_all(repo.path.join("target")).expect("should create target dir");
        std::fs::copy(
            fixture("clean_project")
                .join("target")
                .join("manifest.json"),
            repo.path.join("target").join("manifest.json"),
        )
        .expect("should copy fixture manifest");

        repo
    }

    /// Same as [`up_to_date_repo`], but with an extra commit landed on
    /// `master` after `feature` branched off -- `feature`'s merge-base
    /// with `master` is now behind `master`'s tip, i.e. stale.
    fn stale_repo() -> TestRepo {
        let repo = up_to_date_repo();
        repo.git(&["checkout", "master"]);
        repo.commit(
            "README.md",
            "on master, updated after feature branched off\n",
            "a new commit landed on master after feature branched off",
        );
        repo.git(&["checkout", "feature"]);
        repo
    }

    fn check_command(repo: &TestRepo) -> Command {
        let mut cmd = Command::cargo_bin("zhao").expect("binary should build");
        cmd.arg("check")
            .arg("--state")
            .arg(fixture("diff_baseline_manifest_clean.json"))
            .arg("--project-dir")
            .arg(&repo.path)
            // Determinism: without this, whether the report's text output
            // contains ANSI color codes would depend on the environment
            // these tests happen to run in (e.g. GitHub Actions, which
            // zhao-cli's own CI runs on, enables color even though stdout
            // isn't a real TTY there).
            .arg("--no-color");
        cmd
    }

    /// Acceptance criterion 1: a branch whose merge-base matches the
    /// target branch's current tip produces no staleness warning, in
    /// either output format.
    #[test]
    fn no_warning_when_the_merge_base_matches_the_target_branchs_tip() {
        let repo = up_to_date_repo();

        check_command(&repo)
            .arg("--format")
            .arg("json")
            .assert()
            .code(0)
            .stdout(predicate::str::contains("staleness_warning").not());

        check_command(&repo)
            .assert()
            .code(0)
            .stdout(predicate::str::contains("warning:").not());
    }

    /// Acceptance criterion 2: a branch whose merge-base is behind the
    /// target branch's current tip produces the warning, in both JSON and
    /// human-readable output.
    #[test]
    fn warns_when_the_merge_base_is_behind_the_target_branchs_tip() {
        let repo = stale_repo();

        check_command(&repo)
            .arg("--format")
            .arg("json")
            .assert()
            .code(0)
            .stdout(predicate::str::contains(
                "\"staleness_warning\": \"analysis may be stale, consider rebasing\"",
            ));

        check_command(&repo)
            .assert()
            .code(0)
            .stdout(predicate::str::contains(
                "warning: analysis may be stale, consider rebasing",
            ));
    }

    /// Acceptance criterion 3: the staleness warning never changes the
    /// exit code -- exercised with a fixture pair that has a *real*
    /// breaking Change (`join-cardinality-loosened`, `warn` by default but
    /// escalated to `error` under a `strict` Preset), so this test proves
    /// the exit code still tracks that finding's severity, staleness
    /// warning notwithstanding, rather than merely observing "nothing
    /// changed, so of course the exit code stayed 0" (which a fixture pair
    /// with zero Changes -- as used by the other two tests in this module
    /// -- would prove regardless of whether this feature worked at all).
    #[test]
    fn the_warning_never_changes_the_exit_code_even_under_a_strict_preset() {
        let repo = stale_repo();
        std::fs::create_dir_all(repo.path.join("target")).expect("should create target dir");
        std::fs::copy(
            fixture("rules_project")
                .join("target")
                .join("manifest.json"),
            repo.path.join("target").join("manifest.json"),
        )
        .expect("should overwrite with a fixture that has a real breaking change");
        std::fs::write(repo.path.join("zhao.yml"), "preset: strict\n")
            .expect("should write zhao.yml");

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--state")
            .arg(fixture("rules_baseline_manifest.json"))
            .arg("--project-dir")
            .arg(&repo.path)
            .arg("--format")
            .arg("json")
            .output()
            .expect("command should run");

        assert_eq!(
            output.status.code(),
            Some(1),
            "join-cardinality-loosened should be escalated to error by the strict Preset, \
             regardless of the simultaneous staleness warning; stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let parsed: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
        assert_eq!(
            parsed["staleness_warning"], "analysis may be stale, consider rebasing",
            "the staleness warning should still be present alongside the breaking finding"
        );
        assert_eq!(
            parsed["findings"][0]["rule"], "join-cardinality-loosened",
            "the exit code should come from this finding's severity, not the staleness warning"
        );
        assert_eq!(parsed["findings"][0]["severity"], "error");
    }
}

/// Integration coverage for the current-manifest freshness check (engine.rs
/// `check_current_manifest_freshness`): a real dbt project directory, not
/// just a manifest-only fixture, since the check is a no-op without dbt
/// source files present to compare against.
mod stale_current_manifest {
    use super::*;

    /// A tempdir shaped like a minimal real dbt project: `target/manifest.json`
    /// copied from the `clean_project` fixture, plus a `dbt_project.yml` whose
    /// mtime is controlled independently -- so staleness can be deliberately
    /// induced or avoided without depending on git checkout mtime ordering.
    struct TestProject {
        _dir: tempfile::TempDir,
        path: std::path::PathBuf,
    }

    fn set_mtime(path: &std::path::Path, seconds_since_epoch: u64) {
        let time =
            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds_since_epoch);
        std::fs::File::options()
            .write(true)
            .open(path)
            .expect("file should be openable for writing")
            .set_modified(time)
            .expect("mtime should be settable");
    }

    fn project_with_dbt_project_yml_mtime(
        manifest_seconds: u64,
        dbt_project_seconds: u64,
    ) -> TestProject {
        let dir = tempfile::tempdir().expect("should create temp dir");
        let path = dir.path().to_path_buf();

        std::fs::create_dir_all(path.join("target")).expect("should create target dir");
        std::fs::copy(
            fixture("clean_project")
                .join("target")
                .join("manifest.json"),
            path.join("target").join("manifest.json"),
        )
        .expect("should copy fixture manifest");
        set_mtime(&path.join("target").join("manifest.json"), manifest_seconds);

        std::fs::write(
            path.join("dbt_project.yml"),
            "name: fixture\nversion: '1.0.0'\n",
        )
        .expect("should write dbt_project.yml");
        set_mtime(&path.join("dbt_project.yml"), dbt_project_seconds);

        TestProject { _dir: dir, path }
    }

    #[test]
    fn a_stale_manifest_fails_with_a_clear_error_by_default() {
        // dbt_project.yml modified after the manifest was compiled --
        // exactly the "checked out a different branch, forgot to
        // recompile" bug pattern.
        let project = project_with_dbt_project_yml_mtime(1_000, 2_000);

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--state")
            .arg(fixture("diff_baseline_manifest_clean.json"))
            .arg("--project-dir")
            .arg(&project.path)
            .output()
            .expect("command should run");

        assert_eq!(output.status.code(), Some(2));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("looks stale"), "{stderr}");
        assert!(stderr.contains("dbt compile"), "{stderr}");
        assert!(stderr.contains("--allow-stale-manifest"), "{stderr}");
    }

    #[test]
    fn a_fresh_manifest_is_not_flagged() {
        // Manifest compiled after dbt_project.yml's last change -- the
        // normal, healthy case.
        let project = project_with_dbt_project_yml_mtime(2_000, 1_000);

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--state")
            .arg(fixture("diff_baseline_manifest_clean.json"))
            .arg("--project-dir")
            .arg(&project.path)
            .arg("--format")
            .arg("json")
            .assert()
            .code(0)
            .stdout(predicate::str::contains("\"findings\": []"));
    }

    #[test]
    fn allow_stale_manifest_bypasses_the_check() {
        let project = project_with_dbt_project_yml_mtime(1_000, 2_000);

        Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("check")
            .arg("--state")
            .arg(fixture("diff_baseline_manifest_clean.json"))
            .arg("--project-dir")
            .arg(&project.path)
            .arg("--allow-stale-manifest")
            .arg("--format")
            .arg("json")
            .assert()
            .code(0)
            .stdout(predicate::str::contains("\"findings\": []"));
    }

    #[test]
    fn zhao_diff_is_also_gated_by_the_same_check() {
        let project = project_with_dbt_project_yml_mtime(1_000, 2_000);

        let output = Command::cargo_bin("zhao")
            .expect("binary should build")
            .arg("diff")
            .arg("--state")
            .arg(fixture("diff_baseline_manifest_clean.json"))
            .arg("--project-dir")
            .arg(&project.path)
            .output()
            .expect("command should run");

        assert_eq!(
            output.status.code(),
            Some(2),
            "zhao diff shares engine.rs::build_report with zhao check, so it must be gated too"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("looks stale"), "{stderr}");
    }
}