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
//! Architecture boundary zone and rule definitions.
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use globset::Glob;
use rustc_hash::FxHashSet;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
/// Process-local dedup state for the
/// `patterns + autoDiscover` footgun warning. Keyed on the offending zone
/// name. The warn fires once per (process, zone name) so long-running hosts
/// (`fallow watch`, the LSP, the NAPI worker, the MCP server) do not spam
/// the same diagnostic on every re-analysis. Restart re-arms the warning.
static AUTO_DISCOVER_PATTERNS_WARN_SEEN: OnceLock<Mutex<FxHashSet<String>>> = OnceLock::new();
/// Returns `true` if the warn for `zone_name` has not yet fired in this
/// process, `false` if it has already fired. A poisoned mutex falls back to
/// "would fire" so the user still sees one diagnostic per session.
fn record_auto_discover_patterns_warn_seen(zone_name: &str) -> bool {
let seen = AUTO_DISCOVER_PATTERNS_WARN_SEEN.get_or_init(|| Mutex::new(FxHashSet::default()));
seen.lock()
.map_or(true, |mut set| set.insert(zone_name.to_owned()))
}
/// 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.
///
/// **Trade-off (intentional):** top-level files in `src/features/` (e.g.
/// `src/features/index.ts` barrel, `src/features/types.ts`) do NOT match any
/// child pattern and are unclassified, meaning they are unrestricted by the
/// preset. This is deliberate so feature barrels can re-export children
/// without producing false-positive `features → features/<child>` violations.
/// To classify top-level files strictly, override the `features` zone with
/// an explicit user definition that includes a `patterns` field.
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(),
}
}
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 {
// `features` is a logical group only: auto-discovered child
// zones (`features/<name>`) classify the actual files. Leaving
// `patterns` empty keeps top-level files in `src/features/`
// (typically a barrel like `src/features/index.ts`) unclassified
// so the barrel can re-export children without a cross-zone
// `features → features/<child>` false positive.
name: "features".to_owned(),
patterns: vec![],
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>,
}
/// 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>,
}
/// 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>,
}
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.
pub fn expand_auto_discover(&mut self, project_root: &Path) {
if self.zones.iter().all(|zone| zone.auto_discover.is_empty()) {
return;
}
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();
for mut zone in original_zones {
if zone.auto_discover.is_empty() {
expanded_zones.push(zone);
continue;
}
let group_name = zone.name.clone();
let discovered_zones = discover_child_zones(project_root, &zone);
let mut expanded_names: Vec<String> = discovered_zones
.iter()
.map(|child| child.name.clone())
.collect();
expanded_zones.extend(discovered_zones);
if !zone.patterns.is_empty() {
// Footgun: top-level files inside the auto-discover directory
// (e.g. a `src/features/index.ts` barrel) fall back to the
// parent zone, and the parent rule's allow list typically does
// not include the discovered child zones, so re-exports from
// the barrel surface as `parent -> parent/<child>` false
// positives. The Bulletproof preset deliberately leaves
// `patterns` empty for this reason.
if record_auto_discover_patterns_warn_seen(&group_name) {
tracing::warn!(
"boundary zone '{group_name}' sets BOTH `patterns` and `autoDiscover`. \
Top-level files matching the parent pattern fall back to zone '{group_name}' \
and may produce false-positive cross-zone violations when they re-export \
auto-discovered children (e.g. a `{group_name}/index.ts` barrel). \
Drop `patterns` to leave top-level files unclassified, or define explicit \
allow rules that include the discovered child zones."
);
}
expanded_names.push(group_name.clone());
zone.auto_discover.clear();
expanded_zones.push(zone);
}
if !expanded_names.is_empty() {
group_expansions
.entry(group_name)
.or_default()
.extend(expanded_names);
}
}
self.zones = expanded_zones;
if group_expansions.is_empty() {
return;
}
let original_rules = std::mem::take(&mut self.rules);
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);
if let Some(from_zones) = group_expansions.get(&rule.from) {
for from in from_zones {
let expanded_rule = BoundaryRule {
from: from.clone(),
allow: allow.clone(),
};
if from == &rule.from {
explicit_rules.push(expanded_rule);
} else {
generated_rules.push(expanded_rule);
}
}
} else {
explicit_rules.push(BoundaryRule {
from: rule.from,
allow,
});
}
}
let mut expanded_rules = dedupe_rules_keep_last(generated_rules);
expanded_rules.extend(dedupe_rules_keep_last(explicit_rules));
self.rules = dedupe_rules_keep_last(expanded_rules);
}
/// 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. Returns a list of error messages tagged with
/// `FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX`. Patterns are resolved
/// relative to the zone root, so prefixing the pattern with the same
/// root double-prefixes the path and never matches.
#[must_use]
pub fn validate_root_prefixes(&self) -> Vec<String> {
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(format!(
"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.",
zone.name, pattern, normalized
));
}
}
}
errors
}
/// Validate that all zone names referenced in rules are defined in `zones`.
/// Returns a list of (rule_index, undefined_zone_name) pairs.
#[must_use]
pub fn validate_zone_references(&self) -> Vec<(usize, &str)> {
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((i, rule.from.as_str()));
}
for allowed in &rule.allow {
if !zone_names.contains(allowed.as_str()) {
errors.push((i, allowed.as_str()));
}
}
}
errors
}
/// Resolve into compiled form with pre-built glob matchers.
/// Invalid glob patterns are logged and skipped.
#[must_use]
pub fn resolve(&self) -> ResolvedBoundaryConfig {
let zones = self
.zones
.iter()
.map(|zone| {
let matchers = zone
.patterns
.iter()
.filter_map(|pattern| match Glob::new(pattern) {
Ok(glob) => Some(glob.compile_matcher()),
Err(e) => {
tracing::warn!(
"invalid boundary zone glob pattern '{}' in zone '{}': {e}",
pattern,
zone.name
);
None
}
})
.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(),
})
.collect();
ResolvedBoundaryConfig { zones, rules }
}
}
/// 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),
}
}
fn discover_child_zones(project_root: &Path, zone: &BoundaryZone) -> Vec<BoundaryZone> {
let mut zones_by_name: rustc_hash::FxHashMap<String, BoundaryZone> =
rustc_hash::FxHashMap::default();
let normalized_root = zone
.root
.as_deref()
.map(normalize_zone_root)
.unwrap_or_default();
for raw_dir in &zone.auto_discover {
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
);
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
);
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,
patterns: vec![],
auto_discover: vec![],
root: zone.root.clone(),
});
if !entry
.patterns
.iter()
.any(|pattern| pattern == &child_pattern)
{
entry.patterns.push(child_pattern);
}
}
}
let mut zones: Vec<_> = zones_by_name.into_values().collect();
zones.sort_by(|a, b| a.name.cmp(&b.name));
zones
}
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 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.
#[must_use]
pub fn is_empty(&self) -> bool {
self.zones.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),
}
}
}
#[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()],
},
BoundaryRule {
from: "features".to_string(),
allow: 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_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()],
};
let parent_rule = BoundaryRule {
from: "features".to_string(),
allow: vec!["shared".to_string()],
};
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());
}
}
#[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()],
}],
};
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()],
}],
};
let errors = config.validate_zone_references();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].1, "nonexistent");
}
#[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()],
}],
};
let errors = config.validate_zone_references();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].1, "nonexistent");
}
#[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![],
}],
};
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()],
}],
};
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![],
}],
};
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!(
errors[0].contains("FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX"),
"error should be tagged: {}",
errors[0]
);
assert!(
errors[0].contains("zone 'ui'"),
"error should name the zone: {}",
errors[0]
);
assert!(
errors[0].contains("packages/app/src/**"),
"error should quote the pattern: {}",
errors[0]
);
}
#[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, so the `features` group is empty and
// top-level `src/features/...` files are unclassified. Sibling
// `app` / `shared` / `server` zones still classify normally.
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"),
None,
"without expand_auto_discover, src/features/... is unclassified"
);
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 fix is
/// to keep the bulletproof `features` zone pattern-free so the barrel is
/// unclassified (unrestricted) while child zones still enforce sibling
/// isolation.
#[test]
fn bulletproof_features_barrel_is_unclassified() {
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 stays unclassified.
assert_eq!(
resolved.classify_zone("src/features/index.ts"),
None,
"src/features/index.ts barrel must be unclassified to allow re-exporting children"
);
// 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")
);
// 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()],
}],
};
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());
}
// ── 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()],
}],
};
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()],
},
BoundaryRule {
from: "ui".to_string(),
allow: vec!["also_nonexistent".to_string()],
},
],
};
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()],
}],
};
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]
fn resolve_skips_invalid_zone_glob() {
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 resolved = config.resolve();
// Zone exists but has no valid matchers, so no file can be classified into it
assert!(!resolved.is_empty());
assert_eq!(resolved.classify_zone("anything.ts"), None);
}
}