fallow-config 2.78.1

Configuration types and workspace discovery for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
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
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
//! Architecture boundary zone and rule definitions.

use std::fmt;
use std::path::Path;

use globset::Glob;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Which zone-reference surface on a `BoundaryRule` carries an unknown name.
///
/// The diagnostic surfaces the kind so users editing a multi-field rule know
/// whether to fix `from`, `allow`, or `allowTypeOnly`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ZoneReferenceKind {
    /// Rule's `from` field names an undefined zone.
    From,
    /// One entry in the rule's `allow` list names an undefined zone.
    Allow,
    /// One entry in the rule's `allowTypeOnly` list names an undefined zone.
    AllowTypeOnly,
}

impl ZoneReferenceKind {
    fn config_field(self) -> &'static str {
        match self {
            Self::From => "from",
            Self::Allow => "allow",
            Self::AllowTypeOnly => "allowTypeOnly",
        }
    }
}

/// One offending zone-name reference in a `boundaries.rules[]` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownZoneRef {
    /// Zero-based index into `boundaries.rules[]`.
    pub rule_index: usize,
    /// Which field on the rule carries the unknown name.
    pub kind: ZoneReferenceKind,
    /// The unknown zone name as authored.
    pub zone_name: String,
}

/// One offending redundant-root-prefix pattern in a `boundaries.zones[]` entry.
///
/// Patterns are resolved relative to the zone `root`, so prefixing the pattern
/// with the same root double-prefixes the path and never matches a real file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedundantRootPrefix {
    /// Name of the zone whose pattern redundantly includes its root.
    pub zone_name: String,
    /// The offending pattern as authored.
    pub pattern: String,
    /// The normalized root that the pattern redundantly repeats.
    pub root: String,
}

/// Aggregated boundary-config validation error for `FallowConfig::validate_resolved_boundaries`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ZoneValidationError {
    /// A `boundaries.rules[]` entry references a zone NOT present in
    /// `boundaries.zones[]` (post-preset-expansion and post-auto-discover).
    UnknownZoneReference(UnknownZoneRef),
    /// A `boundaries.zones[].patterns[]` entry redundantly prefixes its
    /// pattern with the zone `root`.
    RedundantRootPrefix(RedundantRootPrefix),
}

impl fmt::Display for ZoneValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownZoneReference(err) => write!(
                f,
                "boundaries.rules[{}].{}: references undefined zone '{}'",
                err.rule_index,
                err.kind.config_field(),
                err.zone_name,
            ),
            Self::RedundantRootPrefix(err) => write!(
                f,
                "FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX: zone '{}': pattern '{}' starts with the zone root '{}'. Patterns are now resolved relative to root; remove the redundant prefix from the pattern.",
                err.zone_name, err.pattern, err.root,
            ),
        }
    }
}

impl std::error::Error for ZoneValidationError {}

/// Built-in architecture presets.
///
/// Each preset expands into a set of zones and import rules for a common
/// architecture pattern. User-defined zones and rules merge on top of the
/// preset defaults (zones with the same name replace the preset zone;
/// rules with the same `from` replace the preset rule).
///
/// # Examples
///
/// ```
/// use fallow_config::BoundaryPreset;
///
/// let preset: BoundaryPreset = serde_json::from_str(r#""layered""#).unwrap();
/// assert!(matches!(preset, BoundaryPreset::Layered));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum BoundaryPreset {
    /// Classic layered architecture: presentation → application → domain ← infrastructure.
    /// Infrastructure may also import from application (common in DI frameworks).
    Layered,
    /// Hexagonal / ports-and-adapters: adapters → ports → domain.
    Hexagonal,
    /// Feature-Sliced Design: app > pages > widgets > features > entities > shared.
    /// Each layer may only import from layers below it.
    FeatureSliced,
    /// Bulletproof React: app → features → shared + server.
    /// Feature modules are isolated from each other via `autoDiscover`: every
    /// immediate child of `src/features/` becomes its own `features/<name>` zone,
    /// and cross-feature imports are reported as boundary violations.
    /// Top-level files in `src/features/` are classified by the logical
    /// `features` parent zone, so barrels can re-export child features while
    /// non-barrel top-level files still obey the `features` boundary rule.
    Bulletproof,
}

impl BoundaryPreset {
    /// Expand the preset into default zones and rules.
    ///
    /// `source_root` is the directory prefix for zone patterns (e.g., `"src"`, `"lib"`).
    /// Patterns are generated as `{source_root}/{zone_name}/**`.
    #[must_use]
    pub fn default_config(&self, source_root: &str) -> (Vec<BoundaryZone>, Vec<BoundaryRule>) {
        match self {
            Self::Layered => Self::layered_config(source_root),
            Self::Hexagonal => Self::hexagonal_config(source_root),
            Self::FeatureSliced => Self::feature_sliced_config(source_root),
            Self::Bulletproof => Self::bulletproof_config(source_root),
        }
    }

    fn zone(name: &str, source_root: &str) -> BoundaryZone {
        BoundaryZone {
            name: name.to_owned(),
            patterns: vec![format!("{source_root}/{name}/**")],
            auto_discover: vec![],
            root: None,
        }
    }

    fn rule(from: &str, allow: &[&str]) -> BoundaryRule {
        BoundaryRule {
            from: from.to_owned(),
            allow: allow.iter().map(|s| (*s).to_owned()).collect(),
            allow_type_only: Vec::new(),
        }
    }

    fn layered_config(source_root: &str) -> (Vec<BoundaryZone>, Vec<BoundaryRule>) {
        let zones = vec![
            Self::zone("presentation", source_root),
            Self::zone("application", source_root),
            Self::zone("domain", source_root),
            Self::zone("infrastructure", source_root),
        ];
        let rules = vec![
            Self::rule("presentation", &["application"]),
            Self::rule("application", &["domain"]),
            Self::rule("domain", &[]),
            Self::rule("infrastructure", &["domain", "application"]),
        ];
        (zones, rules)
    }

    fn hexagonal_config(source_root: &str) -> (Vec<BoundaryZone>, Vec<BoundaryRule>) {
        let zones = vec![
            Self::zone("adapters", source_root),
            Self::zone("ports", source_root),
            Self::zone("domain", source_root),
        ];
        let rules = vec![
            Self::rule("adapters", &["ports"]),
            Self::rule("ports", &["domain"]),
            Self::rule("domain", &[]),
        ];
        (zones, rules)
    }

    fn feature_sliced_config(source_root: &str) -> (Vec<BoundaryZone>, Vec<BoundaryRule>) {
        let layer_names = ["app", "pages", "widgets", "features", "entities", "shared"];
        let zones = layer_names
            .iter()
            .map(|name| Self::zone(name, source_root))
            .collect();
        let rules = layer_names
            .iter()
            .enumerate()
            .map(|(i, name)| {
                let below: Vec<&str> = layer_names[i + 1..].to_vec();
                Self::rule(name, &below)
            })
            .collect();
        (zones, rules)
    }

    fn bulletproof_config(source_root: &str) -> (Vec<BoundaryZone>, Vec<BoundaryRule>) {
        let zones = vec![
            Self::zone("app", source_root),
            BoundaryZone {
                // Discovered child zones classify concrete feature modules
                // first; the parent pattern catches top-level feature files
                // such as barrels and shared types.
                name: "features".to_owned(),
                patterns: vec![format!("{source_root}/features/**")],
                auto_discover: vec![format!("{source_root}/features")],
                root: None,
            },
            BoundaryZone {
                name: "shared".to_owned(),
                patterns: [
                    "components",
                    "hooks",
                    "lib",
                    "utils",
                    "utilities",
                    "providers",
                    "shared",
                    "types",
                    "styles",
                    "i18n",
                ]
                .iter()
                .map(|dir| format!("{source_root}/{dir}/**"))
                .collect(),
                auto_discover: vec![],
                root: None,
            },
            Self::zone("server", source_root),
        ];
        let rules = vec![
            Self::rule("app", &["features", "shared", "server"]),
            Self::rule("features", &["shared", "server"]),
            Self::rule("server", &["shared"]),
            Self::rule("shared", &[]),
        ];
        (zones, rules)
    }
}

/// Architecture boundary configuration.
///
/// Defines zones (directory groupings) and rules (which zones may import from which).
/// Optionally uses a built-in preset as a starting point.
///
/// # Examples
///
/// ```
/// use fallow_config::BoundaryConfig;
///
/// let json = r#"{
///     "zones": [
///         { "name": "ui", "patterns": ["src/components/**"] },
///         { "name": "db", "patterns": ["src/db/**"] }
///     ],
///     "rules": [
///         { "from": "ui", "allow": ["db"] }
///     ]
/// }"#;
/// let config: BoundaryConfig = serde_json::from_str(json).unwrap();
/// assert_eq!(config.zones.len(), 2);
/// assert_eq!(config.rules.len(), 1);
/// ```
///
/// Using a preset:
///
/// ```
/// use fallow_config::BoundaryConfig;
///
/// let json = r#"{ "preset": "layered" }"#;
/// let mut config: BoundaryConfig = serde_json::from_str(json).unwrap();
/// config.expand("src");
/// assert_eq!(config.zones.len(), 4);
/// assert_eq!(config.rules.len(), 4);
/// ```
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BoundaryConfig {
    /// Built-in architecture preset. When set, expands into default zones and rules.
    /// User-defined zones and rules merge on top: zones with the same name replace
    /// the preset zone; rules with the same `from` replace the preset rule.
    /// Preset patterns use `{rootDir}/{zone}/**` where rootDir is auto-detected
    /// from tsconfig.json (falls back to `src`).
    /// Note: preset patterns are flat (`src/<zone>/**`). For monorepos with
    /// per-package source directories, define zones explicitly instead.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset: Option<BoundaryPreset>,
    /// Named zones mapping directory patterns to architectural layers.
    #[serde(default)]
    pub zones: Vec<BoundaryZone>,
    /// Import rules between zones. A zone with a rule entry can only import
    /// from the listed zones (plus itself). A zone without a rule entry is unrestricted.
    #[serde(default)]
    pub rules: Vec<BoundaryRule>,
}

/// A named zone grouping files by directory pattern.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BoundaryZone {
    /// Zone identifier referenced in rules (e.g., `"ui"`, `"database"`, `"shared"`).
    pub name: String,
    /// Glob patterns (relative to project root) that define zone membership.
    /// A file belongs to the first zone whose pattern matches.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub patterns: Vec<String>,
    /// Directories whose immediate child directories should become separate
    /// zones under this logical group.
    ///
    /// For example, `{ "name": "features", "autoDiscover": ["src/features"] }`
    /// creates zones such as `features/auth` and `features/billing`, each with
    /// a pattern for its own subtree. Rules that reference `features` expand to
    /// every discovered child zone. If `patterns` is also set, the parent zone
    /// remains as a fallback after discovered child zones.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub auto_discover: Vec<String>,
    /// Optional subtree scope for monorepo per-package boundaries.
    ///
    /// When set, the zone's `patterns` are matched against paths *relative*
    /// to this directory rather than the project root. At classification
    /// time, fallow checks that a candidate path starts with `root` and
    /// strips that prefix before glob-matching the patterns against the
    /// remainder. Files outside the subtree never match the zone.
    ///
    /// Useful for monorepos where each package has the same internal
    /// directory layout: instead of writing `packages/app/src/**` and
    /// `packages/core/src/**` (which collide on shared zone names), set
    /// `root: "packages/app/"` and `patterns: ["src/**"]` per package.
    ///
    /// Trailing slash and leading `./` are normalized; backslashes are
    /// converted to forward slashes. Patterns must NOT redundantly include
    /// the root prefix: `root: "packages/app/"` with
    /// `patterns: ["packages/app/src/**"]` is rejected with
    /// `FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX` because patterns are
    /// resolved relative to the root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root: Option<String>,
}

/// An import rule between zones.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BoundaryRule {
    /// The zone this rule applies to (the importing side).
    pub from: String,
    /// Zones that `from` is allowed to import from. Self-imports are always allowed.
    /// An empty list means the zone may not import from any other zone.
    #[serde(default)]
    pub allow: Vec<String>,
    /// Zones that `from` may type-only-import from even when not listed in
    /// `allow`. Mirrors the `allow` shape: a list of target zone names. A
    /// type-only import declaration (`import type {...}`, `import type * as ns`,
    /// or a per-specifier inline `type` qualifier on every named specifier) to a
    /// listed zone is not reported as a boundary violation. Mixed-specifier
    /// imports (`import { type Foo, Bar }`) that carry at least one value
    /// symbol still fire because the runtime dependency on `Bar` is real.
    /// Type-only re-exports (`export type { Foo } from "..."`) participate
    /// in the same allowance because they surface as edges flagged
    /// `is_type_only: true` and, like type-only imports, are erased at
    /// compile time.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow_type_only: Vec<String>,
}

/// Resolved boundary config with pre-compiled glob matchers.
#[derive(Debug, Default)]
pub struct ResolvedBoundaryConfig {
    /// Zones with compiled glob matchers for fast file classification.
    pub zones: Vec<ResolvedZone>,
    /// Rules indexed by source zone name.
    pub rules: Vec<ResolvedBoundaryRule>,
    /// Pre-expansion logical groups captured during `expand_auto_discover`,
    /// preserved here for observability (`fallow list --boundaries --format
    /// json`). One entry per `autoDiscover`-bearing zone in user-declaration
    /// order. Empty unless the user (or a preset) wrote at least one
    /// `autoDiscover`. See [`LogicalGroup`] for the per-entry shape.
    pub logical_groups: Vec<LogicalGroup>,
}

/// A user-declared zone that fanned out into one or more child zones via
/// `autoDiscover`. Surfaced verbatim through `fallow list --boundaries
/// --format json` so consumers (config UIs, Sankey renderers, agent-driven
/// config tooling, dashboards) can reconstruct the original grouping intent
/// after expansion has flattened the parent name out of `zones[]`.
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct LogicalGroup {
    /// Logical parent zone name as authored by the user (e.g. `"features"`).
    pub name: String,
    /// Discovered child zone names in stable directory-sorted order
    /// (e.g. `["features/auth", "features/billing"]`). Empty when the parent
    /// directory was empty or unreadable; `status` discriminates the two.
    pub children: Vec<String>,
    /// The exact `autoDiscover` strings the user wrote, preserved verbatim
    /// (no normalization). Round-trip tooling depends on byte-exact match
    /// against the user's config source.
    pub auto_discover: Vec<String>,
    /// Pre-expansion rule keyed on this parent zone name, captured before
    /// `expand_auto_discover` rewrote it into per-child rules. `None` when
    /// the user wrote no rule for the parent (the children are then
    /// unrestricted unless a per-child rule exists).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authored_rule: Option<AuthoredRule>,
    /// When the parent zone also carried explicit `patterns`, it stayed in
    /// `zones[]` after expansion as a fallback classifier. This is its name
    /// (always equal to [`Self::name`]). `None` when the parent had no
    /// patterns and was dropped from `zones[]` entirely. Lets consumers wire
    /// the logical-group entry to its zone twin without name-matching
    /// heuristics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback_zone: Option<String>,
    /// Position of the parent zone in the user's pre-expansion `zones[]`
    /// array. Enables byte-accurate config patches by agent tooling without
    /// re-parsing the user's config source.
    pub source_zone_index: usize,
    /// Why [`Self::children`] is what it is.
    pub status: LogicalGroupStatus,
    /// Parent zone indices whose declarations were merged into this group
    /// because they shared a name (`{ name: "features", autoDiscover: [...] }`
    /// declared twice). `None` on the common case (single declaration);
    /// `Some([i, j, ...])` when at least two declarations were merged. The
    /// FIRST entry equals [`Self::source_zone_index`]; subsequent entries are
    /// the positions of the additional declarations in user-declaration order.
    /// Surfaced in JSON so consumers (config-edit agents, config-hygiene
    /// dashboards) can detect duplicates that `tracing::warn!` would otherwise
    /// hide from `--format json` consumption.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merged_from: Option<Vec<usize>>,
    /// The parent zone's `root` (subtree scope) as the user authored it,
    /// echoed onto the logical group so monorepo-aware tooling can tell
    /// whether `root` was set on the parent (and inherited by every
    /// discovered child) or set per-child. `None` when the parent had no
    /// `root` field. The string is verbatim from the user's config (not
    /// the post-`normalize_zone_root` form) for byte-exact round-trip.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub original_zone_root: Option<String>,
    /// For each entry in [`Self::children`], the index into
    /// [`Self::auto_discover`] of the path that produced it (or the FIRST
    /// path that produced it when multiple `autoDiscover` entries each yield
    /// the same child name). Empty when only one `autoDiscover` path was
    /// authored (every child trivially maps to index 0); populated only when
    /// the parent has two or more `autoDiscover` entries so consumers can
    /// attribute children to specific source directories. The length equals
    /// `children.len()` when populated.
    ///
    /// `#[serde(default)]` pairs with `skip_serializing_if` so the JSON
    /// runtime omits this field on the common single-path case AND the
    /// derived schema marks it optional (schemars 1 promotes any field with a
    /// `serde(default)` attribute out of `required`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub child_source_indices: Vec<usize>,
}

/// Discovery outcome for a [`LogicalGroup`]. Discriminates "no children" into
/// "the directory exists and is empty" versus "at least one `autoDiscover`
/// path was invalid or unreadable", so consumers can render an actionable
/// hint instead of "0 children, mystery".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LogicalGroupStatus {
    /// At least one child zone was discovered.
    Ok,
    /// Every `autoDiscover` path resolved to a readable directory, but
    /// none contained child directories.
    Empty,
    /// At least one `autoDiscover` path was malformed (contained `..`,
    /// absolute) or did not resolve to a readable directory, and zero
    /// children were discovered across all paths. When a mix of invalid and
    /// valid paths produces children, status is [`Self::Ok`] instead.
    InvalidPath,
}

/// Pre-expansion `from`-rule preserved on a [`LogicalGroup`]. Surfaces the
/// user's original intent (`{ from: "features", allow: ["shared"] }`) even
/// after `expand_auto_discover` rewrote it into per-child rules
/// (`features/auth -> shared`, `features/billing -> shared`).
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AuthoredRule {
    /// Pre-expansion `allow` list as the user wrote it.
    pub allow: Vec<String>,
    /// Pre-expansion `allowTypeOnly` list as the user wrote it. Omitted
    /// from JSON output when empty; `serde(default)` keeps the derived
    /// schema in lock-step (schemars 1 marks any field with a
    /// `serde(default)` attribute as non-required).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow_type_only: Vec<String>,
}

/// A zone with pre-compiled glob matchers.
#[derive(Debug)]
pub struct ResolvedZone {
    /// Zone identifier.
    pub name: String,
    /// Pre-compiled glob matchers for zone membership.
    /// When `root` is set, matchers are applied to the path with the
    /// `root` prefix stripped (subtree-relative patterns).
    pub matchers: Vec<globset::GlobMatcher>,
    /// Normalized subtree scope (e.g. `"packages/app/"`). When present,
    /// only paths starting with this prefix can match this zone, and the
    /// prefix is stripped before glob matching. Forward slashes only,
    /// always trailing slash. `None` means patterns are matched against
    /// the project-root-relative path as-is.
    pub root: Option<String>,
}

/// A resolved boundary rule.
#[derive(Debug)]
pub struct ResolvedBoundaryRule {
    /// The zone this rule restricts.
    pub from_zone: String,
    /// Zones that `from_zone` is allowed to import from.
    pub allowed_zones: Vec<String>,
    /// Zones that `from_zone` may type-only-import from even when not listed
    /// in `allowed_zones`. See `BoundaryRule::allow_type_only`.
    pub allow_type_only_zones: Vec<String>,
}

impl BoundaryConfig {
    /// Whether any boundaries are configured (including via preset).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.preset.is_none() && self.zones.is_empty()
    }

    /// Expand the preset (if set) into zones and rules, merging user overrides on top.
    ///
    /// `source_root` is the directory prefix for preset zone patterns (e.g., `"src"`).
    /// After expansion, `self.preset` is cleared and all zones/rules are explicit.
    ///
    /// Merge semantics:
    /// - User zones with the same name as a preset zone **replace** the preset zone entirely.
    /// - User rules with the same `from` as a preset rule **replace** the preset rule.
    /// - User zones/rules with new names **add** to the preset set.
    pub fn expand(&mut self, source_root: &str) {
        let Some(preset) = self.preset.take() else {
            return;
        };

        let (preset_zones, preset_rules) = preset.default_config(source_root);

        // Build set of user-defined zone names for override detection.
        let user_zone_names: rustc_hash::FxHashSet<&str> =
            self.zones.iter().map(|z| z.name.as_str()).collect();

        // Start with preset zones, replacing any that the user overrides.
        let mut merged_zones: Vec<BoundaryZone> = preset_zones
            .into_iter()
            .filter(|pz| {
                if user_zone_names.contains(pz.name.as_str()) {
                    tracing::info!(
                        "boundary preset: user zone '{}' replaces preset zone",
                        pz.name
                    );
                    false
                } else {
                    true
                }
            })
            .collect();
        // Append all user zones (both overrides and additions).
        merged_zones.append(&mut self.zones);
        self.zones = merged_zones;

        // Build set of user-defined rule `from` names for override detection.
        let user_rule_sources: rustc_hash::FxHashSet<&str> =
            self.rules.iter().map(|r| r.from.as_str()).collect();

        let mut merged_rules: Vec<BoundaryRule> = preset_rules
            .into_iter()
            .filter(|pr| {
                if user_rule_sources.contains(pr.from.as_str()) {
                    tracing::info!(
                        "boundary preset: user rule for '{}' replaces preset rule",
                        pr.from
                    );
                    false
                } else {
                    true
                }
            })
            .collect();
        merged_rules.append(&mut self.rules);
        self.rules = merged_rules;
    }

    /// Expand auto-discovered boundary groups into concrete child zones.
    ///
    /// A zone with `autoDiscover: ["src/features"]` discovers the immediate
    /// child directories below `src/features` and emits child zones named
    /// `zone_name/child`. Rules that reference the logical parent are expanded
    /// to all discovered children. If the parent also has explicit `patterns`,
    /// it is kept after the children as a fallback so child directories remain
    /// isolated by first-match classification. The parent fallback rule
    /// automatically allows its discovered children so top-level barrels can
    /// re-export child modules without relaxing sibling isolation on the child
    /// rules.
    ///
    /// Returns one [`LogicalGroup`] per pre-expansion zone that carried a
    /// non-empty `autoDiscover`, in user-declaration order. The caller (the
    /// resolution pipeline) stashes the result onto
    /// [`ResolvedBoundaryConfig::logical_groups`] for `fallow list
    /// --boundaries --format json` to render. Discarding the return is fine
    /// for callers that only need the expansion side effect (classification);
    /// the data is regenerated on the next run.
    ///
    /// Duplicate parent zone name behavior: when two `BoundaryZone`
    /// declarations share a name and both carry `autoDiscover`, their
    /// discovered children merge into a single `LogicalGroup` whose
    /// `auto_discover` concatenates both source path lists in declaration
    /// order. This mirrors the existing rule-side merge behavior (both rules
    /// expand to the same union of child names). A `tracing::warn!` surfaces
    /// the duplicate at config-load time so the user can deduplicate the
    /// source; the merged behavior is a soft default rather than a hard
    /// rejection so existing configs continue to load.
    pub fn expand_auto_discover(&mut self, project_root: &Path) -> Vec<LogicalGroup> {
        if self.zones.iter().all(|zone| zone.auto_discover.is_empty()) {
            return Vec::new();
        }

        let original_zones = std::mem::take(&mut self.zones);
        let mut expanded_zones = Vec::new();
        let mut group_expansions: rustc_hash::FxHashMap<String, Vec<String>> =
            rustc_hash::FxHashMap::default();
        // Preserves user-declaration order: `FxHashMap` iteration is not
        // insertion-ordered, and consumers (snapshot tests, diff-based
        // dashboards) depend on stable JSON output across runs.
        let mut group_drafts: Vec<LogicalGroupDraft> = Vec::new();

        for (source_zone_index, mut zone) in original_zones.into_iter().enumerate() {
            if zone.auto_discover.is_empty() {
                expanded_zones.push(zone);
                continue;
            }

            let group_name = zone.name.clone();
            // Capture the user's verbatim `autoDiscover` strings before
            // discovery normalizes them; round-trip tooling depends on
            // byte-exact match against the source.
            let raw_auto_discover = zone.auto_discover.clone();
            let original_zone_root = zone.root.clone();
            let DiscoveryOutcome {
                zones: discovered_zones,
                source_indices: discovered_source_indices,
                had_invalid_path,
            } = discover_child_zones(project_root, &zone);
            let discovered_count = discovered_zones.len();
            let mut expanded_names: Vec<String> = discovered_zones
                .iter()
                .map(|child| child.name.clone())
                .collect();
            let child_names_only = expanded_names.clone();
            for child_zone in discovered_zones {
                merge_zone_by_name(&mut expanded_zones, child_zone);
            }

            let fallback_zone = if zone.patterns.is_empty() {
                None
            } else {
                expanded_names.push(group_name.clone());
                zone.auto_discover.clear();
                merge_zone_by_name(&mut expanded_zones, zone);
                Some(group_name.clone())
            };

            if !expanded_names.is_empty() {
                group_expansions
                    .entry(group_name.clone())
                    .or_default()
                    .extend(expanded_names);
            }

            let status = if discovered_count > 0 {
                LogicalGroupStatus::Ok
            } else if had_invalid_path {
                LogicalGroupStatus::InvalidPath
            } else {
                LogicalGroupStatus::Empty
            };

            // Merge into existing draft if the user declared the same parent
            // name twice. Concatenates `auto_discover`, dedupes `children`
            // against the existing set so a duplicate declaration discovering
            // the same child does not double-count via `file_count` lookup,
            // preserves the FIRST `source_zone_index` and `original_zone_root`,
            // shifts the new batch's `child_source_indices` by the existing
            // `auto_discover.len()` so they continue to address the
            // post-concatenation array (and drops indices for children
            // already present, since attribution belongs to the first
            // producer), and appends the new `source_zone_index` to
            // `merged_from` so the duplicate is visible in JSON output.
            if let Some(existing) = group_drafts.iter_mut().find(|d| d.name == group_name) {
                tracing::warn!(
                    "boundary zone '{}' is declared multiple times with autoDiscover; merging discovered children",
                    group_name
                );
                let auto_discover_offset = existing.auto_discover.len();
                existing.auto_discover.extend(raw_auto_discover);
                let existing_children: rustc_hash::FxHashSet<String> =
                    existing.children.iter().cloned().collect();
                for (idx, name) in child_names_only.iter().enumerate() {
                    if existing_children.contains(name) {
                        continue;
                    }
                    existing.children.push(name.clone());
                    existing
                        .child_source_indices
                        .push(discovered_source_indices[idx] + auto_discover_offset);
                }
                if existing.fallback_zone.is_none() {
                    existing.fallback_zone = fallback_zone;
                }
                existing.status = merge_status(existing.status, status);
                let chain = existing
                    .merged_from
                    .get_or_insert_with(|| vec![existing.source_zone_index]);
                chain.push(source_zone_index);
            } else {
                group_drafts.push(LogicalGroupDraft {
                    name: group_name,
                    children: child_names_only,
                    auto_discover: raw_auto_discover,
                    fallback_zone,
                    source_zone_index,
                    status,
                    merged_from: None,
                    original_zone_root,
                    child_source_indices: discovered_source_indices,
                });
            }
        }

        self.zones = expanded_zones;

        // Index draft names so we can look up the authored rule per logical
        // group regardless of whether the group produced any children.
        // Groups whose discovery was Empty / InvalidPath contribute NO entry
        // to `group_expansions` (no children means no rule expansion), but
        // their authored rule still belongs on the surfaced LogicalGroup so
        // consumers see the user's intent even when discovery turned up
        // empty.
        let draft_names: rustc_hash::FxHashSet<&str> =
            group_drafts.iter().map(|d| d.name.as_str()).collect();

        // Capture authored rules BEFORE `original_rules` is consumed below.
        // The match-up is by `rule.from == group_name`; the last matching
        // rule wins to mirror `dedupe_rules_keep_last` semantics.
        let original_rules = std::mem::take(&mut self.rules);
        let authored_rules: rustc_hash::FxHashMap<&str, AuthoredRule> = original_rules
            .iter()
            .filter(|rule| draft_names.contains(rule.from.as_str()))
            .map(|rule| {
                (
                    rule.from.as_str(),
                    AuthoredRule {
                        allow: rule.allow.clone(),
                        allow_type_only: rule.allow_type_only.clone(),
                    },
                )
            })
            .collect();

        let logical_groups: Vec<LogicalGroup> = group_drafts
            .into_iter()
            .map(|draft| {
                // `child_source_indices` is only signal-bearing when the
                // parent has two or more `auto_discover` paths; with one
                // path every child trivially has index 0. Skip the noise
                // on the common case so the JSON stays tight; the field
                // is `#[serde(default, skip_serializing_if = "Vec::is_empty")]`.
                let child_source_indices = if draft.auto_discover.len() > 1 {
                    draft.child_source_indices
                } else {
                    Vec::new()
                };
                LogicalGroup {
                    authored_rule: authored_rules.get(draft.name.as_str()).cloned(),
                    name: draft.name,
                    children: draft.children,
                    auto_discover: draft.auto_discover,
                    fallback_zone: draft.fallback_zone,
                    source_zone_index: draft.source_zone_index,
                    status: draft.status,
                    merged_from: draft.merged_from,
                    original_zone_root: draft.original_zone_root,
                    child_source_indices,
                }
            })
            .collect();

        if group_expansions.is_empty() {
            // No groups produced any children, so rule expansion is a no-op;
            // restore the rules verbatim. `logical_groups` still carries the
            // Empty / InvalidPath drafts so consumers can render the user's
            // grouping intent and act on the "discovery turned up nothing"
            // signal.
            self.rules = original_rules;
            return logical_groups;
        }

        self.rules = expand_rules_for_groups(original_rules, &group_expansions);
        logical_groups
    }
}

/// Merge a discovered (or fallback) zone into the post-expansion zones
/// vector by name. A naive `expanded_zones.push(zone)` duplicates entries
/// when the user declared the same parent name twice (each iteration of the
/// outer expansion loop re-runs discovery on its own `autoDiscover` paths
/// and would push the same child names again, producing duplicates in
/// `zones[]` AND triggering the `file_count` summation in
/// `compute_boundary_data` to double-count each child). Merging by name
/// keeps `zones[]` unique and unifies the patterns from both declarations
/// on the same `BoundaryZone`. Existing patterns are preserved verbatim;
/// only NEW patterns are appended.
fn merge_zone_by_name(expanded_zones: &mut Vec<BoundaryZone>, zone: BoundaryZone) {
    if let Some(existing) = expanded_zones.iter_mut().find(|z| z.name == zone.name) {
        for pattern in zone.patterns {
            if !existing.patterns.contains(&pattern) {
                existing.patterns.push(pattern);
            }
        }
    } else {
        expanded_zones.push(zone);
    }
}

/// Rewrite the user's pre-expansion rules to reference the discovered child
/// zones in place of the logical parent. Three rule shapes are produced:
///
/// 1. Rules whose `from` is the parent group expand into one explicit rule
///    per child (or one for the parent fallback when the parent kept its
///    `patterns`).
/// 2. Rules whose `allow` references a group expand to allow every child
///    of that group.
/// 3. Rules untouched by group expansion pass through unchanged.
///
/// Extracted out of [`BoundaryConfig::expand_auto_discover`] so the
/// orchestrator stays under the SIG unit-size threshold; the body itself
/// is unchanged from the pre-#373 inline form.
fn expand_rules_for_groups(
    original_rules: Vec<BoundaryRule>,
    group_expansions: &rustc_hash::FxHashMap<String, Vec<String>>,
) -> Vec<BoundaryRule> {
    let mut generated_rules = Vec::new();
    let mut explicit_rules = Vec::new();
    for rule in original_rules {
        let allow = expand_rule_allow(&rule.allow, group_expansions);
        let allow_type_only = expand_rule_allow(&rule.allow_type_only, group_expansions);

        if let Some(from_zones) = group_expansions.get(&rule.from) {
            for from in from_zones {
                let (allow, allow_type_only) = if from == &rule.from {
                    (
                        expand_parent_fallback_allow(&allow, from_zones, &rule.from),
                        allow_type_only.clone(),
                    )
                } else {
                    (
                        expand_generated_child_allow(&rule.allow, group_expansions, &rule.from),
                        expand_generated_child_allow(
                            &rule.allow_type_only,
                            group_expansions,
                            &rule.from,
                        ),
                    )
                };
                let expanded_rule = BoundaryRule {
                    from: from.clone(),
                    allow,
                    allow_type_only,
                };
                if from == &rule.from {
                    explicit_rules.push(expanded_rule);
                } else {
                    generated_rules.push(expanded_rule);
                }
            }
        } else {
            explicit_rules.push(BoundaryRule {
                from: rule.from,
                allow,
                allow_type_only,
            });
        }
    }

    let mut expanded_rules = dedupe_rules_keep_last(generated_rules);
    expanded_rules.extend(dedupe_rules_keep_last(explicit_rules));
    dedupe_rules_keep_last(expanded_rules)
}

impl BoundaryConfig {
    /// Return the preset name if one is configured but not yet expanded.
    #[must_use]
    pub fn preset_name(&self) -> Option<&str> {
        self.preset.as_ref().map(|p| match p {
            BoundaryPreset::Layered => "layered",
            BoundaryPreset::Hexagonal => "hexagonal",
            BoundaryPreset::FeatureSliced => "feature-sliced",
            BoundaryPreset::Bulletproof => "bulletproof",
        })
    }

    /// Validate that no zone's pattern redundantly includes its `root`
    /// prefix. Patterns are resolved relative to the zone root, so prefixing
    /// the pattern with the same root double-prefixes the path and never
    /// matches.
    ///
    /// The rendered diagnostic carries the legacy
    /// `FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX` tag via
    /// [`ZoneValidationError`]'s `Display` impl, so CI logs grepping for the
    /// old text continue to work.
    #[must_use]
    pub fn validate_root_prefixes(&self) -> Vec<RedundantRootPrefix> {
        let mut errors = Vec::new();
        for zone in &self.zones {
            let Some(raw_root) = zone.root.as_deref() else {
                continue;
            };
            let normalized = normalize_zone_root(raw_root);
            // Skip empty-root zones: `""`, `"."`, and `"./"` all normalize to
            // `""`, which behaves as no root at classification time. Without
            // this guard `starts_with("")` is always true and every pattern
            // produces a spurious redundant-prefix error.
            if normalized.is_empty() {
                continue;
            }
            for pattern in &zone.patterns {
                let normalized_pattern = pattern.replace('\\', "/");
                let stripped = normalized_pattern
                    .strip_prefix("./")
                    .unwrap_or(&normalized_pattern);
                if stripped.starts_with(&normalized) {
                    errors.push(RedundantRootPrefix {
                        zone_name: zone.name.clone(),
                        pattern: pattern.clone(),
                        root: normalized.clone(),
                    });
                }
            }
        }
        errors
    }

    /// Validate that all zone names referenced in rules are defined in `zones`.
    ///
    /// Walks every zone-reference surface on `BoundaryRule`: `from`, `allow`,
    /// and `allow_type_only`. An unknown zone in `allow_type_only` silently
    /// behaves as "not allowed" at runtime, so it MUST surface here for parity
    /// with the existing `allow`-side diagnostic.
    #[must_use]
    pub fn validate_zone_references(&self) -> Vec<UnknownZoneRef> {
        let zone_names: rustc_hash::FxHashSet<&str> =
            self.zones.iter().map(|z| z.name.as_str()).collect();

        let mut errors = Vec::new();
        for (i, rule) in self.rules.iter().enumerate() {
            if !zone_names.contains(rule.from.as_str()) {
                errors.push(UnknownZoneRef {
                    rule_index: i,
                    kind: ZoneReferenceKind::From,
                    zone_name: rule.from.clone(),
                });
            }
            for allowed in &rule.allow {
                if !zone_names.contains(allowed.as_str()) {
                    errors.push(UnknownZoneRef {
                        rule_index: i,
                        kind: ZoneReferenceKind::Allow,
                        zone_name: allowed.clone(),
                    });
                }
            }
            for allowed_type_only in &rule.allow_type_only {
                if !zone_names.contains(allowed_type_only.as_str()) {
                    errors.push(UnknownZoneRef {
                        rule_index: i,
                        kind: ZoneReferenceKind::AllowTypeOnly,
                        zone_name: allowed_type_only.clone(),
                    });
                }
            }
        }
        errors
    }

    /// Resolve into compiled form with pre-built glob matchers.
    ///
    /// User patterns were validated at config load time
    /// (see `FallowConfig::validate_user_globs`).
    #[must_use]
    pub fn resolve(&self) -> ResolvedBoundaryConfig {
        let zones = self
            .zones
            .iter()
            .map(|zone| {
                let matchers = zone
                    .patterns
                    .iter()
                    .map(|pattern| {
                        Glob::new(pattern)
                            .expect("boundaries.zones[].patterns was validated at config load time")
                            .compile_matcher()
                    })
                    .collect();
                let root = zone.root.as_deref().map(normalize_zone_root);
                ResolvedZone {
                    name: zone.name.clone(),
                    matchers,
                    root,
                }
            })
            .collect();

        let rules = self
            .rules
            .iter()
            .map(|rule| ResolvedBoundaryRule {
                from_zone: rule.from.clone(),
                allowed_zones: rule.allow.clone(),
                allow_type_only_zones: rule.allow_type_only.clone(),
            })
            .collect();

        ResolvedBoundaryConfig {
            zones,
            rules,
            // `expand_auto_discover` is the only producer; the resolution
            // pipeline (`crates/config/src/config/resolution.rs`) assigns the
            // returned `Vec<LogicalGroup>` onto the resolved boundaries after
            // `resolve()` runs. `resolve()` itself has no view of the
            // pre-expansion state, so it leaves the field empty here.
            logical_groups: Vec::new(),
        }
    }
}

/// Normalize a zone `root` string into the canonical form used at
/// classification time: forward slashes, no leading `./`, always a
/// trailing slash. Empty / `"."` / `"./"` collapse to `""` which means
/// "subtree is the project root" and effectively behaves like no root.
fn normalize_zone_root(raw: &str) -> String {
    let with_slashes = raw.replace('\\', "/");
    let trimmed = with_slashes.trim_start_matches("./");
    let no_dot = if trimmed == "." { "" } else { trimmed };
    if no_dot.is_empty() {
        String::new()
    } else if no_dot.ends_with('/') {
        no_dot.to_owned()
    } else {
        format!("{no_dot}/")
    }
}

fn normalize_auto_discover_dir(raw: &str) -> Option<String> {
    let with_slashes = raw.replace('\\', "/");
    let trimmed = with_slashes.trim_start_matches("./").trim_end_matches('/');
    if trimmed.starts_with('/') || trimmed.split('/').any(|part| part == "..") {
        None
    } else if trimmed == "." {
        Some(String::new())
    } else {
        Some(trimmed.to_owned())
    }
}

fn join_relative_path(prefix: &str, suffix: &str) -> String {
    match (prefix.is_empty(), suffix.is_empty()) {
        (true, true) => String::new(),
        (true, false) => suffix.to_owned(),
        (false, true) => prefix.trim_end_matches('/').to_owned(),
        (false, false) => format!("{}/{}", prefix.trim_end_matches('/'), suffix),
    }
}

/// Discovery result for a single auto-discover zone. Carries the discovered
/// child `BoundaryZone`s, a flag for "at least one `autoDiscover` path was
/// malformed or unreadable" (distinguishes [`LogicalGroupStatus::InvalidPath`]
/// from [`LogicalGroupStatus::Empty`]), and parallel-to-zones
/// `source_indices` recording which `autoDiscover` entry produced each child
/// (FIRST producer wins when two paths yield the same child name).
struct DiscoveryOutcome {
    zones: Vec<BoundaryZone>,
    source_indices: Vec<usize>,
    had_invalid_path: bool,
}

/// Intermediate accumulator for a [`LogicalGroup`] before its
/// [`AuthoredRule`] is resolved (rules are not consumed until after the zone
/// loop completes, so the rule lookup happens in a second pass).
struct LogicalGroupDraft {
    name: String,
    children: Vec<String>,
    auto_discover: Vec<String>,
    fallback_zone: Option<String>,
    source_zone_index: usize,
    status: LogicalGroupStatus,
    /// `None` until a second declaration with the same `name` is merged in;
    /// then `Some(vec![first_index, ..])` with one entry per merged
    /// declaration in user-declaration order.
    merged_from: Option<Vec<usize>>,
    /// Echo of the parent zone's `root` field as the user authored it
    /// (verbatim, not normalized). On duplicate-merge, the FIRST declaration
    /// wins (consistent with `source_zone_index`).
    original_zone_root: Option<String>,
    /// Parallel to `children`: for child at index `i`, the index into
    /// `auto_discover` of the path that produced it (FIRST producer wins on
    /// collisions). When merging duplicate parent declarations, indices from
    /// the second batch are shifted by the first batch's `auto_discover.len()`
    /// so they continue to address the concatenated `auto_discover` array.
    child_source_indices: Vec<usize>,
}

/// Merge two `LogicalGroupStatus` values when a duplicate parent zone name
/// is encountered: `Ok` wins (at least one child was discovered),
/// `InvalidPath` beats `Empty` (a malformed/unreadable path is a louder
/// signal than "no subdirs"), and otherwise we keep the existing status.
const fn merge_status(existing: LogicalGroupStatus, new: LogicalGroupStatus) -> LogicalGroupStatus {
    match (existing, new) {
        (LogicalGroupStatus::Ok, _) | (_, LogicalGroupStatus::Ok) => LogicalGroupStatus::Ok,
        (LogicalGroupStatus::InvalidPath, _) | (_, LogicalGroupStatus::InvalidPath) => {
            LogicalGroupStatus::InvalidPath
        }
        (LogicalGroupStatus::Empty, LogicalGroupStatus::Empty) => LogicalGroupStatus::Empty,
    }
}

fn discover_child_zones(project_root: &Path, zone: &BoundaryZone) -> DiscoveryOutcome {
    let mut zones_by_name: rustc_hash::FxHashMap<String, BoundaryZone> =
        rustc_hash::FxHashMap::default();
    // Tracks which `autoDiscover` path index FIRST produced each child zone
    // name. When two paths yield the same child name, the first producer
    // wins (the merged `BoundaryZone` accumulates patterns from both but
    // attribution stays stable).
    let mut first_source_index: rustc_hash::FxHashMap<String, usize> =
        rustc_hash::FxHashMap::default();
    let normalized_root = zone
        .root
        .as_deref()
        .map(normalize_zone_root)
        .unwrap_or_default();
    let mut had_invalid_path = false;

    for (source_index, raw_dir) in zone.auto_discover.iter().enumerate() {
        let Some(discover_dir) = normalize_auto_discover_dir(raw_dir) else {
            tracing::warn!(
                "invalid boundary autoDiscover path '{}' in zone '{}': paths must be project-relative and must not contain '..'",
                raw_dir,
                zone.name
            );
            had_invalid_path = true;
            continue;
        };

        let fs_relative = join_relative_path(&normalized_root, &discover_dir);
        let absolute_dir = if fs_relative.is_empty() {
            project_root.to_path_buf()
        } else {
            project_root.join(&fs_relative)
        };
        let Ok(entries) = std::fs::read_dir(&absolute_dir) else {
            tracing::warn!(
                "boundary zone '{}' autoDiscover path '{}' did not resolve to a readable directory",
                zone.name,
                raw_dir
            );
            had_invalid_path = true;
            continue;
        };

        let mut children: Vec<_> = entries
            .filter_map(Result::ok)
            .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
            .collect();
        children.sort_by_key(|entry| entry.file_name());

        for child in children {
            let child_name = child.file_name().to_string_lossy().to_string();
            if child_name.is_empty() {
                continue;
            }

            let zone_name = format!("{}/{}", zone.name, child_name);
            let child_pattern = format!("{}/**", join_relative_path(&discover_dir, &child_name));
            let entry = zones_by_name
                .entry(zone_name.clone())
                .or_insert_with(|| BoundaryZone {
                    name: zone_name.clone(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: zone.root.clone(),
                });
            if !entry
                .patterns
                .iter()
                .any(|pattern| pattern == &child_pattern)
            {
                entry.patterns.push(child_pattern);
            }
            first_source_index.entry(zone_name).or_insert(source_index);
        }
    }

    let mut zones: Vec<_> = zones_by_name.into_values().collect();
    zones.sort_by(|a, b| a.name.cmp(&b.name));
    let source_indices: Vec<usize> = zones
        .iter()
        .map(|z| {
            // Every entry inserted into `zones_by_name` was also inserted
            // into `first_source_index` in the same loop body, so this lookup
            // is infallible. Fall back to 0 defensively for any future
            // refactor that decouples the two maps.
            first_source_index
                .get(z.name.as_str())
                .copied()
                .unwrap_or(0)
        })
        .collect();
    DiscoveryOutcome {
        zones,
        source_indices,
        had_invalid_path,
    }
}

fn expand_rule_allow(
    allow: &[String],
    group_expansions: &rustc_hash::FxHashMap<String, Vec<String>>,
) -> Vec<String> {
    let mut expanded = Vec::new();
    for zone in allow {
        if let Some(expansion) = group_expansions.get(zone) {
            expanded.extend(expansion.iter().cloned());
        } else {
            expanded.push(zone.clone());
        }
    }
    dedupe_preserving_order(expanded)
}

fn expand_parent_fallback_allow(
    allow: &[String],
    from_zones: &[String],
    parent_name: &str,
) -> Vec<String> {
    let mut expanded = allow.to_vec();
    expanded.extend(
        from_zones
            .iter()
            .filter(|from_zone| from_zone.as_str() != parent_name)
            .cloned(),
    );
    dedupe_preserving_order(expanded)
}

fn expand_generated_child_allow(
    allow: &[String],
    group_expansions: &rustc_hash::FxHashMap<String, Vec<String>>,
    source_group: &str,
) -> Vec<String> {
    let mut expanded = Vec::new();
    for zone in allow {
        if zone == source_group {
            if group_expansions
                .get(source_group)
                .is_some_and(|from_zones| from_zones.iter().any(|from_zone| from_zone == zone))
            {
                expanded.push(zone.clone());
            }
        } else if let Some(expansion) = group_expansions.get(zone) {
            expanded.extend(expansion.iter().cloned());
        } else {
            expanded.push(zone.clone());
        }
    }
    dedupe_preserving_order(expanded)
}

fn dedupe_preserving_order(values: Vec<String>) -> Vec<String> {
    let mut seen = rustc_hash::FxHashSet::default();
    values
        .into_iter()
        .filter(|value| seen.insert(value.clone()))
        .collect()
}

fn dedupe_rules_keep_last(rules: Vec<BoundaryRule>) -> Vec<BoundaryRule> {
    let mut seen = rustc_hash::FxHashSet::default();
    let mut deduped: Vec<_> = rules
        .into_iter()
        .rev()
        .filter(|rule| seen.insert(rule.from.clone()))
        .collect();
    deduped.reverse();
    deduped
}

impl ResolvedBoundaryConfig {
    /// Whether any boundaries are configured.
    ///
    /// Considers `logical_groups` too: when every `autoDiscover` zone
    /// produced zero children, `zones` is empty but the user authored a
    /// boundaries section that should still be surfaced (so `fallow list
    /// --boundaries` can render the `Empty` / `InvalidPath` status to the
    /// user). Without this, the whole boundaries block silently disappears
    /// from the output the moment discovery finds nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.zones.is_empty() && self.logical_groups.is_empty()
    }

    /// Classify a file path into a zone. Returns the first matching zone name.
    /// Path should be relative to the project root with forward slashes.
    ///
    /// When a zone declares a `root` (subtree scope), the path must start
    /// with that prefix and the prefix is stripped before glob matching;
    /// otherwise the zone is skipped. Zones without a `root` keep
    /// project-root-relative behavior.
    #[must_use]
    pub fn classify_zone(&self, relative_path: &str) -> Option<&str> {
        for zone in &self.zones {
            let candidate: &str = match zone.root.as_deref() {
                Some(root) if !root.is_empty() => {
                    let Some(stripped) = relative_path.strip_prefix(root) else {
                        continue;
                    };
                    stripped
                }
                _ => relative_path,
            };
            if zone.matchers.iter().any(|m| m.is_match(candidate)) {
                return Some(&zone.name);
            }
        }
        None
    }

    /// Check if an import from `from_zone` to `to_zone` is allowed.
    /// Returns `true` if the import is permitted.
    #[must_use]
    pub fn is_import_allowed(&self, from_zone: &str, to_zone: &str) -> bool {
        // Self-imports are always allowed.
        if from_zone == to_zone {
            return true;
        }

        // Find the rule for the source zone.
        let rule = self.rules.iter().find(|r| r.from_zone == from_zone);

        match rule {
            // Zone has no rule entry — unrestricted.
            None => true,
            // Zone has a rule — check the allowlist.
            Some(r) => r.allowed_zones.iter().any(|z| z == to_zone),
        }
    }

    /// Check whether a type-only import from `from_zone` to `to_zone` is
    /// permitted by the rule's `allowTypeOnly` list. Only consulted by the
    /// boundary detector after `is_import_allowed` has already returned
    /// `false`; the caller is responsible for verifying the import is in
    /// fact type-only (all symbols on the edge carry the type-only flag).
    /// Returns `false` when no rule exists for `from_zone`, since rule-less
    /// zones are unrestricted and `is_import_allowed` short-circuits before
    /// this is called.
    #[must_use]
    pub fn is_type_only_allowed(&self, from_zone: &str, to_zone: &str) -> bool {
        let Some(rule) = self.rules.iter().find(|r| r.from_zone == from_zone) else {
            return false;
        };
        rule.allow_type_only_zones.iter().any(|z| z == to_zone)
    }
}

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

    #[test]
    fn empty_config() {
        let config = BoundaryConfig::default();
        assert!(config.is_empty());
        assert!(config.validate_zone_references().is_empty());
    }

    #[test]
    fn deserialize_json() {
        let json = r#"{
            "zones": [
                { "name": "ui", "patterns": ["src/components/**", "src/pages/**"] },
                { "name": "db", "patterns": ["src/db/**"] },
                { "name": "shared", "patterns": ["src/shared/**"] }
            ],
            "rules": [
                { "from": "ui", "allow": ["shared"] },
                { "from": "db", "allow": ["shared"] }
            ]
        }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.zones.len(), 3);
        assert_eq!(config.rules.len(), 2);
        assert_eq!(config.zones[0].name, "ui");
        assert_eq!(
            config.zones[0].patterns,
            vec!["src/components/**", "src/pages/**"]
        );
        assert_eq!(config.rules[0].from, "ui");
        assert_eq!(config.rules[0].allow, vec!["shared"]);
    }

    #[test]
    fn deserialize_toml() {
        let toml_str = r#"
[[zones]]
name = "ui"
patterns = ["src/components/**"]

[[zones]]
name = "db"
patterns = ["src/db/**"]

[[rules]]
from = "ui"
allow = ["db"]
"#;
        let config: BoundaryConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.zones.len(), 2);
        assert_eq!(config.rules.len(), 1);
    }

    #[test]
    fn auto_discover_expands_child_zones_and_parent_rules() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "app".to_string(),
                    patterns: vec!["src/app/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
            ],
            rules: vec![
                BoundaryRule {
                    from: "app".to_string(),
                    allow: vec!["features".to_string()],
                    allow_type_only: vec![],
                },
                BoundaryRule {
                    from: "features".to_string(),
                    allow: vec![],
                    allow_type_only: vec![],
                },
            ],
        };

        config.expand_auto_discover(temp.path());

        let zone_names: Vec<_> = config.zones.iter().map(|zone| zone.name.as_str()).collect();
        assert_eq!(zone_names, vec!["app", "features/auth", "features/billing"]);
        assert_eq!(
            config.zones[1].patterns,
            vec!["src/features/auth/**".to_string()]
        );
        assert_eq!(
            config.zones[2].patterns,
            vec!["src/features/billing/**".to_string()]
        );
        let app_rule = config
            .rules
            .iter()
            .find(|rule| rule.from == "app")
            .expect("app rule should be preserved");
        assert_eq!(
            app_rule.allow,
            vec!["features/auth".to_string(), "features/billing".to_string()]
        );
        assert!(
            config
                .rules
                .iter()
                .any(|rule| rule.from == "features/auth" && rule.allow.is_empty())
        );
        assert!(
            config
                .rules
                .iter()
                .any(|rule| rule.from == "features/billing" && rule.allow.is_empty())
        );
        assert!(config.validate_zone_references().is_empty());
    }

    #[test]
    fn auto_discover_parent_fallback_allows_children_without_relaxing_child_rules() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "app".to_string(),
                    patterns: vec!["src/app/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec!["src/features/**".to_string()],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec!["src/shared/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![
                BoundaryRule {
                    from: "app".to_string(),
                    allow: vec!["features".to_string(), "shared".to_string()],
                    allow_type_only: vec![],
                },
                BoundaryRule {
                    from: "features".to_string(),
                    allow: vec!["shared".to_string()],
                    allow_type_only: vec![],
                },
            ],
        };

        config.expand_auto_discover(temp.path());

        let zone_names: Vec<_> = config.zones.iter().map(|zone| zone.name.as_str()).collect();
        assert_eq!(
            zone_names,
            vec![
                "app",
                "features/auth",
                "features/billing",
                "features",
                "shared"
            ]
        );

        let app_rule = config
            .rules
            .iter()
            .find(|rule| rule.from == "app")
            .expect("app rule should be preserved");
        assert_eq!(
            app_rule.allow,
            vec![
                "features/auth".to_string(),
                "features/billing".to_string(),
                "features".to_string(),
                "shared".to_string()
            ]
        );

        let parent_rule = config
            .rules
            .iter()
            .find(|rule| rule.from == "features")
            .expect("parent fallback rule should be preserved");
        assert_eq!(
            parent_rule.allow,
            vec![
                "shared".to_string(),
                "features/auth".to_string(),
                "features/billing".to_string()
            ]
        );

        let auth_rule = config
            .rules
            .iter()
            .find(|rule| rule.from == "features/auth")
            .expect("auth child rule should be generated");
        assert_eq!(auth_rule.allow, vec!["shared".to_string()]);

        let billing_rule = config
            .rules
            .iter()
            .find(|rule| rule.from == "features/billing")
            .expect("billing child rule should be generated");
        assert_eq!(billing_rule.allow, vec!["shared".to_string()]);
        assert!(config.validate_zone_references().is_empty());
    }

    #[test]
    fn auto_discover_explicit_child_rule_wins_over_generated_parent_rule() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        for explicit_child_first in [true, false] {
            let explicit_child_rule = BoundaryRule {
                from: "features/auth".to_string(),
                allow: vec!["shared".to_string(), "features/billing".to_string()],
                allow_type_only: vec![],
            };
            let parent_rule = BoundaryRule {
                from: "features".to_string(),
                allow: vec!["shared".to_string()],
                allow_type_only: vec![],
            };
            let rules = if explicit_child_first {
                vec![explicit_child_rule, parent_rule]
            } else {
                vec![parent_rule, explicit_child_rule]
            };

            let mut config = BoundaryConfig {
                preset: None,
                zones: vec![
                    BoundaryZone {
                        name: "features".to_string(),
                        patterns: vec![],
                        auto_discover: vec!["src/features".to_string()],
                        root: None,
                    },
                    BoundaryZone {
                        name: "shared".to_string(),
                        patterns: vec!["src/shared/**".to_string()],
                        auto_discover: vec![],
                        root: None,
                    },
                ],
                rules,
            };

            config.expand_auto_discover(temp.path());

            let auth_rule = config
                .rules
                .iter()
                .find(|rule| rule.from == "features/auth")
                .expect("explicit child rule should remain");
            assert_eq!(
                auth_rule.allow,
                vec!["shared".to_string(), "features/billing".to_string()],
                "explicit child rule should win regardless of rule order"
            );

            let billing_rule = config
                .rules
                .iter()
                .find(|rule| rule.from == "features/billing")
                .expect("parent rule should still generate sibling child rule");
            assert_eq!(billing_rule.allow, vec!["shared".to_string()]);
            assert!(config.validate_zone_references().is_empty());
        }
    }

    // ── LogicalGroup return value (issue #373) ──────────────────

    #[test]
    fn logical_groups_returned_for_simple_auto_discover_zone() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "app".to_string(),
                    patterns: vec!["src/app/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "features".to_string(),
                allow: vec!["app".to_string()],
                allow_type_only: vec![],
            }],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        let g = &groups[0];
        assert_eq!(g.name, "features");
        assert_eq!(g.children, vec!["features/auth", "features/billing"]);
        assert_eq!(g.auto_discover, vec!["src/features"]);
        assert_eq!(g.source_zone_index, 1);
        assert_eq!(g.status, LogicalGroupStatus::Ok);
        // Parent had no explicit patterns → not retained as fallback.
        assert!(g.fallback_zone.is_none());
        let rule = g
            .authored_rule
            .as_ref()
            .expect("authored rule preserved verbatim");
        assert_eq!(rule.allow, vec!["app"]);
        assert!(rule.allow_type_only.is_empty());
    }

    #[test]
    fn logical_groups_preserve_verbatim_auto_discover_strings() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                // Trailing slash + leading `./` are normalized during discovery
                // but the logical group must echo the user's literal string so
                // round-trip config tooling does not introduce spurious diffs.
                auto_discover: vec!["./src/features/".to_string()],
                root: None,
            }],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].auto_discover, vec!["./src/features/"]);
        assert_eq!(groups[0].children, vec!["features/auth"]);
    }

    #[test]
    fn logical_groups_bulletproof_keeps_fallback_zone_cross_reference() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                // Bulletproof shape: parent carries BOTH patterns AND
                // autoDiscover, so the parent stays in zones[] as a fallback
                // classifier while ALSO becoming a logical group.
                name: "features".to_string(),
                patterns: vec!["src/features/**".to_string()],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].fallback_zone.as_deref(), Some("features"));
        // Parent zone is still present in zones[] as the fallback classifier.
        assert!(config.zones.iter().any(|z| z.name == "features"));
    }

    #[test]
    fn logical_groups_status_empty_when_no_child_dirs() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features")).unwrap();
        // No child subdirs created.

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].status, LogicalGroupStatus::Empty);
        assert!(groups[0].children.is_empty());
    }

    #[test]
    fn logical_groups_status_invalid_path_when_dir_missing() {
        let temp = tempfile::tempdir().unwrap();
        // src/features intentionally not created.

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].status, LogicalGroupStatus::InvalidPath);
        assert!(groups[0].children.is_empty());
    }

    #[test]
    fn logical_groups_status_ok_wins_over_invalid_when_mixed() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        // src/modules intentionally not created (invalid path).

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
                root: None,
            }],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        // One path produced children → status is Ok even though another path
        // was invalid. The InvalidPath warning still surfaces via tracing.
        assert_eq!(groups[0].status, LogicalGroupStatus::Ok);
        assert_eq!(groups[0].children, vec!["features/auth"]);
    }

    #[test]
    fn logical_groups_preserve_declaration_order() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/zeta/a")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/alpha/a")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/mid/a")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "zeta".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/zeta".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "alpha".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/alpha".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "mid".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/mid".to_string()],
                    root: None,
                },
            ],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        // Insertion order is preserved; not alphabetized.
        let names: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
        assert_eq!(names, vec!["zeta", "alpha", "mid"]);
    }

    #[test]
    fn logical_groups_merged_from_records_duplicate_indices() {
        // The single-declaration path leaves merged_from None; the
        // duplicate-merge path populates it with every contributing index.
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/extra/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "other".to_string(),
                    patterns: vec!["src/other/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/extra".to_string()],
                    root: None,
                },
            ],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        // merged_from holds both contributing zone indices in declaration
        // order: position 0 and position 2 (the "other" zone at position 1
        // is unrelated).
        assert_eq!(groups[0].merged_from.as_deref(), Some(&[0_usize, 2][..]));
        // The first index also wins source_zone_index.
        assert_eq!(groups[0].source_zone_index, 0);
    }

    #[test]
    fn logical_groups_merged_from_none_on_single_declaration() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        // Common case: no duplicate, no merged_from.
        assert!(groups[0].merged_from.is_none());
    }

    #[test]
    fn logical_groups_echo_original_zone_root() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("packages/app/src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                // Monorepo subtree scope on the parent; should round-trip
                // verbatim to logical_groups[0].original_zone_root so
                // patcher tools can distinguish parent-set vs per-child root.
                root: Some("packages/app/".to_string()),
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(
            groups[0].original_zone_root.as_deref(),
            Some("packages/app/")
        );
    }

    #[test]
    fn logical_groups_original_zone_root_none_when_unset() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert!(groups[0].original_zone_root.is_none());
    }

    #[test]
    fn logical_groups_child_source_indices_populated_for_multi_path() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/modules/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                // Two paths: each produces one child. Children are
                // alphabetically sorted across paths, so auth (from index 0)
                // sorts before billing (from index 1).
                auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(
            groups[0].children,
            vec!["features/auth", "features/billing"]
        );
        assert_eq!(groups[0].child_source_indices, vec![0, 1]);
    }

    #[test]
    fn logical_groups_child_source_indices_empty_for_single_path() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        // With one path, every child trivially has source index 0. The
        // helper field is suppressed (empty Vec) so the JSON stays tight
        // on the common case.
        assert!(groups[0].child_source_indices.is_empty());
    }

    #[test]
    fn logical_groups_child_source_indices_after_duplicate_merge_shifted() {
        // When two parent declarations merge, the child indices from the
        // SECOND batch must be shifted by the FIRST batch's
        // auto_discover.len() so they continue to address the
        // post-concatenation `auto_discover` array correctly.
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/extra/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/extra".to_string()],
                    root: None,
                },
            ],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        // Merged auto_discover has 2 entries; index 0 = src/features,
        // index 1 = src/extra. The features/billing child came from the
        // second batch's first path, which post-shift is index 1.
        assert_eq!(groups[0].auto_discover, vec!["src/features", "src/extra"]);
        let auth_idx = groups[0]
            .children
            .iter()
            .position(|c| c == "features/auth")
            .unwrap();
        let billing_idx = groups[0]
            .children
            .iter()
            .position(|c| c == "features/billing")
            .unwrap();
        assert_eq!(groups[0].child_source_indices[auth_idx], 0);
        assert_eq!(groups[0].child_source_indices[billing_idx], 1);
    }

    #[test]
    fn logical_groups_merge_duplicate_parent_zone_declarations() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/extra/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/extra".to_string()],
                    root: None,
                },
            ],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        // The two declarations merge into a single logical group with
        // concatenated auto_discover paths and children.
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].name, "features");
        assert_eq!(groups[0].auto_discover, vec!["src/features", "src/extra"]);
        assert!(groups[0].children.iter().any(|c| c == "features/auth"));
        assert!(groups[0].children.iter().any(|c| c == "features/billing"));
        assert_eq!(groups[0].source_zone_index, 0);
    }

    #[test]
    fn logical_groups_duplicate_identical_declarations_no_double_count() {
        // Regression for codex parallel review (post-impl pass): two
        // identical `features` declarations with the same `autoDiscover`
        // path used to emit duplicate `zones[]` entries, duplicate
        // `children[]`, and double-counted `file_count` (4 for 2 real
        // files). `merge_zone_by_name` keeps `zones[]` unique by name and
        // the merge logic dedupes children against the existing set.
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
                BoundaryZone {
                    name: "features".to_string(),
                    patterns: vec![],
                    auto_discover: vec!["src/features".to_string()],
                    root: None,
                },
            ],
            rules: vec![],
        };

        let groups = config.expand_auto_discover(temp.path());
        assert_eq!(groups.len(), 1);
        // zones[] must NOT contain duplicates of features/auth or
        // features/billing.
        let zone_names: Vec<&str> = config.zones.iter().map(|z| z.name.as_str()).collect();
        assert_eq!(zone_names, vec!["features/auth", "features/billing"]);
        // children[] must NOT contain duplicates.
        assert_eq!(
            groups[0].children,
            vec!["features/auth", "features/billing"]
        );
        // auto_discover preserves both verbatim (the duplicate is visible
        // via merged_from + the warning, but the path list itself
        // concatenates).
        assert_eq!(
            groups[0].auto_discover,
            vec!["src/features", "src/features"]
        );
        // merged_from records both zone indices.
        assert_eq!(groups[0].merged_from.as_deref(), Some(&[0_usize, 1][..]));
    }

    #[test]
    fn logical_groups_empty_when_no_auto_discover_present() {
        let temp = tempfile::tempdir().unwrap();
        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/components/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        assert!(groups.is_empty());
    }

    #[test]
    fn logical_groups_propagate_through_resolve() {
        // End-to-end: data populated by expand_auto_discover survives a
        // round trip through `BoundaryConfig::resolve()` so consumers of
        // `ResolvedBoundaryConfig.logical_groups` see the same content.
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();

        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "features".to_string(),
                patterns: vec![],
                auto_discover: vec!["src/features".to_string()],
                root: None,
            }],
            rules: vec![],
        };
        let groups = config.expand_auto_discover(temp.path());
        let mut resolved = config.resolve();
        // `resolve()` itself does not have access to the pre-expansion state;
        // the resolution pipeline stitches the groups back on. Mirror that
        // here so the test exercises the same shape consumers see.
        resolved.logical_groups = groups;
        assert_eq!(resolved.logical_groups.len(), 1);
        assert_eq!(resolved.logical_groups[0].name, "features");
        assert_eq!(resolved.logical_groups[0].children, vec!["features/auth"]);
    }

    #[test]
    fn validate_zone_references_valid() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["db".to_string()],
                allow_type_only: vec![],
            }],
        };
        assert!(config.validate_zone_references().is_empty());
    }

    #[test]
    fn validate_zone_references_invalid_from() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "nonexistent".to_string(),
                allow: vec!["ui".to_string()],
                allow_type_only: vec![],
            }],
        };
        let errors = config.validate_zone_references();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].zone_name, "nonexistent");
        assert_eq!(errors[0].kind, ZoneReferenceKind::From);
        assert_eq!(errors[0].rule_index, 0);
    }

    #[test]
    fn validate_zone_references_invalid_allow() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["nonexistent".to_string()],
                allow_type_only: vec![],
            }],
        };
        let errors = config.validate_zone_references();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].zone_name, "nonexistent");
        assert_eq!(errors[0].kind, ZoneReferenceKind::Allow);
    }

    #[test]
    fn validate_zone_references_invalid_allow_type_only() {
        // An undefined zone in `allowTypeOnly` silently behaves as "not
        // allowed" at runtime, which the user almost always meant as a typo
        // for an existing zone. Surface the same diagnostic as `allow`.
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only: vec!["nonexistent_type_zone".to_string()],
            }],
        };
        let errors = config.validate_zone_references();
        assert_eq!(errors.len(), 1, "got: {errors:?}");
        assert_eq!(errors[0].zone_name, "nonexistent_type_zone");
        assert_eq!(errors[0].kind, ZoneReferenceKind::AllowTypeOnly);
    }

    #[test]
    fn resolve_and_classify() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/components/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec!["src/db/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("src/components/Button.tsx"),
            Some("ui")
        );
        assert_eq!(resolved.classify_zone("src/db/queries.ts"), Some("db"));
        assert_eq!(resolved.classify_zone("src/utils/helpers.ts"), None);
    }

    #[test]
    fn first_match_wins() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "specific".to_string(),
                    patterns: vec!["src/shared/db-utils/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec!["src/shared/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("src/shared/db-utils/pool.ts"),
            Some("specific")
        );
        assert_eq!(
            resolved.classify_zone("src/shared/helpers.ts"),
            Some("shared")
        );
    }

    #[test]
    fn self_import_always_allowed() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only: vec![],
            }],
        };
        let resolved = config.resolve();
        assert!(resolved.is_import_allowed("ui", "ui"));
    }

    #[test]
    fn unrestricted_zone_allows_all() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert!(resolved.is_import_allowed("shared", "db"));
    }

    #[test]
    fn restricted_zone_blocks_unlisted() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["shared".to_string()],
                allow_type_only: vec![],
            }],
        };
        let resolved = config.resolve();
        assert!(resolved.is_import_allowed("ui", "shared"));
        assert!(!resolved.is_import_allowed("ui", "db"));
    }

    #[test]
    fn empty_allow_blocks_all_except_self() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "isolated".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "other".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "isolated".to_string(),
                allow: vec![],
                allow_type_only: vec![],
            }],
        };
        let resolved = config.resolve();
        assert!(resolved.is_import_allowed("isolated", "isolated"));
        assert!(!resolved.is_import_allowed("isolated", "other"));
    }

    #[test]
    fn zone_root_filters_classification_to_subtree() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/**".to_string()],
                    auto_discover: vec![],
                    root: Some("packages/app/".to_string()),
                },
                BoundaryZone {
                    name: "domain".to_string(),
                    patterns: vec!["src/**".to_string()],
                    auto_discover: vec![],
                    root: Some("packages/core/".to_string()),
                },
            ],
            rules: vec![],
        };
        let resolved = config.resolve();
        // Files inside packages/app/ classify as ui
        assert_eq!(
            resolved.classify_zone("packages/app/src/login.tsx"),
            Some("ui")
        );
        // Files inside packages/core/ classify as domain (same pattern, different root)
        assert_eq!(
            resolved.classify_zone("packages/core/src/order.ts"),
            Some("domain")
        );
        // Files outside either subtree do not match
        assert_eq!(resolved.classify_zone("src/login.tsx"), None);
        assert_eq!(resolved.classify_zone("packages/utils/src/x.ts"), None);
    }

    /// Case-sensitivity contract: `root` matching is case-sensitive,
    /// matching the existing globset case-sensitivity for `patterns`. On
    /// case-insensitive filesystems (HFS+, NTFS) two files differing only
    /// in case still classify only when the configured `root` exactly
    /// matches the path's case as fallow recorded it. Locking this down
    /// prevents silent platform-divergent classification.
    #[test]
    fn zone_root_is_case_sensitive() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/**".to_string()],
                auto_discover: vec![],
                root: Some("packages/app/".to_string()),
            }],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("packages/app/src/login.tsx"),
            Some("ui"),
            "exact-case path classifies"
        );
        assert_eq!(
            resolved.classify_zone("packages/App/src/login.tsx"),
            None,
            "case-different path does not classify (root is case-sensitive)"
        );
        assert_eq!(
            resolved.classify_zone("Packages/app/src/login.tsx"),
            None,
            "case-different prefix does not classify"
        );
    }

    #[test]
    fn zone_root_normalizes_trailing_slash_and_dot_prefix() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "no-slash".to_string(),
                    patterns: vec!["src/**".to_string()],
                    auto_discover: vec![],
                    root: Some("packages/app".to_string()),
                },
                BoundaryZone {
                    name: "dot-prefixed".to_string(),
                    patterns: vec!["src/**".to_string()],
                    auto_discover: vec![],
                    root: Some("./packages/lib/".to_string()),
                },
            ],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert_eq!(resolved.zones[0].root.as_deref(), Some("packages/app/"));
        assert_eq!(resolved.zones[1].root.as_deref(), Some("packages/lib/"));
        assert_eq!(
            resolved.classify_zone("packages/app/src/x.ts"),
            Some("no-slash")
        );
        assert_eq!(
            resolved.classify_zone("packages/lib/src/x.ts"),
            Some("dot-prefixed")
        );
    }

    #[test]
    fn validate_root_prefixes_flags_redundant_pattern() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["packages/app/src/**".to_string()],
                auto_discover: vec![],
                root: Some("packages/app/".to_string()),
            }],
            rules: vec![],
        };
        let errors = config.validate_root_prefixes();
        assert_eq!(errors.len(), 1, "expected one redundant-prefix error");
        assert_eq!(errors[0].zone_name, "ui");
        assert_eq!(errors[0].pattern, "packages/app/src/**");
        assert_eq!(errors[0].root, "packages/app/");
        // Display preserves the legacy FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX
        // tag so existing CI grep recipes continue to work.
        let rendered = ZoneValidationError::RedundantRootPrefix(errors[0].clone()).to_string();
        assert!(
            rendered.contains("FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX"),
            "Display should carry legacy tag: {rendered}"
        );
        assert!(
            rendered.contains("zone 'ui'"),
            "Display rendering: {rendered}"
        );
        assert!(
            rendered.contains("packages/app/src/**"),
            "Display rendering: {rendered}"
        );
    }

    #[test]
    fn validate_root_prefixes_handles_unnormalized_root() {
        // Root without trailing slash + pattern with leading "./" should
        // still be detected as redundant after normalization.
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["./packages/app/src/**".to_string()],
                auto_discover: vec![],
                root: Some("packages/app".to_string()),
            }],
            rules: vec![],
        };
        let errors = config.validate_root_prefixes();
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn validate_root_prefixes_empty_when_no_overlap() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/**".to_string()],
                auto_discover: vec![],
                root: Some("packages/app/".to_string()),
            }],
            rules: vec![],
        };
        assert!(config.validate_root_prefixes().is_empty());
    }

    #[test]
    fn validate_root_prefixes_skips_zones_without_root() {
        let json = r#"{
            "zones": [{ "name": "ui", "patterns": ["src/**"] }],
            "rules": []
        }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert!(config.validate_root_prefixes().is_empty());
    }

    /// Regression: an empty `root` (or `"."`/`"./"`, both of which normalize
    /// to `""`) used to make `starts_with("")` always true, producing a
    /// spurious FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX error for every
    /// pattern in the zone. The validation must skip empty-normalized roots
    /// the same way `classify_zone` does.
    #[test]
    fn validate_root_prefixes_skips_empty_root() {
        for raw_root in ["", ".", "./"] {
            let config = BoundaryConfig {
                preset: None,
                zones: vec![BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/**".to_string(), "lib/**".to_string()],
                    auto_discover: vec![],
                    root: Some(raw_root.to_string()),
                }],
                rules: vec![],
            };
            let errors = config.validate_root_prefixes();
            assert!(
                errors.is_empty(),
                "empty-normalized root {raw_root:?} produced spurious errors: {errors:?}"
            );
        }
    }

    #[test]
    fn deserialize_zone_with_root() {
        let json = r#"{
            "zones": [
                { "name": "ui", "patterns": ["src/**"], "root": "packages/app/" }
            ],
            "rules": []
        }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.zones[0].root.as_deref(), Some("packages/app/"));
    }

    // ── Preset deserialization ─────────────────────────────────

    #[test]
    fn deserialize_preset_json() {
        let json = r#"{ "preset": "layered" }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.preset, Some(BoundaryPreset::Layered));
        assert!(config.zones.is_empty());
    }

    #[test]
    fn deserialize_preset_hexagonal_json() {
        let json = r#"{ "preset": "hexagonal" }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.preset, Some(BoundaryPreset::Hexagonal));
    }

    #[test]
    fn deserialize_preset_feature_sliced_json() {
        let json = r#"{ "preset": "feature-sliced" }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.preset, Some(BoundaryPreset::FeatureSliced));
    }

    #[test]
    fn deserialize_preset_toml() {
        let toml_str = r#"preset = "layered""#;
        let config: BoundaryConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.preset, Some(BoundaryPreset::Layered));
    }

    #[test]
    fn deserialize_invalid_preset_rejected() {
        let json = r#"{ "preset": "invalid_preset" }"#;
        let result: Result<BoundaryConfig, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn preset_absent_by_default() {
        let config = BoundaryConfig::default();
        assert!(config.preset.is_none());
        assert!(config.is_empty());
    }

    #[test]
    fn preset_makes_config_non_empty() {
        let config = BoundaryConfig {
            preset: Some(BoundaryPreset::Layered),
            zones: vec![],
            rules: vec![],
        };
        assert!(!config.is_empty());
    }

    // ── Preset expansion ───────────────────────────────────────

    #[test]
    fn expand_layered_produces_four_zones() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Layered),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 4);
        assert_eq!(config.rules.len(), 4);
        assert!(config.preset.is_none(), "preset cleared after expand");
        assert_eq!(config.zones[0].name, "presentation");
        assert_eq!(config.zones[0].patterns, vec!["src/presentation/**"]);
    }

    #[test]
    fn expand_layered_rules_correct() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Layered),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        // presentation → application only
        let pres_rule = config
            .rules
            .iter()
            .find(|r| r.from == "presentation")
            .unwrap();
        assert_eq!(pres_rule.allow, vec!["application"]);
        // application → domain only
        let app_rule = config
            .rules
            .iter()
            .find(|r| r.from == "application")
            .unwrap();
        assert_eq!(app_rule.allow, vec!["domain"]);
        // domain → nothing
        let dom_rule = config.rules.iter().find(|r| r.from == "domain").unwrap();
        assert!(dom_rule.allow.is_empty());
        // infrastructure → domain + application (DI-friendly)
        let infra_rule = config
            .rules
            .iter()
            .find(|r| r.from == "infrastructure")
            .unwrap();
        assert_eq!(infra_rule.allow, vec!["domain", "application"]);
    }

    #[test]
    fn expand_hexagonal_produces_three_zones() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 3);
        assert_eq!(config.rules.len(), 3);
        assert_eq!(config.zones[0].name, "adapters");
        assert_eq!(config.zones[1].name, "ports");
        assert_eq!(config.zones[2].name, "domain");
    }

    #[test]
    fn expand_feature_sliced_produces_six_zones() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::FeatureSliced),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 6);
        assert_eq!(config.rules.len(), 6);
        // app can import everything below
        let app_rule = config.rules.iter().find(|r| r.from == "app").unwrap();
        assert_eq!(
            app_rule.allow,
            vec!["pages", "widgets", "features", "entities", "shared"]
        );
        // shared imports nothing
        let shared_rule = config.rules.iter().find(|r| r.from == "shared").unwrap();
        assert!(shared_rule.allow.is_empty());
        // entities → shared only
        let ent_rule = config.rules.iter().find(|r| r.from == "entities").unwrap();
        assert_eq!(ent_rule.allow, vec!["shared"]);
    }

    #[test]
    fn expand_bulletproof_produces_four_zones() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Bulletproof),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 4);
        assert_eq!(config.rules.len(), 4);
        assert_eq!(config.zones[0].name, "app");
        assert_eq!(config.zones[1].name, "features");
        assert_eq!(config.zones[2].name, "shared");
        assert_eq!(config.zones[3].name, "server");
        // shared zone has multiple patterns
        assert!(config.zones[2].patterns.len() > 1);
        assert!(
            config.zones[2]
                .patterns
                .contains(&"src/components/**".to_string())
        );
        assert!(
            config.zones[2]
                .patterns
                .contains(&"src/hooks/**".to_string())
        );
        assert!(config.zones[2].patterns.contains(&"src/lib/**".to_string()));
        assert!(
            config.zones[2]
                .patterns
                .contains(&"src/providers/**".to_string())
        );
    }

    #[test]
    fn expand_bulletproof_rules_correct() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Bulletproof),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        // app → features, shared, server
        let app_rule = config.rules.iter().find(|r| r.from == "app").unwrap();
        assert_eq!(app_rule.allow, vec!["features", "shared", "server"]);
        // features → shared, server
        let feat_rule = config.rules.iter().find(|r| r.from == "features").unwrap();
        assert_eq!(feat_rule.allow, vec!["shared", "server"]);
        // server → shared
        let srv_rule = config.rules.iter().find(|r| r.from == "server").unwrap();
        assert_eq!(srv_rule.allow, vec!["shared"]);
        // shared → nothing (isolated)
        let shared_rule = config.rules.iter().find(|r| r.from == "shared").unwrap();
        assert!(shared_rule.allow.is_empty());
    }

    #[test]
    fn expand_bulletproof_then_resolve_classifies() {
        // `expand()` alone (without `expand_auto_discover`) does not produce
        // the per-feature child zones yet, but the parent `features` fallback
        // still classifies top-level and nested `src/features/...` files.
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Bulletproof),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("src/app/dashboard/page.tsx"),
            Some("app")
        );
        assert_eq!(
            resolved.classify_zone("src/features/auth/hooks/useAuth.ts"),
            Some("features"),
            "without expand_auto_discover, src/features/... falls back to the parent zone"
        );
        assert_eq!(
            resolved.classify_zone("src/components/Button/Button.tsx"),
            Some("shared")
        );
        assert_eq!(
            resolved.classify_zone("src/hooks/useFormatters.ts"),
            Some("shared")
        );
        assert_eq!(
            resolved.classify_zone("src/server/db/schema/users.ts"),
            Some("server")
        );
        // features cannot import shared directly — only via allowed rules
        assert!(resolved.is_import_allowed("features", "shared"));
        assert!(resolved.is_import_allowed("features", "server"));
        assert!(!resolved.is_import_allowed("features", "app"));
        assert!(!resolved.is_import_allowed("shared", "features"));
        assert!(!resolved.is_import_allowed("server", "features"));
    }

    /// Regression for the bulletproof barrel pattern: a top-level
    /// `src/features/index.ts` barrel re-exporting child features must NOT
    /// trigger `features → features/<child>` boundary violations. The parent
    /// fallback rule allows discovered children while generated child rules
    /// still enforce sibling isolation.
    #[test]
    fn bulletproof_features_barrel_can_import_children() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/auth")).unwrap();
        std::fs::create_dir_all(temp.path().join("src/features/billing")).unwrap();

        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Bulletproof),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        config.expand_auto_discover(temp.path());
        let resolved = config.resolve();

        // Top-level barrel inside src/features falls back to the parent zone.
        assert_eq!(
            resolved.classify_zone("src/features/index.ts"),
            Some("features"),
            "src/features/index.ts barrel should classify as the parent features zone"
        );
        // Discovered child zones still classify normally.
        assert_eq!(
            resolved.classify_zone("src/features/auth/login.ts"),
            Some("features/auth")
        );
        assert_eq!(
            resolved.classify_zone("src/features/billing/invoice.ts"),
            Some("features/billing")
        );
        // Parent barrels can re-export child features.
        assert!(resolved.is_import_allowed("features", "features/auth"));
        assert!(resolved.is_import_allowed("features", "features/billing"));
        // Sibling-feature import is still a cross-zone violation.
        assert!(!resolved.is_import_allowed("features/auth", "features/billing"));
    }

    #[test]
    fn expand_uses_custom_source_root() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![],
            rules: vec![],
        };
        config.expand("lib");
        assert_eq!(config.zones[0].patterns, vec!["lib/adapters/**"]);
        assert_eq!(config.zones[2].patterns, vec!["lib/domain/**"]);
    }

    // ── Preset merge behavior ──────────────────────────────────

    #[test]
    fn user_zone_replaces_preset_zone() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![BoundaryZone {
                name: "domain".to_string(),
                patterns: vec!["src/core/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        config.expand("src");
        // 3 zones total: adapters + ports from preset, domain from user
        assert_eq!(config.zones.len(), 3);
        let domain = config.zones.iter().find(|z| z.name == "domain").unwrap();
        assert_eq!(domain.patterns, vec!["src/core/**"]);
    }

    #[test]
    fn user_zone_adds_to_preset() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![BoundaryZone {
                name: "shared".to_string(),
                patterns: vec!["src/shared/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 4); // 3 preset + 1 user
        assert!(config.zones.iter().any(|z| z.name == "shared"));
    }

    #[test]
    fn user_rule_replaces_preset_rule() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![],
            rules: vec![BoundaryRule {
                from: "adapters".to_string(),
                allow: vec!["ports".to_string(), "domain".to_string()],
                allow_type_only: vec![],
            }],
        };
        config.expand("src");
        let adapter_rule = config.rules.iter().find(|r| r.from == "adapters").unwrap();
        // User rule allows both ports and domain (preset only allowed ports)
        assert_eq!(adapter_rule.allow, vec!["ports", "domain"]);
        // Other preset rules untouched
        assert_eq!(
            config.rules.iter().filter(|r| r.from == "adapters").count(),
            1
        );
    }

    #[test]
    fn expand_without_preset_is_noop() {
        let mut config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/ui/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        config.expand("src");
        assert_eq!(config.zones.len(), 1);
        assert_eq!(config.zones[0].name, "ui");
    }

    #[test]
    fn expand_then_validate_succeeds() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Layered),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        assert!(config.validate_zone_references().is_empty());
    }

    #[test]
    fn expand_then_resolve_classifies() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::Hexagonal),
            zones: vec![],
            rules: vec![],
        };
        config.expand("src");
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("src/adapters/http/handler.ts"),
            Some("adapters")
        );
        assert_eq!(resolved.classify_zone("src/domain/user.ts"), Some("domain"));
        assert!(!resolved.is_import_allowed("adapters", "domain"));
        assert!(resolved.is_import_allowed("adapters", "ports"));
    }

    #[test]
    fn preset_name_returns_correct_string() {
        let config = BoundaryConfig {
            preset: Some(BoundaryPreset::FeatureSliced),
            zones: vec![],
            rules: vec![],
        };
        assert_eq!(config.preset_name(), Some("feature-sliced"));

        let empty = BoundaryConfig::default();
        assert_eq!(empty.preset_name(), None);
    }

    #[test]
    fn preset_name_all_variants() {
        let cases = [
            (BoundaryPreset::Layered, "layered"),
            (BoundaryPreset::Hexagonal, "hexagonal"),
            (BoundaryPreset::FeatureSliced, "feature-sliced"),
            (BoundaryPreset::Bulletproof, "bulletproof"),
        ];
        for (preset, expected_name) in cases {
            let config = BoundaryConfig {
                preset: Some(preset),
                zones: vec![],
                rules: vec![],
            };
            assert_eq!(
                config.preset_name(),
                Some(expected_name),
                "preset_name() mismatch for variant"
            );
        }
    }

    // ── ResolvedBoundaryConfig::is_empty ────────────────────────────

    #[test]
    fn resolved_boundary_config_empty() {
        let resolved = ResolvedBoundaryConfig::default();
        assert!(resolved.is_empty());
    }

    #[test]
    fn resolved_boundary_config_with_zones_not_empty() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/ui/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert!(!resolved.is_empty());
    }

    #[test]
    fn resolved_boundary_config_with_only_logical_groups_not_empty() {
        // Regression for issue #373 smoke: a config whose every autoDiscover
        // zone produced zero children ends up with empty `zones[]` but a
        // populated `logical_groups[]`. The boundaries section must still
        // surface so `fallow list --boundaries` can render the Empty /
        // InvalidPath status (otherwise the whole block silently disappears
        // and the user has no signal that discovery turned up nothing).
        let resolved = ResolvedBoundaryConfig {
            zones: vec![],
            rules: vec![],
            logical_groups: vec![LogicalGroup {
                name: "features".to_string(),
                children: vec![],
                auto_discover: vec!["src/features".to_string()],
                authored_rule: None,
                fallback_zone: None,
                source_zone_index: 0,
                status: LogicalGroupStatus::Empty,
                merged_from: None,
                original_zone_root: None,
                child_source_indices: vec![],
            }],
        };
        assert!(!resolved.is_empty());
    }

    // ── BoundaryConfig::is_empty edge cases ─────────────────────────

    #[test]
    fn boundary_config_with_only_rules_is_empty() {
        // Having rules but no zones/preset is still "empty" since rules without zones
        // cannot produce boundary violations.
        let config = BoundaryConfig {
            preset: None,
            zones: vec![],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["db".to_string()],
                allow_type_only: vec![],
            }],
        };
        assert!(config.is_empty());
    }

    #[test]
    fn boundary_config_with_zones_not_empty() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        assert!(!config.is_empty());
    }

    // ── Multiple zone patterns ──────────────────────────────────────

    #[test]
    fn zone_with_multiple_patterns_matches_any() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![
                    "src/components/**".to_string(),
                    "src/pages/**".to_string(),
                    "src/views/**".to_string(),
                ],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        let resolved = config.resolve();
        assert_eq!(
            resolved.classify_zone("src/components/Button.tsx"),
            Some("ui")
        );
        assert_eq!(resolved.classify_zone("src/pages/Home.tsx"), Some("ui"));
        assert_eq!(
            resolved.classify_zone("src/views/Dashboard.tsx"),
            Some("ui")
        );
        assert_eq!(resolved.classify_zone("src/utils/helpers.ts"), None);
    }

    // ── validate_zone_references with multiple errors ───────────────

    #[test]
    fn validate_zone_references_multiple_errors() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec![],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![
                BoundaryRule {
                    from: "nonexistent_from".to_string(),
                    allow: vec!["nonexistent_allow".to_string()],
                    allow_type_only: vec![],
                },
                BoundaryRule {
                    from: "ui".to_string(),
                    allow: vec!["also_nonexistent".to_string()],
                    allow_type_only: vec![],
                },
            ],
        };
        let errors = config.validate_zone_references();
        // Rule 0: invalid "from" + invalid "allow" = 2 errors
        // Rule 1: valid "from", invalid "allow" = 1 error
        assert_eq!(errors.len(), 3);
    }

    // ── Preset expansion with custom source root ────────────────────

    #[test]
    fn expand_feature_sliced_with_custom_root() {
        let mut config = BoundaryConfig {
            preset: Some(BoundaryPreset::FeatureSliced),
            zones: vec![],
            rules: vec![],
        };
        config.expand("lib");
        assert_eq!(config.zones[0].patterns, vec!["lib/app/**"]);
        assert_eq!(config.zones[5].patterns, vec!["lib/shared/**"]);
    }

    // ── is_import_allowed for zone not in rules (unrestricted) ──────

    #[test]
    fn zone_not_in_rules_is_unrestricted() {
        let config = BoundaryConfig {
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "a".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "b".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "c".to_string(),
                    patterns: vec![],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "a".to_string(),
                allow: vec!["b".to_string()],
                allow_type_only: vec![],
            }],
        };
        let resolved = config.resolve();
        // "a" is restricted: can import from "b" but not "c"
        assert!(resolved.is_import_allowed("a", "b"));
        assert!(!resolved.is_import_allowed("a", "c"));
        // "b" has no rule entry: unrestricted
        assert!(resolved.is_import_allowed("b", "a"));
        assert!(resolved.is_import_allowed("b", "c"));
        // "c" has no rule entry: unrestricted
        assert!(resolved.is_import_allowed("c", "a"));
    }

    // ── Preset serialization/deserialization roundtrip ───────────────

    #[test]
    fn boundary_preset_json_roundtrip() {
        let presets = [
            BoundaryPreset::Layered,
            BoundaryPreset::Hexagonal,
            BoundaryPreset::FeatureSliced,
            BoundaryPreset::Bulletproof,
        ];
        for preset in presets {
            let json = serde_json::to_string(&preset).unwrap();
            let restored: BoundaryPreset = serde_json::from_str(&json).unwrap();
            assert_eq!(restored, preset);
        }
    }

    #[test]
    fn deserialize_preset_bulletproof_json() {
        let json = r#"{ "preset": "bulletproof" }"#;
        let config: BoundaryConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.preset, Some(BoundaryPreset::Bulletproof));
    }

    // ── Zone with invalid glob ──────────────────────────────────────

    #[test]
    #[should_panic(expected = "validated at config load time")]
    fn resolve_panics_on_unvalidated_invalid_zone_glob() {
        // Per issue #463, boundaries.zones[].patterns are validated by
        // FallowConfig::load before reaching resolve(). A program that
        // constructs a config in-code with an invalid pattern has skipped
        // that validation; resolve() asserts the invariant by panicking.
        let config = BoundaryConfig {
            preset: None,
            zones: vec![BoundaryZone {
                name: "broken".to_string(),
                patterns: vec!["[invalid".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![],
        };
        let _ = config.resolve();
    }
}