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
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
//! Rendering a `zhao check` run's results as JSON or brief text.
//!
//! zhao-core's own types ([`zhao_core::diff::Change`],
//! [`zhao_core::rules::Finding`]) intentionally carry no serialization
//! derives -- they're the engine's internal vocabulary, not a wire format
//! commitment. This module owns the JSON shape as its own, separate
//! concern, converting from the engine's types rather than exposing them
//! directly.

use serde::Serialize;
use zhao_core::adapters::AdapterVocabulary;
use zhao_core::diff::Change;
use zhao_core::model::{JoinKind, Materialization, NodeId, ParsedProject, Upstream};
use zhao_core::rules::{Finding, FindingDetail, Severity};

/// The message included in a [`Report`] when the Baseline's merge-base has
/// fallen behind the target branch's current tip.
pub const STALENESS_WARNING: &str = "analysis may be stale, consider rebasing";

/// The full JSON payload for a `zhao check` run.
#[derive(Debug, Serialize)]
pub struct Report {
    /// Every Change detected between the Baseline and the current state.
    pub changes: Vec<ChangeJson>,
    /// Every Rule that fired against those Changes.
    pub findings: Vec<FindingJson>,
    /// Present when the target branch has moved on since the Baseline's
    /// merge-base, so this run's analysis may not reflect the target
    /// branch's latest state. Purely informational: never affects
    /// [`Report::is_breaking`] or the process exit code, regardless of
    /// Preset.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub staleness_warning: Option<String>,
    /// Exactly which Nodes named in `findings`' Downstream impact need
    /// validating, in the adapter's own display names (e.g. dbt's bare
    /// model name). Always present, `[]` when there's nothing to
    /// validate (either no impactful non-`pass`-severity Finding fired at
    /// all, or this report was built without
    /// [`Report::with_impacted_models`]).
    pub impacted_models: Vec<String>,
    /// The computed `--defer` plan: which Nodes need building (the same
    /// set `impacted_models` names) and which of their upstream
    /// dependencies can be deferred to an existing state instead. `None`
    /// under the same conditions as an empty `impacted_models`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub defer_plan: Option<DeferPlanJson>,
    /// A ready-to-run command to rebuild exactly `impacted_models` --
    /// see [`Report::with_recommended_command`]. `None` unless
    /// `zhao.yml`'s `recommended-command.subcommand` is set: zhao has no
    /// way to know whether a project's workflow wants `dbt run`, `dbt
    /// build`, or something else, so it never assumes one (the same
    /// "never assumes" reasoning `defer_plan.state` documents for
    /// `--defer`) -- also `None` when `impacted_models` is empty, same
    /// as `defer_plan`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recommended_command: Option<String>,
    /// One entry per schema-changing Change (column added/removed/type
    /// changed -- never a join change, which isn't a schema change) on a
    /// Node materialized `incremental`. Phrased as a conditional
    /// possibility, never a fact: zhao has no live connection and cannot
    /// know whether the Node actually exists yet in any given target
    /// environment. Always serialized, even as `[]` -- unlike
    /// `defer_plan` (only ever computed on request, using `Option` to
    /// distinguish "not computed" from "computed, found nothing"), this
    /// is unconditionally computed whenever a `ParsedProject` is
    /// available, so there's no "not computed" state for a consumer to
    /// need to distinguish in the first place.
    pub schema_evolution_warnings: Vec<SchemaEvolutionWarningJson>,
}

impl Report {
    /// Builds a [`Report`] from the engine's own `Change`/`Finding` output.
    /// No staleness warning, impacted-models list, or defer plan is set --
    /// chain [`Report::with_staleness_warning`]/
    /// [`Report::with_impacted_models`]/[`Report::with_defer_plan`] to
    /// add them.
    pub fn new(changes: &[Change], findings: &[Finding]) -> Self {
        Self {
            changes: changes.iter().map(ChangeJson::from).collect(),
            findings: findings.iter().map(FindingJson::from).collect(),
            staleness_warning: None,
            impacted_models: Vec::new(),
            defer_plan: None,
            recommended_command: None,
            schema_evolution_warnings: Vec::new(),
        }
    }

    /// The exact set of Nodes to rebuild for this change: every changed Node
    /// (a Node whose own definition was edited has to be rebuilt whatever its
    /// Findings say), followed by the Nodes named in the Downstream impact
    /// section -- every non-`pass` Finding's [`FindingJson::impacted_node`] --
    /// deduplicated, in first-seen order. Shared by
    /// [`Report::with_impacted_models`] and [`Report::with_defer_plan`],
    /// which both need precisely this set: the former to name it in the
    /// adapter's own display names, the latter as the `--defer` plan's
    /// "build" set.
    fn impacted_node_ids(&self) -> Vec<String> {
        let mut seen = std::collections::HashSet::new();
        let mut node_ids = Vec::new();
        // Every changed Node comes first: its own definition was edited, so it
        // has to be rebuilt no matter what the Rules made of the change.
        for change in &self.changes {
            let node_id = change.node().to_string();
            if seen.insert(node_id.clone()) {
                node_ids.push(node_id);
            }
        }
        for finding in &self.findings {
            if finding.severity() == SeverityJson::Pass {
                continue;
            }
            let node_id = finding.impacted_node().to_string();
            if seen.insert(node_id.clone()) {
                node_ids.push(node_id);
            }
        }
        node_ids
    }

    /// Sets this report's staleness warning: `Some(`[`STALENESS_WARNING`]`)`
    /// if the Baseline's merge-base is behind the target branch's current
    /// tip, `None` otherwise (including when that couldn't be determined
    /// at all, e.g. outside a git repository -- staleness is purely
    /// best-effort and informational, never a hard requirement).
    pub fn with_staleness_warning(mut self, is_stale: bool) -> Self {
        self.staleness_warning = is_stale.then(|| STALENESS_WARNING.to_string());
        self
    }

    /// Sets this report's impacted-models list: the exact set of Nodes
    /// named in the Downstream impact section (every non-`pass` Finding's
    /// [`FindingJson::impacted_node`], deduplicated), rendered through
    /// `vocabulary` into the adapter's own display names -- e.g. dbt's
    /// bare model name, not zhao's internal `NodeId` string.
    ///
    /// Deliberately does *not* look a Node up by ID first (an earlier
    /// version of this method did, resolving each ID against a
    /// `ParsedProject`): an impacted Node reached only via the Baseline
    /// (e.g. one deleted entirely in the current state, for
    /// `ColumnRemovedWithActiveReferences`) may have no corresponding
    /// `Node` in the current state to look up at all, even though it's
    /// still correctly named in the Downstream impact section from its ID
    /// string alone -- looking it up first would silently drop it from
    /// this list, undermining the "matches Downstream impact exactly"
    /// contract. `vocabulary` is expected to derive its own name straight
    /// from the ID string instead (e.g. dbt's `unique_id` shape already
    /// contains the bare model name).
    pub fn with_impacted_models(mut self, vocabulary: &dyn AdapterVocabulary) -> Self {
        self.impacted_models = self
            .impacted_node_ids()
            .iter()
            .map(|id| vocabulary.node_display_name(id))
            .collect();
        self
    }

    /// Sets this report's `--defer` plan: `build` is the same impacted-Node
    /// set [`Report::with_impacted_models`] names; `defer` is every
    /// Node those Nodes depend on (directly or transitively, through
    /// `current`'s Lineage Edges) that isn't itself in `build` -- Nodes a
    /// CI job building only the impacted set should treat as already
    /// available (via a `--defer`-style flag, in whatever build tool
    /// actually runs this) rather than rebuild from scratch. Pure
    /// computation: this method never connects to a warehouse or
    /// provisions anything.
    ///
    /// `settings` (from `zhao.yml`'s `defer.target`/`defer.state`, with
    /// any `--defer-target`/`--defer-state` CLI override already applied
    /// by the caller) additionally surfaces the configured state path on
    /// the plan -- see [`DeferSettings`]/[`DeferPlanJson::state`]. Pass
    /// [`DeferSettings::default`] when neither is configured; the plan's
    /// `build`/`defer` lists are computed the same either way.
    ///
    /// `None` when nothing is impacted at all (nothing to build, so no
    /// plan makes sense); `Some` with an empty `defer` list is meaningful
    /// otherwise -- it means every dependency of the build set is an
    /// Origin, not a Node, so there's genuinely nothing to defer.
    pub fn with_defer_plan(
        mut self,
        current: &ParsedProject,
        vocabulary: &dyn AdapterVocabulary,
        settings: &DeferSettings,
    ) -> Self {
        let build = self.impacted_node_ids();
        self.defer_plan = if build.is_empty() {
            None
        } else {
            Some(DeferPlanJson::compute(current, build, vocabulary, settings))
        };
        self
    }

    /// Sets this report's recommended command: `<dbt_command> <subcommand>
    /// --select <impacted_models...>`, optionally followed by `--target
    /// <target_label>` -- a single, ready-to-run command that rebuilds
    /// exactly the impacted-Node set `with_impacted_models` computed,
    /// using the adapter's own display names the same way
    /// `impacted_models`/`defer_plan` already do.
    ///
    /// `subcommand` is `zhao.yml`'s `recommended-command.subcommand`
    /// (e.g. `"run"`, `"build"`, `"test"`) -- `None` (not configured)
    /// produces no recommended command at all, same "never assumes"
    /// reasoning as `--defer`. `dbt_command` is the already-resolved
    /// `dbt-command` wrapper (CLI override, else `zhao.yml`, else
    /// `"dbt"`) every other `dbt` invocation this run already uses.
    /// `target_label` is [`DeferSettings::target`] -- reusing the
    /// existing `defer.target`/`--defer-target` concept exactly as-is
    /// rather than introducing a second way to name a target, since a
    /// human-readable target label already means the same thing in both
    /// places: what environment this command's output should be
    /// compared/deployed against.
    ///
    /// `None` when `impacted_models` is empty, same as `defer_plan` --
    /// there's nothing to build, so no command makes sense.
    pub fn with_recommended_command(
        mut self,
        subcommand: Option<&str>,
        dbt_command: &str,
        target_label: Option<&str>,
    ) -> Self {
        self.recommended_command = match subcommand {
            Some(subcommand) if !self.impacted_models.is_empty() => {
                let mut command = format!(
                    "{dbt_command} {subcommand} --select {}",
                    self.impacted_models.join(" ")
                );
                if let Some(target) = target_label {
                    command.push_str(" --target ");
                    command.push_str(target);
                }
                Some(command)
            }
            _ => None,
        };
        self
    }

    /// Sets this report's schema-evolution warnings: one per
    /// schema-changing Change (column added/removed/type changed) whose
    /// Node is materialized `incremental` in `current`. A non-schema
    /// Change (a join change) or a Change on any other materialization
    /// never produces a warning here.
    ///
    /// `current.node(...)` returning `None` (the Change's Node has no
    /// corresponding `Node` in `current` at all) can't currently happen in
    /// practice -- every `Change` originates from `zhao_core::diff::diff`,
    /// which only ever emits one for a Node it found in `current` in the
    /// first place, and `current` here is always that same
    /// `ParsedProject`. Handled as a no-op skip via `?` anyway, purely as
    /// a defensive guard against that invariant changing later, not
    /// because it's a reachable case today.
    pub fn with_schema_evolution_warnings(mut self, current: &ParsedProject) -> Self {
        self.schema_evolution_warnings = self
            .changes
            .iter()
            .filter(|change| change.is_column_change())
            .filter_map(|change| {
                let node = current.node(&NodeId::new(change.node()))?;
                (node.materialization == Materialization::Incremental).then(|| {
                    SchemaEvolutionWarningJson {
                        node: change.node().to_string(),
                        message: format!(
                            "if this incrementally-materialized model already exists in your \
                             target environment, this change requires manual schema \
                             evolution: {}",
                            change.describe()
                        ),
                        change_description: change.describe(),
                    }
                })
            })
            .collect();
        self
    }

    /// Upgrades or drops each schema-evolution warning based on a live
    /// existence check, for `--check-relations` (opt-in, since it
    /// requires a real connection the offline default gate never needs):
    /// `check(node)` returning `Some(true)` rewords that warning from
    /// conditional ("if this model already exists...") to definitive
    /// (the model is confirmed to exist); `Some(false)` removes the
    /// warning entirely (confirmed not to exist, so there's nothing to
    /// flag); `None` (the check couldn't be performed at all -- an
    /// unsupported warehouse, or the check itself failed) leaves that
    /// warning's conditional wording untouched, the same as if
    /// `--check-relations` had never been passed.
    pub fn with_live_relation_checks(
        mut self,
        mut check: impl FnMut(&str) -> Option<bool>,
    ) -> Self {
        self.schema_evolution_warnings
            .retain_mut(|warning| match check(&warning.node) {
                Some(true) => {
                    warning.message = format!(
                        "this incrementally-materialized model exists in your target \
                         environment; this change requires manual schema evolution: {}",
                        warning.change_description
                    );
                    true
                }
                Some(false) => false,
                None => true,
            });
        self
    }

    /// Whether this run's Findings should fail the CI gate: any Finding
    /// at [`Severity::Error`]. A staleness warning never contributes here,
    /// under any Preset.
    pub fn is_breaking(&self) -> bool {
        self.findings
            .iter()
            .any(|f| f.severity() == SeverityJson::Error)
    }
}

/// The `--defer` target/state settings a [`Report::with_defer_plan`] call
/// needs to generate a ready-to-run command -- from `zhao.yml`'s
/// `defer.target`/`defer.state` (see `zhao_core::config::Config`), with
/// `--defer-target`/`--defer-state` CLI flags already resolved as
/// overrides by the caller. Both are optional and independent: `target`
/// alone (no `state`) produces a plan with no command, since dbt's
/// `--defer` mechanism has nothing to function without a state path;
/// `state` alone (no `target`) still produces a full command, just
/// without a human-readable label for what the state represents.
#[derive(Debug, Clone, Default)]
pub struct DeferSettings {
    /// A human-readable label for the dbt target the state was compiled
    /// from (e.g. `"prod"`) -- surfaced alongside the generated command,
    /// never passed to dbt as a `--target` flag.
    pub target: Option<String>,
    /// The path passed to `dbt ... --defer --state <path>`.
    pub state: Option<String>,
}

/// The computed dbt `--defer` plan for a run -- see
/// [`Report::with_defer_plan`].
#[derive(Debug, Serialize)]
pub struct DeferPlanJson {
    /// Nodes that need to be built: the same set named in Downstream
    /// impact / `impacted_models`.
    pub build: Vec<String>,
    /// Nodes `build`'s Nodes depend on (directly or transitively) that
    /// aren't themselves in `build` -- these should be deferred to an
    /// existing state (a `--defer`-style flag, in whatever build tool
    /// actually runs this) rather than rebuilt.
    pub defer: Vec<String>,
    /// The human-readable label for the target the plan defers to (from
    /// [`DeferSettings::target`]), if configured -- present independently
    /// of `state` (a target name alone, with no state path, still
    /// documents intent even though there's no path to defer to yet).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// The configured path to defer to (from `zhao.yml`'s `defer.state`
    /// or `--defer-state`), if any -- the raw path only, never a
    /// constructed command: zhao has no way to know whether a project's
    /// CI actually invokes `dbt build`, `dbt run`, or some custom
    /// wrapper, so it never assumes one. `None` when no state path is
    /// configured -- the plan's `build`/`defer` lists are still always
    /// present regardless, since they're useful on their own even
    /// without a state to defer to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
}

impl DeferPlanJson {
    /// Computes the plan: `build` is used as given (the caller already
    /// determined the impacted set); `defer` is `build`'s full transitive
    /// upstream Node closure (walking `current`'s Lineage Edges), minus
    /// `build` itself. Origins are never included -- dbt never builds a
    /// source in the first place, so there's nothing to defer for one.
    /// The graph walk itself works in zhao's own `NodeId` strings; both
    /// `build` and `defer` are rendered through `vocabulary` at the end,
    /// same as [`Report::with_impacted_models`], so a `--defer` plan
    /// names Nodes the same way `impacted_models` does rather than
    /// mixing zhao's internal IDs with the adapter's own names.
    fn compute(
        current: &ParsedProject,
        build: Vec<String>,
        vocabulary: &dyn AdapterVocabulary,
        settings: &DeferSettings,
    ) -> Self {
        let build_set: std::collections::HashSet<&str> = build.iter().map(String::as_str).collect();
        let mut visited: std::collections::HashSet<String> = build.iter().cloned().collect();
        let mut deferred = std::collections::BTreeSet::new();
        let mut frontier: Vec<NodeId> = build.iter().map(|id| NodeId::new(id.clone())).collect();

        while let Some(node_id) = frontier.pop() {
            for edge in &current.edges {
                if edge.downstream != node_id {
                    continue;
                }
                let Upstream::Node(upstream_id) = &edge.upstream else {
                    continue;
                };
                let upstream_id_string = upstream_id.to_string();
                if visited.insert(upstream_id_string.clone()) {
                    if !build_set.contains(upstream_id_string.as_str()) {
                        deferred.insert(upstream_id_string);
                    }
                    frontier.push(upstream_id.clone());
                }
            }
        }

        let build_names: Vec<String> = build
            .iter()
            .map(|id| vocabulary.node_display_name(id))
            .collect();
        let defer_names: Vec<String> = deferred
            .iter()
            .map(|id| vocabulary.node_display_name(id))
            .collect();

        Self {
            build: build_names,
            defer: defer_names,
            target: settings.target.clone(),
            state: settings.state.clone(),
        }
    }
}

/// A single conditional schema-evolution notice -- see
/// [`Report::with_schema_evolution_warnings`].
#[derive(Debug, Serialize)]
pub struct SchemaEvolutionWarningJson {
    /// The incrementally-materialized Node the schema-changing Change
    /// belongs to.
    pub node: String,
    /// The conditional warning text -- always phrased as a possibility
    /// ("if this model already exists..."), never asserts the model
    /// exists as fact.
    pub message: String,
    /// The underlying Change's own one-line description (e.g. `"+
    /// column added: new_col"`), kept alongside `message` so
    /// [`Report::with_live_relation_checks`] can rebuild a definitive
    /// message without re-deriving or text-parsing the conditional one.
    /// Never serialized -- an internal detail, not part of the JSON
    /// contract.
    #[serde(skip)]
    change_description: String,
}

/// A [`Change`], reshaped for JSON output.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ChangeJson {
    /// See [`Change::ColumnAdded`].
    ColumnAdded { node: String, column: String },
    /// See [`Change::ColumnRemoved`].
    ColumnRemoved { node: String, column: String },
    /// See [`Change::ColumnTypeChanged`].
    ColumnTypeChanged {
        node: String,
        column: String,
        from_type: String,
        to_type: String,
    },
    /// See [`Change::ColumnExpressionChanged`].
    ColumnExpressionChanged {
        node: String,
        column: String,
        from_expression: Option<String>,
        to_expression: Option<String>,
    },
    /// See [`Change::JoinChanged`].
    JoinChanged {
        node: String,
        position: usize,
        from_kind: Option<String>,
        to_kind: Option<String>,
    },
    /// See [`Change::StructFieldAdded`].
    StructFieldAdded {
        node: String,
        column: String,
        field: String,
    },
    /// See [`Change::StructFieldRemoved`].
    StructFieldRemoved {
        node: String,
        column: String,
        field: String,
    },
    /// See [`Change::StructFieldTypeChanged`].
    StructFieldTypeChanged {
        node: String,
        column: String,
        field: String,
        from_type: String,
        to_type: String,
    },
}

impl ChangeJson {
    /// The name of the Node this Change belongs to, regardless of variant.
    fn node(&self) -> &str {
        match self {
            ChangeJson::ColumnAdded { node, .. }
            | ChangeJson::ColumnRemoved { node, .. }
            | ChangeJson::ColumnTypeChanged { node, .. }
            | ChangeJson::JoinChanged { node, .. }
            | ChangeJson::StructFieldAdded { node, .. }
            | ChangeJson::StructFieldRemoved { node, .. }
            | ChangeJson::StructFieldTypeChanged { node, .. }
            | ChangeJson::ColumnExpressionChanged { node, .. } => node,
        }
    }

    /// A one-line, human-readable description of just this Change (no
    /// Node name -- the "Changed" section groups these under their Node).
    fn describe(&self) -> String {
        match self {
            ChangeJson::ColumnAdded { column, .. } => format!("+ column added: {column}"),
            ChangeJson::ColumnRemoved { column, .. } => format!("- column removed: {column}"),
            ChangeJson::ColumnExpressionChanged { column, .. } => {
                format!("~ column expression changed: {column}")
            }
            ChangeJson::ColumnTypeChanged {
                column,
                from_type,
                to_type,
                ..
            } => format!("~ column type changed: {column} ({from_type} -> {to_type})"),
            ChangeJson::JoinChanged {
                position,
                from_kind,
                to_kind,
                ..
            } => format!(
                "~ join changed at position {position}: {} -> {}",
                from_kind.as_deref().unwrap_or("none"),
                to_kind.as_deref().unwrap_or("none")
            ),
            ChangeJson::StructFieldAdded { column, field, .. } => {
                format!("+ struct field added: {column}.{field}")
            }
            ChangeJson::StructFieldRemoved { column, field, .. } => {
                format!("- struct field removed: {column}.{field}")
            }
            ChangeJson::StructFieldTypeChanged {
                column,
                field,
                from_type,
                to_type,
                ..
            } => {
                format!("~ struct field type changed: {column}.{field} ({from_type} -> {to_type})")
            }
        }
    }

    /// Whether this Change counts toward the summary line's "column(s)
    /// changed" tally -- everything except a join change, which isn't a
    /// column.
    fn is_column_change(&self) -> bool {
        !matches!(self, ChangeJson::JoinChanged { .. })
    }
}

impl From<&Change> for ChangeJson {
    fn from(change: &Change) -> Self {
        match change {
            Change::ColumnAdded { node, column } => ChangeJson::ColumnAdded {
                node: node.to_string(),
                column: column.to_string(),
            },
            Change::ColumnRemoved { node, column } => ChangeJson::ColumnRemoved {
                node: node.to_string(),
                column: column.to_string(),
            },
            Change::ColumnTypeChanged {
                node,
                column,
                from_type,
                to_type,
            } => ChangeJson::ColumnTypeChanged {
                node: node.to_string(),
                column: column.to_string(),
                from_type: from_type.clone(),
                to_type: to_type.clone(),
            },
            Change::ColumnExpressionChanged {
                node,
                column,
                from_expression,
                to_expression,
            } => ChangeJson::ColumnExpressionChanged {
                node: node.to_string(),
                column: column.to_string(),
                from_expression: from_expression.clone(),
                to_expression: to_expression.clone(),
            },
            Change::JoinChanged {
                node,
                position,
                from_kind,
                to_kind,
            } => ChangeJson::JoinChanged {
                node: node.to_string(),
                position: *position,
                from_kind: from_kind.map(join_kind_slug),
                to_kind: to_kind.map(join_kind_slug),
            },
            Change::StructFieldAdded {
                node,
                column,
                field,
            } => ChangeJson::StructFieldAdded {
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
            },
            Change::StructFieldRemoved {
                node,
                column,
                field,
            } => ChangeJson::StructFieldRemoved {
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
            },
            Change::StructFieldTypeChanged {
                node,
                column,
                field,
                from_type,
                to_type,
            } => ChangeJson::StructFieldTypeChanged {
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
                from_type: from_type.clone(),
                to_type: to_type.clone(),
            },
        }
    }
}

/// A [`Severity`], reshaped for JSON output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SeverityJson {
    /// See [`Severity::Error`].
    Error,
    /// See [`Severity::Warn`].
    Warn,
    /// See [`Severity::Pass`].
    Pass,
}

impl From<Severity> for SeverityJson {
    fn from(severity: Severity) -> Self {
        match severity {
            Severity::Error => SeverityJson::Error,
            Severity::Warn => SeverityJson::Warn,
            Severity::Pass => SeverityJson::Pass,
        }
    }
}

/// A [`Finding`], reshaped for JSON output.
///
/// Tagged by `rule` via serde directly from each variant's name (rather
/// than a hand-written slug function): renaming a variant automatically
/// changes its JSON tag with the compiler enforcing every variant stays
/// handled, instead of a parallel string-mapping function that could
/// silently drift out of sync.
#[derive(Debug, Serialize)]
#[serde(tag = "rule", rename_all = "kebab-case")]
pub enum FindingJson {
    /// See [`FindingDetail::ColumnRemovedWithActiveReferences`].
    ColumnRemovedWithActiveReferences {
        severity: SeverityJson,
        node: String,
        column: String,
        reached: String,
        reached_column: String,
    },
    /// See [`FindingDetail::ColumnTypeNarrowed`].
    ColumnTypeNarrowed {
        severity: SeverityJson,
        node: String,
        column: String,
        from_type: String,
        to_type: String,
    },
    /// See [`FindingDetail::JoinCardinalityLoosened`].
    JoinCardinalityLoosened {
        severity: SeverityJson,
        node: String,
        position: usize,
        from_kind: String,
        to_kind: String,
    },
    /// See [`FindingDetail::ColumnAdded`].
    ColumnAdded {
        severity: SeverityJson,
        node: String,
        column: String,
    },
    /// See [`FindingDetail::ColumnExpressionChanged`].
    ColumnExpressionChanged {
        severity: SeverityJson,
        node: String,
        column: String,
        reached: String,
        reached_column: String,
    },
    /// See [`FindingDetail::StructFieldRemoved`].
    StructFieldRemoved {
        severity: SeverityJson,
        node: String,
        column: String,
        field: String,
    },
    /// See [`FindingDetail::StructFieldAdded`].
    StructFieldAdded {
        severity: SeverityJson,
        node: String,
        column: String,
        field: String,
    },
    /// See [`FindingDetail::StructFieldTypeNarrowed`].
    StructFieldTypeNarrowed {
        severity: SeverityJson,
        node: String,
        column: String,
        field: String,
        from_type: String,
        to_type: String,
    },
}

impl FindingJson {
    fn severity(&self) -> SeverityJson {
        match self {
            FindingJson::ColumnRemovedWithActiveReferences { severity, .. }
            | FindingJson::ColumnTypeNarrowed { severity, .. }
            | FindingJson::JoinCardinalityLoosened { severity, .. }
            | FindingJson::ColumnAdded { severity, .. }
            | FindingJson::ColumnExpressionChanged { severity, .. }
            | FindingJson::StructFieldRemoved { severity, .. }
            | FindingJson::StructFieldAdded { severity, .. }
            | FindingJson::StructFieldTypeNarrowed { severity, .. } => *severity,
        }
    }

    /// This Finding's Rule, as the same kebab-case slug serde tags it with
    /// in JSON (`#[serde(tag = "rule", rename_all = "kebab-case")]` on
    /// this enum) -- an explicit match rather than deriving it from the
    /// JSON representation, so this and the JSON tag can't independently
    /// drift; `finding_json_rule_name_matches_its_serialized_json_tag`
    /// below cross-checks the two stay in sync.
    fn rule_name(&self) -> &'static str {
        match self {
            FindingJson::ColumnRemovedWithActiveReferences { .. } => {
                "column-removed-with-active-references"
            }
            FindingJson::ColumnTypeNarrowed { .. } => "column-type-narrowed",
            FindingJson::JoinCardinalityLoosened { .. } => "join-cardinality-loosened",
            FindingJson::ColumnAdded { .. } => "column-added",
            FindingJson::ColumnExpressionChanged { .. } => "column-expression-changed",
            FindingJson::StructFieldRemoved { .. } => "struct-field-removed",
            FindingJson::StructFieldAdded { .. } => "struct-field-added",
            FindingJson::StructFieldTypeNarrowed { .. } => "struct-field-type-narrowed",
        }
    }

    /// The Node this Finding's downstream impact is actually reported
    /// against: the downstream Node reached for
    /// [`FindingJson::ColumnRemovedWithActiveReferences`] (the only Rule
    /// that currently reasons about a *separate* downstream Node), or the
    /// changed Node itself for every other Rule, which reason about the
    /// changed Node's own behavior rather than tracing further downstream.
    fn impacted_node(&self) -> &str {
        match self {
            FindingJson::ColumnRemovedWithActiveReferences { reached, .. }
            | FindingJson::ColumnExpressionChanged { reached, .. } => reached,
            FindingJson::ColumnTypeNarrowed { node, .. }
            | FindingJson::JoinCardinalityLoosened { node, .. }
            | FindingJson::ColumnAdded { node, .. }
            | FindingJson::StructFieldRemoved { node, .. }
            | FindingJson::StructFieldAdded { node, .. }
            | FindingJson::StructFieldTypeNarrowed { node, .. } => node,
        }
    }
}

impl From<&Finding> for FindingJson {
    fn from(finding: &Finding) -> Self {
        let severity = finding.severity.into();
        match &finding.detail {
            FindingDetail::ColumnRemovedWithActiveReferences {
                node,
                column,
                reached,
                reached_column,
            } => FindingJson::ColumnRemovedWithActiveReferences {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                reached: reached.to_string(),
                reached_column: reached_column.to_string(),
            },
            FindingDetail::ColumnTypeNarrowed {
                node,
                column,
                from_type,
                to_type,
            } => FindingJson::ColumnTypeNarrowed {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                from_type: from_type.clone(),
                to_type: to_type.clone(),
            },
            FindingDetail::JoinCardinalityLoosened {
                node,
                position,
                from_kind,
                to_kind,
            } => FindingJson::JoinCardinalityLoosened {
                severity,
                node: node.to_string(),
                position: *position,
                from_kind: join_kind_slug(*from_kind),
                to_kind: join_kind_slug(*to_kind),
            },
            FindingDetail::ColumnExpressionChanged {
                node,
                column,
                reached,
                reached_column,
            } => FindingJson::ColumnExpressionChanged {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                reached: reached.to_string(),
                reached_column: reached_column.to_string(),
            },
            FindingDetail::ColumnAdded { node, column } => FindingJson::ColumnAdded {
                severity,
                node: node.to_string(),
                column: column.to_string(),
            },
            FindingDetail::StructFieldRemoved {
                node,
                column,
                field,
            } => FindingJson::StructFieldRemoved {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
            },
            FindingDetail::StructFieldAdded {
                node,
                column,
                field,
            } => FindingJson::StructFieldAdded {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
            },
            FindingDetail::StructFieldTypeNarrowed {
                node,
                column,
                field,
                from_type,
                to_type,
            } => FindingJson::StructFieldTypeNarrowed {
                severity,
                node: node.to_string(),
                column: column.to_string(),
                field: field.to_string(),
                from_type: from_type.clone(),
                to_type: to_type.clone(),
            },
        }
    }
}

/// Maps a [`JoinKind`] to its stable JSON string, via an explicit,
/// compiler-checked match rather than its `Debug` representation -- a
/// `Debug`-derived string would silently change this stable output if a
/// variant were ever renamed for unrelated internal reasons, with no
/// compiler error to catch it (unlike this match, which fails to compile
/// if a variant is left unhandled).
fn join_kind_slug(kind: JoinKind) -> String {
    match kind {
        JoinKind::Inner => "inner",
        JoinKind::Left => "left",
        JoinKind::Right => "right",
        JoinKind::Full => "full",
        JoinKind::Cross => "cross",
    }
    .to_string()
}

/// The ANSI escape sequence `BREAKING` labels are wrapped in when color is
/// enabled -- bold red.
const BREAKING_COLOR: &str = "\x1b[1;31m";
/// The ANSI escape sequence `WARN` labels are wrapped in when color is
/// enabled -- bold yellow.
const WARN_COLOR: &str = "\x1b[1;33m";
/// Resets any color started by [`BREAKING_COLOR`]/[`WARN_COLOR`].
const COLOR_RESET: &str = "\x1b[0m";

/// Wraps `text` in `color`, or returns it unchanged if `use_color` is
/// `false` -- the single point every color decision in this module goes
/// through, so no ANSI code can leak out when color is supposed to be off.
fn colorize(text: &str, color: &str, use_color: bool) -> String {
    if use_color {
        format!("{color}{text}{COLOR_RESET}")
    } else {
        text.to_string()
    }
}

/// Renders a [`Report`] as the three-part human-readable report: a
/// "Changed" section (each Node that actually changed, and precisely what
/// changed about it), a "Downstream impact" section (only Nodes actually
/// reached by a breaking or warning-level Finding, labeled `BREAKING` or
/// `WARN` with the specific reference and Rule that fired), and a summary
/// line. Every Node reference goes through `vocabulary` (e.g. "model" for
/// dbt), never zhao's own internal "Node"/"Origin" terms.
///
/// When `use_color` is `true`, `BREAKING`/`WARN` labels are wrapped in
/// ANSI color codes (red/yellow); when `false`, the output is plain text
/// with no escape sequences anywhere -- deciding *whether* color is
/// appropriate (a TTY, `--no-color`, `NO_COLOR`, known CI environments
/// like GitHub Actions that render ANSI without being a real TTY, ...) is
/// the caller's responsibility, not this function's.
///
/// ## Known limitation
///
/// `vocabulary.origin_term()` (e.g. "source" for dbt) is never actually
/// used here: neither [`Change`] nor [`FindingDetail`] can reference an
/// Origin today -- `diff()` only ever compares Nodes -- so there's
/// currently no path through this report that could render one. This
/// isn't a gap in this function specifically; it'll start mattering once
/// the diff engine itself gains the ability to detect an Origin-level
/// change (e.g. a source's declared schema changing).
pub fn render_text(report: &Report, vocabulary: &dyn AdapterVocabulary, use_color: bool) -> String {
    let mut out = String::new();
    let node_term = vocabulary.node_term();

    if let Some(warning) = &report.staleness_warning {
        out.push_str(&format!("warning: {warning}\n\n"));
    }

    if report.findings.is_empty() && report.changes.is_empty() {
        out.push_str("No changes detected.\n");
        return out;
    }

    out.push_str("Changed:\n");
    for (node, changes) in group_by_node(&report.changes, ChangeJson::node) {
        out.push_str(&format!("  {node_term} {node}:\n"));
        for change in changes {
            out.push_str(&format!("    {}\n", change.describe()));
        }
    }

    let impactful: Vec<&FindingJson> = report
        .findings
        .iter()
        .filter(|f| f.severity() != SeverityJson::Pass)
        .collect();
    if !impactful.is_empty() {
        out.push_str("\nDownstream impact:\n");
        for (node, findings) in group_by_node(&impactful, |f: &&FindingJson| f.impacted_node()) {
            out.push_str(&format!("  {node_term} {node}:\n"));
            for finding in findings {
                let label = match finding.severity() {
                    SeverityJson::Error => colorize("BREAKING", BREAKING_COLOR, use_color),
                    SeverityJson::Warn => colorize("WARN", WARN_COLOR, use_color),
                    SeverityJson::Pass => unreachable!("filtered out above"),
                };
                out.push_str(&format!(
                    "    [{label}] {} ({})\n",
                    describe_impact(finding, node_term),
                    finding.rule_name()
                ));
            }
        }
    }

    let models_changed = report
        .changes
        .iter()
        .map(ChangeJson::node)
        .collect::<std::collections::HashSet<_>>()
        .len();
    let columns_changed = report
        .changes
        .iter()
        .filter(|c| c.is_column_change())
        .count();
    let breaking = report
        .findings
        .iter()
        .filter(|f| f.severity() == SeverityJson::Error)
        .count();
    let warning = report
        .findings
        .iter()
        .filter(|f| f.severity() == SeverityJson::Warn)
        .count();
    out.push_str(&format!(
        "\nSummary: {models_changed} {node_term}(s) changed, {columns_changed} column(s) \
         changed, {breaking} breaking, {warning} warning\n"
    ));

    if !report.impacted_models.is_empty() {
        out.push_str(&format!(
            "\nImpacted models: {}\n",
            report.impacted_models.join(", ")
        ));
    }

    if let Some(plan) = &report.defer_plan {
        out.push_str("\nDefer plan:\n");
        out.push_str(&format!("  Build: {}\n", plan.build.join(", ")));
        out.push_str(&format!(
            "  Defer (assumed available): {}\n",
            if plan.defer.is_empty() {
                "none".to_string()
            } else {
                plan.defer.join(", ")
            }
        ));
        if let Some(target) = &plan.target {
            out.push_str(&format!("  Target: {target}\n"));
        }
        if let Some(state) = &plan.state {
            out.push_str(&format!("  State: {state}\n"));
        }
    }

    if let Some(command) = &report.recommended_command {
        out.push_str(&format!("\nRecommended command: {command}\n"));
    }

    if !report.schema_evolution_warnings.is_empty() {
        out.push_str("\nSchema evolution:\n");
        for warning in &report.schema_evolution_warnings {
            out.push_str(&format!(
                "  {node_term} {}: {}\n",
                warning.node, warning.message
            ));
        }
    }

    out
}

/// Groups `items` by a key derived from each one, preserving each group's
/// first-seen order (both across groups and within a group) rather than
/// sorting -- so the report's ordering follows the underlying `Change`/
/// `Finding` list's own (already-deterministic) order.
fn group_by_node<'a, T, F>(items: &'a [T], key: F) -> Vec<(&'a str, Vec<&'a T>)>
where
    F: Fn(&'a T) -> &'a str,
{
    let mut order: Vec<&'a str> = Vec::new();
    let mut groups: std::collections::HashMap<&'a str, Vec<&'a T>> =
        std::collections::HashMap::new();
    for item in items {
        let node = key(item);
        groups
            .entry(node)
            .or_insert_with(|| {
                order.push(node);
                Vec::new()
            })
            .push(item);
    }
    order
        .into_iter()
        .map(|node| {
            (
                node,
                groups.remove(node).expect("present for every ordered key"),
            )
        })
        .collect()
}

/// A one-line description of a Finding's impact, for the "Downstream
/// impact" section -- no Node name (the section already groups by it) and
/// no Severity label (the caller prefixes `[BREAKING]`/`[WARN]` itself).
fn describe_impact(finding: &FindingJson, node_term: &str) -> String {
    match finding {
        FindingJson::ColumnRemovedWithActiveReferences {
            node,
            column,
            reached_column,
            ..
        } => {
            format!(
                "{column} removed from {node_term} {node} breaks reference via {reached_column}"
            )
        }
        FindingJson::ColumnTypeNarrowed {
            column,
            from_type,
            to_type,
            ..
        } => {
            format!("{column} type narrowed from {from_type} to {to_type}")
        }
        FindingJson::JoinCardinalityLoosened {
            position,
            from_kind,
            to_kind,
            ..
        } => {
            format!("join at position {position} loosened from {from_kind} to {to_kind}")
        }
        FindingJson::ColumnAdded { column, .. } => {
            format!("{column} added")
        }
        FindingJson::ColumnExpressionChanged {
            node,
            column,
            reached,
            reached_column,
            ..
        } => {
            if node == reached {
                format!("expression of {column} changed")
            } else {
                format!(
                    "{reached_column} derives from {column}, whose expression changed in {node_term} {node}"
                )
            }
        }
        FindingJson::StructFieldRemoved { column, field, .. } => {
            format!("{field} removed from struct column {column}")
        }
        FindingJson::StructFieldAdded { column, field, .. } => {
            format!("{field} added to struct column {column}")
        }
        FindingJson::StructFieldTypeNarrowed {
            column,
            field,
            from_type,
            to_type,
            ..
        } => {
            format!("{column}.{field} type narrowed from {from_type} to {to_type}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zhao_core::adapters::dbt::DbtVocabulary;
    use zhao_core::model::{JoinKind as CoreJoinKind, NodeId};

    fn all_finding_variants() -> Vec<Finding> {
        let node = NodeId::new("model.a");
        vec![
            Finding {
                severity: Severity::Error,
                detail: FindingDetail::ColumnRemovedWithActiveReferences {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("id"),
                    reached: NodeId::new("model.b"),
                    reached_column: zhao_core::model::ColumnName::new("a_id"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnTypeNarrowed {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnExpressionChanged {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("amount"),
                    reached: NodeId::new("model.b"),
                    reached_column: zhao_core::model::ColumnName::new("total"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::JoinCardinalityLoosened {
                    node: node.clone(),
                    position: 0,
                    from_kind: CoreJoinKind::Inner,
                    to_kind: CoreJoinKind::Left,
                },
            },
            Finding {
                severity: Severity::Pass,
                detail: FindingDetail::ColumnAdded {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("new_col"),
                },
            },
            Finding {
                severity: Severity::Error,
                detail: FindingDetail::StructFieldRemoved {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("payload"),
                    field: zhao_core::model::ColumnName::new("legacy_flag"),
                },
            },
            Finding {
                severity: Severity::Pass,
                detail: FindingDetail::StructFieldAdded {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("payload"),
                    field: zhao_core::model::ColumnName::new("email"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::StructFieldTypeNarrowed {
                    node,
                    column: zhao_core::model::ColumnName::new("payload"),
                    field: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
        ]
    }

    /// `FindingJson::rule_name` is a hand-maintained mirror of the same
    /// enum's `#[serde(tag = "rule", rename_all = "kebab-case")]`
    /// derive -- this test is what keeps the two from silently drifting
    /// apart if a variant is ever renamed and only one side is updated.
    #[test]
    fn finding_json_rule_name_matches_its_serialized_json_tag() {
        for finding in &all_finding_variants() {
            let json = FindingJson::from(finding);
            let serialized: serde_json::Value =
                serde_json::to_value(&json).expect("should serialize");
            assert_eq!(
                serialized["rule"]
                    .as_str()
                    .expect("rule should be a string"),
                json.rule_name(),
                "rule_name() drifted from the derived JSON tag for {json:?}"
            );
        }
    }

    #[test]
    fn render_text_reports_no_changes_detected_when_nothing_changed() {
        let report = Report::new(&[], &[]);

        assert_eq!(
            render_text(&report, &DbtVocabulary, false),
            "No changes detected.\n"
        );
    }

    #[test]
    fn render_text_produces_the_three_part_report_using_the_adapters_vocabulary() {
        let changes = vec![
            Change::ColumnAdded {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("new_col"),
            },
            Change::ColumnRemoved {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("id"),
            },
        ];
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::ColumnRemovedWithActiveReferences {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("id"),
                reached: NodeId::new("model.b"),
                reached_column: zhao_core::model::ColumnName::new("a_id"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        // Uses dbt's vocabulary ("model"), never zhao's internal terms.
        assert!(text.contains("model model.a"), "{text}");
        assert!(!text.contains("Node "), "{text}");
        assert!(!text.contains("Origin "), "{text}");

        // Changed section: both changes on model.a, grouped under it.
        assert!(text.contains("Changed:\n  model model.a:\n"), "{text}");
        assert!(text.contains("+ column added: new_col"), "{text}");
        assert!(text.contains("- column removed: id"), "{text}");

        // Downstream impact: the reached model, not the changed one, with
        // the rule name.
        assert!(
            text.contains("Downstream impact:\n  model model.b:\n"),
            "{text}"
        );
        assert!(
            text.contains("[BREAKING]") && text.contains("column-removed-with-active-references"),
            "{text}"
        );

        // Summary counts.
        assert!(
            text.contains(
                "Summary: 1 model(s) changed, 2 column(s) changed, 1 breaking, 0 warning"
            ),
            "{text}"
        );
    }

    /// A `pass`-severity Finding (e.g. `column-added`) is informational,
    /// not impact -- it must not appear in "Downstream impact" at all,
    /// even though the Change it's attached to does appear in "Changed".
    #[test]
    fn render_text_excludes_pass_severity_findings_from_downstream_impact() {
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let findings = vec![Finding {
            severity: Severity::Pass,
            detail: FindingDetail::ColumnAdded {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("new_col"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(text.contains("Changed:"), "{text}");
        assert!(
            !text.contains("Downstream impact:"),
            "a pass-severity finding must not produce a Downstream impact section: {text}"
        );
        assert!(text.contains("0 breaking, 0 warning"), "{text}");
    }

    /// With `use_color: false`, no ANSI escape byte appears anywhere in
    /// the output -- the property `--no-color`'s "byte-for-byte plain
    /// text" acceptance criterion ultimately rests on.
    #[test]
    fn render_text_with_use_color_false_contains_no_ansi_escapes() {
        let changes = vec![Change::ColumnRemoved {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("id"),
        }];
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::ColumnRemovedWithActiveReferences {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("id"),
                reached: NodeId::new("model.b"),
                reached_column: zhao_core::model::ColumnName::new("a_id"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(
            !text.contains('\x1b'),
            "no ANSI escape byte should appear when use_color is false: {text:?}"
        );
    }

    /// With `use_color: true`, `BREAKING`/`WARN` labels carry an ANSI
    /// escape somewhere in the output -- checked for *presence* only, not
    /// the exact byte sequence, so this doesn't snapshot-lock the specific
    /// color codes chosen.
    #[test]
    fn render_text_with_use_color_true_contains_ansi_escapes_for_breaking_and_warn() {
        let node = NodeId::new("model.a");
        let findings = vec![
            Finding {
                severity: Severity::Error,
                detail: FindingDetail::ColumnRemovedWithActiveReferences {
                    node: node.clone(),
                    column: zhao_core::model::ColumnName::new("id"),
                    reached: NodeId::new("model.b"),
                    reached_column: zhao_core::model::ColumnName::new("a_id"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnTypeNarrowed {
                    node,
                    column: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
        ];
        let report = Report::new(&[], &findings);

        let text = render_text(&report, &DbtVocabulary, true);

        assert!(
            text.contains('\x1b'),
            "an ANSI escape byte should appear somewhere when use_color is true: {text:?}"
        );
        // Still contains the plain label text -- color wraps it, doesn't
        // replace it.
        assert!(text.contains("BREAKING"), "{text}");
        assert!(text.contains("WARN"), "{text}");
    }

    /// Acceptance criterion 1: the generated selector set exactly matches
    /// the Nodes listed in the Downstream impact section -- no more (a
    /// Node that only appears in "Changed", like `stg_orders` here via a
    /// pass-severity Finding, must be excluded), no less, and
    /// deduplicated (both Findings below share `stg_customers` as their
    /// impacted Node).
    #[test]
    fn with_impacted_models_includes_exactly_the_downstream_impact_nodes() {
        let findings = vec![
            Finding {
                severity: Severity::Error,
                detail: FindingDetail::ColumnRemovedWithActiveReferences {
                    node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                    column: zhao_core::model::ColumnName::new("id"),
                    reached: NodeId::new("model.zhao_dbt_test.dim_customers"),
                    reached_column: zhao_core::model::ColumnName::new("a_id"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnTypeNarrowed {
                    node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                    column: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
            Finding {
                severity: Severity::Pass,
                detail: FindingDetail::ColumnAdded {
                    node: NodeId::new("model.zhao_dbt_test.stg_orders"),
                    column: zhao_core::model::ColumnName::new("new_col"),
                },
            },
        ];
        let report = Report::new(&[], &findings).with_impacted_models(&DbtVocabulary);

        assert_eq!(
            report.impacted_models,
            vec!["dim_customers".to_string(), "stg_customers".to_string()],
            "should include dim_customers (via the reached Finding) and stg_customers \
             (via the type-narrowed Finding on itself) exactly once each, and never \
             stg_orders (only a pass-severity Finding, not Downstream impact)"
        );
    }

    /// Regression test for the bug an earlier version of this method had:
    /// a Node reached only via the Baseline (e.g. one that no longer
    /// exists in the current state at all, for
    /// `ColumnRemovedWithActiveReferences`) must still be named in
    /// `impacted_models` -- this method no longer looks Nodes up
    /// against a `ParsedProject` at all, precisely so there's nothing to
    /// fail to resolve.
    #[test]
    fn with_impacted_models_includes_a_node_that_no_longer_exists_anywhere_but_its_id() {
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::ColumnRemovedWithActiveReferences {
                node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                column: zhao_core::model::ColumnName::new("id"),
                reached: NodeId::new("model.zhao_dbt_test.deleted_downstream_model"),
                reached_column: zhao_core::model::ColumnName::new("a_id"),
            },
        }];
        let report = Report::new(&[], &findings).with_impacted_models(&DbtVocabulary);

        assert_eq!(
            report.impacted_models,
            vec!["deleted_downstream_model".to_string()],
        );
    }

    /// Acceptance criterion 2: a run with zero impacted Nodes produces an
    /// empty impacted-models list.
    #[test]
    fn with_impacted_models_is_empty_when_nothing_is_impactful() {
        // No Findings at all.
        let report = Report::new(&[], &[]).with_impacted_models(&DbtVocabulary);
        assert_eq!(report.impacted_models, Vec::<String>::new());

        // A Finding exists, but it's pass-severity -- not Downstream
        // impact, so still nothing impacted.
        let findings = vec![Finding {
            severity: Severity::Pass,
            detail: FindingDetail::ColumnAdded {
                node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                column: zhao_core::model::ColumnName::new("new_col"),
            },
        }];
        let report = Report::new(&[], &findings).with_impacted_models(&DbtVocabulary);
        assert_eq!(report.impacted_models, Vec::<String>::new());
    }

    /// A changed model is part of the set to rebuild even when every Finding on
    /// it is pass-severity (a column added), and it comes before whatever sits
    /// downstream of it, each model listed once.
    #[test]
    fn impacted_models_lists_changed_models_first_then_downstream_readers() {
        let changes = vec![
            Change::ColumnAdded {
                node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                column: zhao_core::model::ColumnName::new("new_col"),
            },
            Change::ColumnExpressionChanged {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("total"),
                from_expression: Some("a + 1".to_string()),
                to_expression: Some("a + 2".to_string()),
            },
        ];
        let findings = vec![
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnExpressionChanged {
                    node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                    column: zhao_core::model::ColumnName::new("total"),
                    reached: NodeId::new("model.zhao_dbt_test.dim_customers"),
                    reached_column: zhao_core::model::ColumnName::new("total"),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnExpressionChanged {
                    node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                    column: zhao_core::model::ColumnName::new("total"),
                    reached: NodeId::new("model.zhao_dbt_test.fct_orders"),
                    reached_column: zhao_core::model::ColumnName::new("amount"),
                },
            },
        ];
        let report = Report::new(&changes, &findings).with_impacted_models(&DbtVocabulary);
        assert_eq!(
            report.impacted_models,
            vec!["stg_customers", "dim_customers", "fct_orders"]
        );
    }

    #[test]
    fn render_text_describes_a_column_expression_change_and_what_it_reaches() {
        let changes = vec![Change::ColumnExpressionChanged {
            node: NodeId::new("model.zhao_dbt_test.dim_customers"),
            column: zhao_core::model::ColumnName::new("total"),
            from_expression: Some("a + 1".to_string()),
            to_expression: Some("a + 2".to_string()),
        }];
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnExpressionChanged {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("total"),
                reached: NodeId::new("model.zhao_dbt_test.fct_orders"),
                reached_column: zhao_core::model::ColumnName::new("amount"),
            },
        }];
        let text = render_text(&Report::new(&changes, &findings), &DbtVocabulary, false);
        assert!(
            text.contains("~ column expression changed: total"),
            "{text}"
        );
        assert!(
            text.contains("amount derives from total, whose expression changed"),
            "{text}"
        );
        assert!(text.contains("(column-expression-changed)"), "{text}");
    }

    /// `render_text` appends the impacted-models line as a final line when
    /// present, and omits it entirely when absent.
    #[test]
    fn render_text_appends_the_impacted_models_line_when_present() {
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::ColumnRemovedWithActiveReferences {
                node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                column: zhao_core::model::ColumnName::new("id"),
                reached: NodeId::new("model.zhao_dbt_test.stg_customers"),
                reached_column: zhao_core::model::ColumnName::new("id"),
            },
        }];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_staleness_warning(false);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(text.contains("Impacted models: stg_customers"), "{text}");
    }

    #[test]
    fn render_text_omits_the_impacted_models_line_when_absent() {
        let report = Report::new(&[], &[]);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(!text.contains("Impacted models:"), "{text}");
    }

    fn impacted_models_finding(node: &str) -> Finding {
        Finding {
            severity: Severity::Error,
            detail: FindingDetail::ColumnRemovedWithActiveReferences {
                node: NodeId::new(node),
                column: zhao_core::model::ColumnName::new("id"),
                reached: NodeId::new(node),
                reached_column: zhao_core::model::ColumnName::new("id"),
            },
        }
    }

    #[test]
    fn with_recommended_command_is_none_when_subcommand_is_not_configured() {
        let findings = vec![impacted_models_finding("model.zhao_dbt_test.stg_customers")];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_recommended_command(None, "dbt", None);

        assert!(report.recommended_command.is_none());
    }

    #[test]
    fn with_recommended_command_is_none_when_nothing_is_impacted_even_if_configured() {
        let report = Report::new(&[], &[]).with_recommended_command(Some("run"), "dbt", None);

        assert!(report.recommended_command.is_none());
    }

    #[test]
    fn with_recommended_command_builds_a_select_command_from_impacted_models() {
        let findings = vec![
            impacted_models_finding("model.zhao_dbt_test.stg_customers"),
            impacted_models_finding("model.zhao_dbt_test.dim_customers"),
        ];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_recommended_command(Some("run"), "dbt", None);

        assert_eq!(
            report.recommended_command.as_deref(),
            Some("dbt run --select stg_customers dim_customers")
        );
    }

    #[test]
    fn with_recommended_command_uses_the_configured_dbt_command_wrapper() {
        let findings = vec![impacted_models_finding("model.zhao_dbt_test.stg_customers")];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_recommended_command(Some("build"), "uv run dbt", None);

        assert_eq!(
            report.recommended_command.as_deref(),
            Some("uv run dbt build --select stg_customers")
        );
    }

    #[test]
    fn with_recommended_command_appends_target_when_a_label_is_given() {
        let findings = vec![impacted_models_finding("model.zhao_dbt_test.stg_customers")];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_recommended_command(Some("run"), "dbt", Some("prod"));

        assert_eq!(
            report.recommended_command.as_deref(),
            Some("dbt run --select stg_customers --target prod")
        );
    }

    #[test]
    fn render_text_appends_the_recommended_command_line_when_present() {
        let findings = vec![impacted_models_finding("model.zhao_dbt_test.stg_customers")];
        let report = Report::new(&[], &findings)
            .with_impacted_models(&DbtVocabulary)
            .with_recommended_command(Some("run"), "dbt", None);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(
            text.contains("Recommended command: dbt run --select stg_customers"),
            "{text}"
        );
    }

    #[test]
    fn render_text_omits_the_recommended_command_line_when_absent() {
        let report = Report::new(&[], &[]);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(!text.contains("Recommended command:"), "{text}");
    }

    /// A minimal `ParsedProject` with one Node per `(id, name)` pair and
    /// the given `LineageEdge`s -- enough to exercise
    /// `Report::with_defer_plan`'s graph walk without needing a real
    /// compiled manifest.
    fn project_with_edges(edges: Vec<zhao_core::model::LineageEdge>) -> ParsedProject {
        ParsedProject {
            seed_node_ids: Default::default(),
            nodes: Vec::new(),
            origins: Vec::new(),
            edges,
        }
    }

    fn node_edge(upstream: &str, downstream: &str) -> zhao_core::model::LineageEdge {
        zhao_core::model::LineageEdge {
            upstream: Upstream::Node(NodeId::new(upstream)),
            downstream: NodeId::new(downstream),
            column: None,
        }
    }

    fn node_with_materialization(
        id: &str,
        materialization: Materialization,
    ) -> zhao_core::model::Node {
        zhao_core::model::Node {
            id: NodeId::new(id),
            name: id.to_string(),
            columns: Vec::new(),
            joins: Vec::new(),
            materialization,
        }
    }

    fn project_with_nodes(nodes: Vec<zhao_core::model::Node>) -> ParsedProject {
        ParsedProject {
            seed_node_ids: Default::default(),
            nodes,
            origins: Vec::new(),
            edges: Vec::new(),
        }
    }

    /// Acceptance criterion 1: given a Change reaching a subset of Nodes,
    /// the plan correctly separates build (the impacted set) from defer
    /// (their upstream dependencies) -- including a Node reached only
    /// transitively (`model.zhao_dbt_test.raw_base`, two hops upstream of
    /// the single impacted Node), proving this is a real transitive
    /// closure, not just direct parents.
    #[test]
    fn with_defer_plan_separates_build_from_transitive_upstream_dependencies() {
        let current = project_with_edges(vec![
            node_edge(
                "model.zhao_dbt_test.stg_orders",
                "model.zhao_dbt_test.dim_customers",
            ),
            node_edge(
                "model.zhao_dbt_test.raw_base",
                "model.zhao_dbt_test.stg_orders",
            ),
        ]);
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let report = Report::new(&[], &findings).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        let plan = report.defer_plan.expect("plan should be present");
        assert_eq!(plan.build, vec!["dim_customers"]);
        assert_eq!(plan.defer, vec!["raw_base", "stg_orders"]);
    }

    /// A build Node whose only upstream dependency is an Origin (a
    /// source, not a Node) produces an empty (not absent) defer list --
    /// dbt never builds a source, so there's genuinely nothing to defer,
    /// but that's still meaningful information, not "no plan at all."
    #[test]
    fn with_defer_plan_defer_is_empty_not_absent_when_only_an_origin_is_upstream() {
        let current = project_with_edges(vec![zhao_core::model::LineageEdge {
            upstream: Upstream::Origin(zhao_core::model::OriginId::new("source.raw.customers")),
            downstream: NodeId::new("model.zhao_dbt_test.stg_customers"),
            column: None,
        }]);
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let report = Report::new(&[], &findings).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        let plan = report.defer_plan.expect("plan should be present");
        assert_eq!(plan.build, vec!["stg_customers"]);
        assert!(plan.defer.is_empty());
    }

    /// A Node already in the build set is never also listed in defer,
    /// even if another build Node depends on it directly.
    #[test]
    fn with_defer_plan_never_defers_a_node_thats_also_being_built() {
        let current = project_with_edges(vec![node_edge(
            "model.zhao_dbt_test.stg_customers",
            "model.zhao_dbt_test.dim_customers",
        )]);
        let findings = vec![
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnTypeNarrowed {
                    node: NodeId::new("model.zhao_dbt_test.stg_customers"),
                    column: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
            Finding {
                severity: Severity::Warn,
                detail: FindingDetail::ColumnTypeNarrowed {
                    node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                    column: zhao_core::model::ColumnName::new("amount"),
                    from_type: "bigint".to_string(),
                    to_type: "int".to_string(),
                },
            },
        ];
        let report = Report::new(&[], &findings).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        let plan = report.defer_plan.expect("plan should be present");
        assert!(!plan.defer.contains(&"stg_customers".to_string()));
    }

    /// A run with zero impacted Nodes produces no defer plan at all.
    #[test]
    fn with_defer_plan_is_none_when_nothing_is_impactful() {
        let current = project_with_edges(Vec::new());
        let report = Report::new(&[], &[]).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        assert!(report.defer_plan.is_none());
    }

    #[test]
    fn render_text_appends_the_defer_plan_when_present() {
        let current = project_with_edges(vec![node_edge(
            "model.zhao_dbt_test.stg_orders",
            "model.zhao_dbt_test.dim_customers",
        )]);
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let report = Report::new(&[], &findings).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(text.contains("Defer plan:"), "{text}");
        assert!(text.contains("Build: dim_customers"), "{text}");
        assert!(
            text.contains("Defer (assumed available): stg_orders"),
            "{text}"
        );
    }

    #[test]
    fn render_text_omits_the_defer_plan_section_when_absent() {
        let report = Report::new(&[], &[]);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(!text.contains("Defer plan:"), "{text}");
    }

    /// A configured `defer.state` produces a ready-to-run command naming
    /// exactly the build set and the configured state path.
    #[test]
    fn defer_settings_with_a_state_path_surface_it_on_the_plan() {
        let current = project_with_edges(vec![node_edge(
            "model.zhao_dbt_test.stg_orders",
            "model.zhao_dbt_test.dim_customers",
        )]);
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let settings = DeferSettings {
            target: Some("prod".to_string()),
            state: Some("artifacts/prod/manifest.json".to_string()),
        };
        let report =
            Report::new(&[], &findings).with_defer_plan(&current, &DbtVocabulary, &settings);

        let plan = report.defer_plan.as_ref().expect("plan should be present");
        assert_eq!(plan.target.as_deref(), Some("prod"));
        assert_eq!(plan.state.as_deref(), Some("artifacts/prod/manifest.json"));

        let text = render_text(&report, &DbtVocabulary, false);
        assert!(text.contains("Target: prod"), "{text}");
        assert!(
            text.contains("State: artifacts/prod/manifest.json"),
            "{text}"
        );
    }

    /// A `defer.target` with no `defer.state` still labels the plan (for
    /// documentation purposes), but surfaces no state path at all.
    #[test]
    fn defer_settings_with_only_a_target_produce_no_state() {
        let current = project_with_edges(Vec::new());
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let settings = DeferSettings {
            target: Some("prod".to_string()),
            state: None,
        };
        let report =
            Report::new(&[], &findings).with_defer_plan(&current, &DbtVocabulary, &settings);

        let plan = report.defer_plan.expect("plan should be present");
        assert_eq!(plan.target.as_deref(), Some("prod"));
        assert!(plan.state.is_none());
    }

    /// The symmetric case: `state` configured with no `target` still
    /// surfaces the state path, just with no human-readable label
    /// alongside it.
    #[test]
    fn defer_settings_with_only_a_state_surface_it_with_no_target() {
        let current = project_with_edges(Vec::new());
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let settings = DeferSettings {
            target: None,
            state: Some("artifacts/prod/manifest.json".to_string()),
        };
        let report =
            Report::new(&[], &findings).with_defer_plan(&current, &DbtVocabulary, &settings);

        let plan = report.defer_plan.as_ref().expect("plan should be present");
        assert!(plan.target.is_none());
        assert_eq!(plan.state.as_deref(), Some("artifacts/prod/manifest.json"));

        let text = render_text(&report, &DbtVocabulary, false);
        assert!(!text.contains("Target:"), "{text}");
        assert!(text.contains("State:"), "{text}");
    }

    /// The state path is surfaced completely raw/verbatim, even one
    /// containing spaces or other shell-special characters -- there's no
    /// command being constructed here for it to need quoting into.
    #[test]
    fn a_state_path_with_spaces_is_surfaced_verbatim() {
        let current = project_with_edges(Vec::new());
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let settings = DeferSettings {
            target: None,
            state: Some("artifacts/My Manifests/prod/manifest.json".to_string()),
        };
        let report =
            Report::new(&[], &findings).with_defer_plan(&current, &DbtVocabulary, &settings);

        let plan = report.defer_plan.expect("plan should be present");
        assert_eq!(
            plan.state.as_deref(),
            Some("artifacts/My Manifests/prod/manifest.json")
        );
    }

    /// Default (unconfigured) `DeferSettings` produce neither a target
    /// label nor a state path -- the plan's build/defer lists alone,
    /// exactly as before this feature existed.
    #[test]
    fn default_defer_settings_produce_neither_target_nor_state() {
        let current = project_with_edges(Vec::new());
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::ColumnTypeNarrowed {
                node: NodeId::new("model.zhao_dbt_test.dim_customers"),
                column: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let report = Report::new(&[], &findings).with_defer_plan(
            &current,
            &DbtVocabulary,
            &DeferSettings::default(),
        );

        let plan = report.defer_plan.expect("plan should be present");
        assert!(plan.target.is_none());
        assert!(plan.state.is_none());
    }

    /// Acceptance criterion 1: a schema-changing Change on an incremental
    /// Node produces the flag.
    #[test]
    fn schema_evolution_warning_fires_for_a_schema_change_on_an_incremental_node() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        assert_eq!(report.schema_evolution_warnings.len(), 1);
        assert_eq!(report.schema_evolution_warnings[0].node, "model.a");
    }

    /// Acceptance criterion 2: the identical kind of Change on a
    /// table-materialized Node never produces the flag.
    #[test]
    fn schema_evolution_warning_never_fires_for_a_table_node() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Table,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        assert!(report.schema_evolution_warnings.is_empty());
    }

    /// The remaining two `Materialization` variants -- `view` (also
    /// exercised via the sibling `does_not_fire_for_a_table_node` test's
    /// counterpart above) never fires, but `ephemeral` and an unrecognized
    /// `Other` materialization must not fire either.
    #[test]
    fn schema_evolution_warning_never_fires_for_ephemeral_or_other_materializations() {
        for materialization in [
            Materialization::View,
            Materialization::Ephemeral,
            Materialization::Other("materialized_view".to_string()),
        ] {
            let current = project_with_nodes(vec![node_with_materialization(
                "model.a",
                materialization.clone(),
            )]);
            let changes = vec![Change::ColumnAdded {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("new_col"),
            }];
            let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

            assert!(
                report.schema_evolution_warnings.is_empty(),
                "{materialization:?} should never produce a schema evolution warning"
            );
        }
    }

    /// A non-schema Change (a join change) on an incremental Node never
    /// produces the flag either -- it's not a schema change at all.
    #[test]
    fn schema_evolution_warning_never_fires_for_a_join_change() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::JoinChanged {
            node: NodeId::new("model.a"),
            position: 0,
            from_kind: Some(CoreJoinKind::Inner),
            to_kind: Some(CoreJoinKind::Left),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        assert!(report.schema_evolution_warnings.is_empty());
    }

    /// `--check-relations` acceptance criterion: confirmed existing
    /// upgrades the warning from conditional to definitive wording,
    /// without dropping it.
    #[test]
    fn with_live_relation_checks_upgrades_a_confirmed_warning_to_definitive_wording() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[])
            .with_schema_evolution_warnings(&current)
            .with_live_relation_checks(|_node| Some(true));

        assert_eq!(report.schema_evolution_warnings.len(), 1);
        let message = &report.schema_evolution_warnings[0].message;
        assert!(
            !message.starts_with("if "),
            "a confirmed-existing warning should no longer be phrased conditionally: {message}"
        );
        assert!(
            message.contains("exists in your target environment"),
            "{message}"
        );
    }

    /// `--check-relations` acceptance criterion: confirmed not to exist
    /// drops the warning entirely.
    #[test]
    fn with_live_relation_checks_drops_a_confirmed_absent_warning() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[])
            .with_schema_evolution_warnings(&current)
            .with_live_relation_checks(|_node| Some(false));

        assert!(report.schema_evolution_warnings.is_empty());
    }

    /// `--check-relations` acceptance criterion (implied): when the check
    /// couldn't be performed at all (unsupported warehouse, failed
    /// check), the warning's original conditional wording is left
    /// untouched -- same as `--check-relations` never having been passed.
    #[test]
    fn with_live_relation_checks_leaves_an_undetermined_warning_unchanged() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let before = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);
        let original_message = before.schema_evolution_warnings[0].message.clone();

        let after = before.with_live_relation_checks(|_node| None);

        assert_eq!(after.schema_evolution_warnings.len(), 1);
        assert_eq!(after.schema_evolution_warnings[0].message, original_message);
    }

    /// Acceptance criterion 3: the message is phrased as a conditional
    /// possibility, never asserts the model exists as fact.
    #[test]
    fn schema_evolution_warning_message_is_phrased_conditionally() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnRemoved {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("old_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        let message = &report.schema_evolution_warnings[0].message;
        assert!(
            message.starts_with("if "),
            "message should be phrased as a conditional, not asserted as fact: {message}"
        );
    }

    /// Acceptance criterion 4: no DDL of any kind appears anywhere in the
    /// output.
    #[test]
    fn schema_evolution_warning_never_contains_ddl() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        let text = render_text(&report, &DbtVocabulary, false);
        for ddl_keyword in ["ALTER TABLE", "ADD COLUMN", "DROP COLUMN", "CREATE TABLE"] {
            assert!(
                !text.to_uppercase().contains(ddl_keyword),
                "found DDL-shaped text {ddl_keyword:?} in: {text}"
            );
        }
    }

    #[test]
    fn render_text_appends_the_schema_evolution_section_when_present() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(text.contains("Schema evolution:"), "{text}");
        assert!(text.contains("model model.a:"), "{text}");
    }

    #[test]
    fn render_text_omits_the_schema_evolution_section_when_absent() {
        // A real Change on a real (table-materialized) Node, so this
        // exercises the full render path rather than the early-return
        // "No changes detected." case -- the section must still be absent.
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Table,
        )]);
        let changes = vec![Change::ColumnAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("new_col"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(!text.contains("Schema evolution:"), "{text}");
    }

    // -----------------------------------------------------------------
    // Struct-internal field evolution (issue #53) -- full Change/Finding
    // pipeline through Report/render_text, not a separate mechanism.
    // -----------------------------------------------------------------

    /// A struct field removal surfaces in both the "Changed" and
    /// "Downstream impact" sections of the plain-text report, labeled
    /// `BREAKING` with its Rule name -- the same shape
    /// `column-removed-with-active-references` gets, just for a nested
    /// field instead of a top-level column.
    #[test]
    fn render_text_reports_a_struct_field_removal_as_breaking() {
        let changes = vec![Change::StructFieldRemoved {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("payload"),
            field: zhao_core::model::ColumnName::new("legacy_flag"),
        }];
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::StructFieldRemoved {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("payload"),
                field: zhao_core::model::ColumnName::new("legacy_flag"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(
            text.contains("- struct field removed: payload.legacy_flag"),
            "{text}"
        );
        assert!(
            text.contains("Downstream impact:\n  model model.a:\n"),
            "{text}"
        );
        assert!(
            text.contains("[BREAKING]") && text.contains("struct-field-removed"),
            "{text}"
        );
        assert!(
            text.contains("legacy_flag removed from struct column payload"),
            "{text}"
        );
        assert!(text.contains("1 breaking, 0 warning"), "{text}");
    }

    /// A struct field addition is `pass`-severity and never appears in
    /// "Downstream impact" -- the same treatment `column-added` gets.
    #[test]
    fn render_text_reports_a_struct_field_addition_as_informational_only() {
        let changes = vec![Change::StructFieldAdded {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("payload"),
            field: zhao_core::model::ColumnName::new("email"),
        }];
        let findings = vec![Finding {
            severity: Severity::Pass,
            detail: FindingDetail::StructFieldAdded {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("payload"),
                field: zhao_core::model::ColumnName::new("email"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(
            text.contains("+ struct field added: payload.email"),
            "{text}"
        );
        assert!(
            !text.contains("Downstream impact:"),
            "a pass-severity struct field addition must not produce Downstream impact: {text}"
        );
        assert!(text.contains("0 breaking, 0 warning"), "{text}");
    }

    /// A struct field type narrowing is `warn`-severity, matching
    /// `column-type-narrowed`'s own treatment.
    #[test]
    fn render_text_reports_a_struct_field_type_narrowing_as_a_warning() {
        let changes = vec![Change::StructFieldTypeChanged {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("payload"),
            field: zhao_core::model::ColumnName::new("amount"),
            from_type: "bigint".to_string(),
            to_type: "int".to_string(),
        }];
        let findings = vec![Finding {
            severity: Severity::Warn,
            detail: FindingDetail::StructFieldTypeNarrowed {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("payload"),
                field: zhao_core::model::ColumnName::new("amount"),
                from_type: "bigint".to_string(),
                to_type: "int".to_string(),
            },
        }];
        let report = Report::new(&changes, &findings);

        let text = render_text(&report, &DbtVocabulary, false);

        assert!(
            text.contains("~ struct field type changed: payload.amount (bigint -> int)"),
            "{text}"
        );
        assert!(
            text.contains("[WARN]") && text.contains("struct-field-type-narrowed"),
            "{text}"
        );
        assert!(text.contains("0 breaking, 1 warning"), "{text}");
    }

    /// The `--format json` payload carries the same struct-evolution
    /// Change/Finding through `serde_json`, tagged the same way every
    /// other Change/Finding variant already is -- not a separate,
    /// parallel JSON shape.
    #[test]
    fn json_report_serializes_struct_field_changes_and_findings() {
        let changes = vec![Change::StructFieldRemoved {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("payload"),
            field: zhao_core::model::ColumnName::new("legacy_flag"),
        }];
        let findings = vec![Finding {
            severity: Severity::Error,
            detail: FindingDetail::StructFieldRemoved {
                node: NodeId::new("model.a"),
                column: zhao_core::model::ColumnName::new("payload"),
                field: zhao_core::model::ColumnName::new("legacy_flag"),
            },
        }];
        let report = Report::new(&changes, &findings);

        let json: serde_json::Value =
            serde_json::to_value(&report).expect("report should serialize");

        assert_eq!(json["changes"][0]["type"], "struct_field_removed");
        assert_eq!(json["changes"][0]["column"], "payload");
        assert_eq!(json["changes"][0]["field"], "legacy_flag");
        assert_eq!(json["findings"][0]["rule"], "struct-field-removed");
        assert_eq!(json["findings"][0]["severity"], "error");
        assert_eq!(json["findings"][0]["field"], "legacy_flag");
    }

    /// A struct-evolution Change on an `incremental` Node produces a
    /// schema-evolution warning too, the same as any other schema
    /// Change -- `Change::is_column_change` covers every non-`JoinChanged`
    /// variant by construction, so this needs no dedicated wiring, but is
    /// still worth pinning down as a regression guard.
    #[test]
    fn schema_evolution_warning_fires_for_a_struct_field_change_on_an_incremental_node() {
        let current = project_with_nodes(vec![node_with_materialization(
            "model.a",
            Materialization::Incremental,
        )]);
        let changes = vec![Change::StructFieldRemoved {
            node: NodeId::new("model.a"),
            column: zhao_core::model::ColumnName::new("payload"),
            field: zhao_core::model::ColumnName::new("legacy_flag"),
        }];
        let report = Report::new(&changes, &[]).with_schema_evolution_warnings(&current);

        assert_eq!(report.schema_evolution_warnings.len(), 1);
        assert_eq!(report.schema_evolution_warnings[0].node, "model.a");
    }
}