vlanctl 0.2.0

Apply and tear down named VLAN profiles for lidar sensor networking
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
use crate::config::{Interface, Profile, Route};
use crate::net::{Cmd, CommandRunner};
use crate::state::ParentConfig;
use anyhow::{Context, Result};
use ipnet::IpNet;

mod windows;
mod windows_driver_vlan;
pub use windows::{SWITCH_NAME as WINDOWS_SWITCH_NAME, WindowsHyperV};
pub use windows_driver_vlan::WindowsDriverVlan;

/// Per-operating-system command generation and host-state reading.
///
/// Two of the emission methods return **decisions, not syntax**, and that is
/// deliberate. The straight-line logic this trait replaces looked universal
/// but encoded macOS semantics; a port that shared it would silently break
/// the other platforms.
///
/// The state-reading methods (`list_devices`, `addresses_on`, `is_wireless`,
/// `link_is_active`) exist for the same reason: they parse the output of
/// OS-specific tools, and a wrong parser silently mis-detects hardware rather
/// than erroring, so each platform must supply its own rather than inherit
/// one that happens to compile. That said, none of the four has a production
/// caller yet: `apply`, `down`, `status`, and `resolve_device` all still call
/// the macOS parsers in `commands`/`device` directly. These methods are
/// declared now for the Linux and Windows backends to implement; wiring the
/// real call sites over to them is host-detection work with its own review
/// surface (a wrong parser there silently picks the wrong NIC), not a
/// byproduct of declaring the trait.
///
/// Route and static-ARP command **syntax** is behind this seam as of
/// [`Platform::route_commands`]. It previously was not: shared code built
/// BSD `route add ...`/`arp -s ...` for every platform and delegated only
/// the *decision* of whether to emit a host route, so a non-BSD backend
/// rendered unusable commands. The decision-only hook it replaced
/// (`wants_onlink_host_route`) could express *whether* to route but not
/// *how*.
pub trait Platform {
    /// Short identifier for logs and error messages, e.g. `"macos"`.
    fn name(&self) -> &'static str;

    /// Interface name for a profile entry. `vlan11` on macOS, `eth0.11` on
    /// Linux (or `vlan11` when the dotted form would exceed the kernel's
    /// name limit), and the `vEthernet (vlan11)` alias of a Hyper-V virtual
    /// adapter on Windows. Untagged entries return the parent device on
    /// macOS and Linux, where they configure it directly; on Windows the
    /// parent has no stack of its own once bound to the switch, so an
    /// untagged entry is a virtual adapter too and is named as one.
    ///
    /// This is the single source of every sub-interface name: bring-up,
    /// teardown, the collision guard in `commands::apply`, and creation
    /// recording all read it, so a platform's naming rule lives here and
    /// nowhere else.
    fn iface_name(&self, interface: &Interface, device: &str) -> String;

    /// Ordered commands to bring one interface up: interface creation,
    /// address, and MTU. Routes are a separate concern
    /// ([`Platform::route_commands`], appended by [`bringup_commands_for`]),
    /// so implementations must not include them here.
    fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd>;

    /// Commands to tear one interface down.
    fn teardown_commands(&self, iface: &str) -> Vec<Cmd>;

    /// Ordered commands for ONE route on `iface`, including any static-ARP
    /// entry — both the decision of what to emit and the syntax to emit it
    /// in. `in_subnet` is true when the destination falls inside `iface`'s
    /// own connected subnet, which [`bringup_commands_for`] computes.
    ///
    /// The platforms genuinely disagree here, which is why this is behind
    /// the seam rather than shared. For a *gatewayless in-subnet*
    /// destination macOS must emit **no** route: an interface-scoped host
    /// route there installs a permanent self-MAC LLINFO entry and
    /// black-holes the traffic, so the connected route has to resolve it.
    /// Linux emits one regardless — `ip route add X/32 dev Y` makes the
    /// destination genuinely on-link and the kernel ARPs for it, which is
    /// the only way to reach several hosts sharing one subnet across
    /// different VLANs. The command vocabulary differs too: BSD
    /// `route`/`arp` against Linux `ip route`/`ip neigh`.
    fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd>;

    /// VLAN ids already in use on `parent`, each with the device name
    /// holding it.
    ///
    /// Exists because a platform's uniqueness constraint is not always the
    /// interface *name*. On Linux the kernel keys VLANs on **(parent, vlan
    /// id)**, so a pre-existing `vlan10` on `eth0` makes `eth0.10`
    /// impossible to create even though the names differ — `ip link add`
    /// fails with `8021q: VLAN device already exists` part-way through an
    /// apply. The name-based collision guard cannot see that, so `apply`
    /// consults this as well and refuses up front.
    ///
    /// A platform with no such constraint returns an empty list, and should
    /// issue no probe to do so.
    fn existing_vlans(
        &self,
        runner: &mut dyn CommandRunner,
        parent: &str,
    ) -> Result<Vec<(u16, String)>>;

    /// Whether `name` could be a VLAN **parent** — i.e. a real wired device
    /// this platform might trunk onto, as opposed to loopback, a virtual
    /// device, or a VLAN sub-interface we or someone else created.
    ///
    /// Behind the seam because device naming is the most platform-shaped
    /// thing there is: macOS wired devices are `enN`, while Linux uses
    /// `eth0`, `enp0s31f6`, `enx<mac>`, `eno1`, `ens5` — so the macOS `en`
    /// prefix excludes the very device the Linux backend targets. This is a
    /// *name* predicate only; liveness and wireless-ness are separate
    /// questions ([`Platform::link_is_active`], [`Platform::is_wireless`]).
    fn is_candidate_device(&self, name: &str) -> bool;

    /// Whether teardown may revert configuration applied to the **parent**
    /// device (as opposed to a VLAN sub-interface it created).
    ///
    /// macOS answers `false`: an untagged entry aliases an address onto the
    /// physical device and that persists by design. Windows must answer
    /// `true`, because its untagged equivalent is a vSwitch binding that
    /// re-plumbs the NIC and cannot be left behind.
    ///
    /// No code reads this answer today: an untagged entry is an address
    /// alias, and undoing one needs `-alias <addr>` syntax that the generic
    /// [`Platform::teardown_commands`] has no way to express (see the
    /// comment in `commands::apply` for the full reasoning). A platform that
    /// must actually revert parent configuration needs its own recording and
    /// teardown path built for that purpose — implementing this method as
    /// `true` alone gets a backend nothing. Windows has that path: its
    /// untagged entry is a virtual adapter whose creation
    /// [`Platform::records_created_interface`] recognises, so `apply`
    /// records it and `down` removes it like any tagged one.
    fn reverts_parent_config(&self) -> bool;

    /// The parent device's own IPv4 configuration, read before an apply
    /// takes the device over, so `down` can put it back.
    ///
    /// `Ok(None)` by default, and that is the right answer for macOS and
    /// Linux: a VLAN sub-interface sits beside the parent's own addressing,
    /// which the apply never touches. A backend answers `Some` when its
    /// apply *destroys* that addressing — the Hyper-V backend binds the
    /// parent to an external switch, and Windows clears the parent's
    /// addresses when it does and does not restore them when the switch is
    /// removed. `commands::apply` records the answer in the state file and
    /// `commands::down` hands it to [`Platform::parent_restore_commands`]
    /// after the last interface is gone; a failed apply's rollback does the
    /// same.
    ///
    /// A device with no IPv4 stack at all (already bound to something) is
    /// `Ok(None)`: there is nothing to put back. Only a genuine failure to
    /// ask is an `Err`, and it refuses the apply — an apply that cannot
    /// promise to undo itself must not start.
    fn parent_snapshot(
        &self,
        _runner: &mut dyn CommandRunner,
        _device: &str,
    ) -> Result<Option<ParentConfig>> {
        Ok(None)
    }

    /// Commands that put `parent` back on its device: the inverse of what
    /// the apply's bring-up destroyed. Empty by default, matching
    /// [`Platform::parent_snapshot`]'s default of nothing to restore.
    fn parent_restore_commands(&self, _parent: &ParentConfig) -> Vec<Cmd> {
        Vec::new()
    }

    /// Whether attaching to a parent device takes it away from the host's
    /// own use, so that picking the wrong one would sever the host from a
    /// network it was relying on.
    ///
    /// `false` (the default) for macOS and Linux: a VLAN sub-interface sits
    /// alongside the parent's own addressing, and a wrong guess wastes an
    /// apply but disconnects nothing. `true` for Windows, where the parent
    /// is bound to a Hyper-V switch and loses its own TCP/IP binding until
    /// `down`. `device::resolve_device` refuses to auto-detect a parent on
    /// a platform that answers `true` and asks the caller to name it.
    fn claims_parent_exclusively(&self) -> bool {
        false
    }

    /// Whether [`Platform::teardown_commands`] removes the interface it is
    /// given, so that `commands::down` can confirm the teardown by the
    /// interface's absence from [`Platform::list_devices`].
    ///
    /// `true` (the default) for every backend that creates an interface.
    /// A backend whose interface is the parent device itself answers
    /// `false`: teardown reconfigures the parent and leaves it listed, and
    /// checking for its absence would report every clean `down` as
    /// incomplete.
    fn teardown_removes_interface(&self) -> bool {
        true
    }

    /// Whether this backend can apply `profile` at all, checked by
    /// `commands::apply` before it touches anything — before it even tears
    /// down the previously active profile, so a refusal changes nothing.
    ///
    /// `Ok` by default: `Profile::validate` already covers what is wrong
    /// with a profile on its own terms. This is for a limit that belongs to
    /// one backend, such as [`WindowsDriverVlan`] holding one VLAN per
    /// adapter, and the message should say which backend would take the
    /// profile instead.
    fn validate_profile(&self, _profile: &Profile) -> Result<()> {
        Ok(())
    }

    /// Names of every network device currently on the host, physical and
    /// virtual, in the OS's own naming.
    ///
    /// Declared for the Linux and Windows backends; not yet
    /// consumed anywhere. `apply`/`down`/`status`/`resolve_device` still call
    /// `commands::live_interfaces` (the macOS parser) directly.
    fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>>;

    /// IPv4 addresses currently configured on `device`, each with its prefix
    /// length. Other address families are excluded.
    ///
    /// Declared for the Linux and Windows backends; not yet
    /// consumed anywhere. `apply`/`down`/`status`/`resolve_device` still call
    /// `commands::device_inet_addresses` (the macOS parser) directly.
    fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>>;

    /// Whether `device` is a wireless (Wi-Fi) adapter, which device
    /// detection must never pick as the sensor link.
    ///
    /// Declared for the Linux and Windows backends; not yet
    /// consumed anywhere. `resolve_device` still calls `device::wifi_devices`
    /// (the macOS parser) directly.
    fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool>;

    /// Whether `device` currently has a live link — carrier from a connected
    /// peer. An interface that is administratively down, or up with nothing
    /// plugged in, answers `false`; only a genuine failure to ask is an
    /// `Err`.
    ///
    /// Declared for the Linux and Windows backends; not yet
    /// consumed anywhere. `resolve_device` still calls
    /// `device::interface_is_active` (the macOS parser) directly.
    fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool>;

    /// Whether `cmd` is this platform's *interface creation* command, and so
    /// the interface it names must be recorded for teardown and rollback.
    ///
    /// This exists because the recording test used to match `ifconfig`
    /// argument shape directly, which silently recorded nothing on any other
    /// platform — leaving rollback with nothing to undo and `down` a no-op.
    fn records_created_interface(&self, cmd: &Cmd) -> bool;
}

/// macOS / BSD. The behavior this crate shipped before the `Platform` seam
/// existed, extracted unchanged.
pub struct MacOs;

impl Platform for MacOs {
    fn name(&self) -> &'static str {
        "macos"
    }

    fn iface_name(&self, interface: &Interface, device: &str) -> String {
        iface_name(interface, device)
    }

    fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd> {
        create_address_mtu_commands(interface, device)
    }

    fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
        teardown_commands(iface)
    }

    fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd> {
        let mut cmds = Vec::new();
        match &route.gateway {
            Some(gateway) => {
                let gateway = gateway.to_string();
                cmds.push(Cmd::new("route", &["add", &route.destination, &gateway]));
            }
            None => {
                // An interface-scoped host route to an in-subnet destination
                // installs a permanent self-MAC LLINFO entry and black-holes
                // the traffic; the connected route resolves it correctly.
                if !in_subnet {
                    cmds.push(interface_route_command(&route.destination, iface));
                }
                // Static ARP for an on-link host the kernel can't resolve.
                // The `-host ... -interface` route above leaves an LLINFO
                // entry resolving to our own MAC; `arp -s` overwrites it with
                // the real one. No preceding `arp -d`: on macOS that deletes
                // the freshly-added host route. Validation guarantees
                // mac => gatewayless /32, so the parse always succeeds.
                if let Some(mac) = &route.mac
                    && let Ok(net) = route.destination.parse::<IpNet>()
                {
                    let host = net.addr().to_string();
                    cmds.push(Cmd::new("arp", &["-s", &host, mac]));
                }
            }
        }
        cmds
    }

    fn existing_vlans(
        &self,
        _runner: &mut dyn CommandRunner,
        _parent: &str,
    ) -> Result<Vec<(u16, String)>> {
        // Deliberately empty, and deliberately issues no probe: macOS
        // addresses a VLAN by its interface name, which the name-based guard
        // already covers. Whether BSD also rejects a duplicate (parent, vlan
        // id) under a different name has NOT been verified on hardware, and
        // inventing a constraint we have not tested would risk refusing an
        // apply that works today. If it is ever confirmed, this is where it
        // goes.
        Ok(Vec::new())
    }

    fn is_candidate_device(&self, name: &str) -> bool {
        // macOS wired Ethernet is `enN`. The `!contains('.')` closes a
        // pre-existing gap: `en0.100` is a VLAN sub-interface, not a parent,
        // and a bare prefix test counted it as a candidate.
        name.starts_with("en") && !name.contains('.')
    }

    fn reverts_parent_config(&self) -> bool {
        // An untagged entry aliases an address onto the physical device.
        // Teardown deliberately leaves it: the device may carry unrelated
        // configuration this crate did not create.
        false
    }

    fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
        // `ifconfig -l`: one line of space-separated names.
        crate::commands::live_interfaces(runner)
    }

    fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>> {
        // The `inet <addr> netmask <hex>` lines of `ifconfig <device>`.
        crate::commands::device_inet_addresses(runner, device)
    }

    fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
        // `networksetup -listallhardwareports`: the device under a Wi-Fi
        // hardware port.
        Ok(crate::device::wifi_devices(runner)?
            .iter()
            .any(|w| w == device))
    }

    fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
        // `ifconfig <device>` reporting `status: active`.
        crate::device::interface_is_active(runner, device)
    }

    fn records_created_interface(&self, cmd: &Cmd) -> bool {
        // `ifconfig <name> create`
        cmd.program == "ifconfig" && cmd.args.get(1).map(|a| a == "create").unwrap_or(false)
    }
}

/// Longest interface name the Linux kernel accepts: `IFNAMSIZ` (16) less
/// the terminating NUL.
const LINUX_IFNAMSIZ_MAX: usize = 15;

/// Widest a VLAN id's decimal form can be, per the `1..=4094` range
/// `Profile::validate` enforces (`src/config.rs`).
const LINUX_MAX_VLAN_ID_DIGITS: usize = 4;

/// Longest parent device name for which `<parent>.<id>` fits
/// [`LINUX_IFNAMSIZ_MAX`] for *every* valid VLAN id, not just the one at
/// hand: the widest suffix is `.` plus [`LINUX_MAX_VLAN_ID_DIGITS`] digits
/// (`.4094`, 5 bytes), so `15 - 5 = 10`. Naming must be decided from this
/// worst case — see [`Linux::iface_name`] for why.
const LINUX_MAX_DOTTED_PARENT_LEN: usize = LINUX_IFNAMSIZ_MAX - 1 - LINUX_MAX_VLAN_ID_DIGITS;

/// Linux. Commands mirror the recipe already proven on this hardware by the
/// `ip`-based bring-up script this crate's shell-out approach replaces.
pub struct Linux;

impl Platform for Linux {
    fn name(&self) -> &'static str {
        "linux"
    }

    fn iface_name(&self, interface: &Interface, device: &str) -> String {
        match interface.vlan {
            Some(id) => {
                // 8021q convention: `<parent>.<id>` — when the *parent*
                // fits, using the widest possible suffix
                // ([`LINUX_MAX_DOTTED_PARENT_LEN`]) rather than this
                // interface's own id. The kernel caps a name at
                // `IFNAMSIZ - 1` (15) bytes, and a predictable USB NIC name
                // (`enx` + 12 MAC hex digits) is already 15, so `ip link
                // add` would reject any suffix on it.
                //
                // Deciding per-interface (by this id's own width) instead
                // of per-parent would let one profile mix naming schemes on
                // one NIC: an 11-byte parent fits `<parent>.999` (15 bytes)
                // but overflows at `<parent>.4094` (16 bytes), so id 999
                // would get a dotted name and id 4094 would get the
                // fallback on the very same device — confusing to read in
                // `ip link` output. Deciding from the parent alone keeps
                // naming consistent across every interface in a profile.
                //
                // Overflow falls back to `vlan<id>` rather than truncating
                // the parent: in an `enx` name the trailing hex digits are
                // the device-unique half of the MAC, so trimming them would
                // make two same-vendor NICs collide on one name — a silent
                // failure. `vlan<id>` cannot collide within a profile
                // (validation rejects duplicate ids and a profile has one
                // parent), it is the name the proven `ip`-based recipe and
                // macOS both use, and `vlan4094` is 8 bytes, so it always
                // fits.
                if device.len() <= LINUX_MAX_DOTTED_PARENT_LEN {
                    format!("{device}.{id}")
                } else {
                    format!("vlan{id}")
                }
            }
            None => device.to_string(),
        }
    }

    fn bringup_commands(&self, interface: &Interface, device: &str) -> Vec<Cmd> {
        let name = self.iface_name(interface, device);
        let addr = interface.address.to_string();
        let mut cmds = Vec::new();
        // Raise the parent before adding anything on it, as the recipe does,
        // on BOTH paths. A NIC left admin-down after boot would otherwise
        // leave every sub-interface LOWERLAYERDOWN while every command
        // succeeds. `ip link set ... up` is idempotent, so repeating it per
        // entry is harmless.
        //
        // This is deliberately OUTSIDE the tagged branch: an untagged entry
        // configures the parent directly, and `ip addr add` succeeds on a
        // down link, so its own routes would then be emitted against a down
        // device and rejected with ENETDOWN. An untagged-only profile has no
        // later tagged entry to raise the parent at all.
        cmds.push(Cmd::new("ip", &["link", "set", device, "up"]));
        if let Some(id) = interface.vlan {
            let id = id.to_string();
            cmds.push(Cmd::new(
                "ip",
                &[
                    "link", "add", "link", device, "name", &name, "type", "vlan", "id", &id,
                ],
            ));
            cmds.push(Cmd::new("ip", &["link", "set", &name, "up"]));
        }
        // `ip addr add` takes CIDR directly — no netmask conversion needed.
        cmds.push(Cmd::new("ip", &["addr", "add", &addr, "dev", &name]));
        if let Some(mtu) = interface.mtu {
            cmds.push(Cmd::new(
                "ip",
                &["link", "set", &name, "mtu", &mtu.to_string()],
            ));
        }
        cmds
    }

    fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
        // Deleting the link drops its addresses and routes with it.
        vec![Cmd::new("ip", &["link", "del", iface])]
    }

    fn route_commands(&self, route: &Route, _in_subnet: bool, iface: &str) -> Vec<Cmd> {
        // `in_subnet` is deliberately ignored: unlike macOS, `ip route add
        // X/32 dev Y` makes X genuinely on-link and the kernel ARPs for it.
        // That is the only way to reach several hosts that share one subnet
        // across different VLANs, which is exactly the in-subnet case.
        let mut cmds = Vec::new();
        match &route.gateway {
            Some(gateway) => {
                let gateway = gateway.to_string();
                cmds.push(Cmd::new(
                    "ip",
                    &[
                        "route",
                        "add",
                        &route.destination,
                        "via",
                        &gateway,
                        "dev",
                        iface,
                    ],
                ));
            }
            None => {
                cmds.push(Cmd::new(
                    "ip",
                    &["route", "add", &route.destination, "dev", iface],
                ));
                // `ip neigh REPLACE` is the Linux equivalent of `arp -s`,
                // which overwrites an existing entry. `ip neigh add` is not:
                // it fails with "File exists" when one is already present,
                // which the parent device can easily be — it persists across
                // applies and may already hold a learned or stale entry for
                // the sensor, aborting the apply and rolling it back. (A
                // freshly created tagged device has an empty table, so `add`
                // only ever looked correct there by accident.)
                //
                // No self-MAC hazard here, so no ordering constraint against
                // the route above — but it is kept in the same order as
                // macOS so the two backends read alike.
                if let Some(mac) = &route.mac
                    && let Ok(net) = route.destination.parse::<IpNet>()
                {
                    let host = net.addr().to_string();
                    cmds.push(Cmd::new(
                        "ip",
                        &["neigh", "replace", &host, "lladdr", mac, "dev", iface],
                    ));
                }
            }
        }
        cmds
    }

    fn existing_vlans(
        &self,
        runner: &mut dyn CommandRunner,
        parent: &str,
    ) -> Result<Vec<(u16, String)>> {
        // `-d` is what carries `linkinfo`; without it the vlan id is absent
        // from the JSON entirely.
        let out = runner.run(&Cmd::new("ip", &["-d", "-json", "link", "show"]))?;
        // `?` on a parse failure, matching the neighbouring host-state
        // readers: unreadable output is a genuine failure to ask, not "no
        // VLANs present" — answering the latter would let apply proceed into
        // the kernel rejection this method exists to prevent.
        let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
        let mut found = Vec::new();
        for entry in &entries {
            // Only VLANs stacked on THIS parent constrain us; the same id on
            // another device is unrelated.
            if entry.get("link").and_then(|l| l.as_str()) != Some(parent) {
                continue;
            }
            let info = entry.get("linkinfo");
            let Some(id) = info
                .and_then(|i| i.get("info_data"))
                .and_then(|d| d.get("id"))
                .and_then(|i| i.as_u64())
            else {
                continue;
            };
            let Some(name) = entry.get("ifname").and_then(|n| n.as_str()) else {
                continue;
            };
            found.push((id as u16, name.to_string()));
        }
        Ok(found)
    }

    fn is_candidate_device(&self, name: &str) -> bool {
        // Mirrors the exclusion list of the shell script this replaced, which
        // was known to pick the right parent on our hardware. Linux wired
        // names are too varied to allow-list (`eth0`, `enp0s31f6`,
        // `enx<mac>`, `eno1`, `ens5`), so exclude what is definitely not a
        // parent instead. A name containing `.` is a VLAN sub-interface.
        const VIRTUAL: &[&str] = &[
            "docker", "veth", "br-", "virbr", "vlan", "tun", "tap", "bond", "wl",
        ];
        name != "lo" && !name.contains('.') && !VIRTUAL.iter().any(|p| name.starts_with(p))
    }

    fn reverts_parent_config(&self) -> bool {
        // Easy to over-read, so stated plainly: this `true` covers parent
        // *addressing*, NOT parent *link state*. Bring-up raises the parent
        // with `ip link set <device> up`, and that is deliberately ONE-WAY —
        // neither teardown nor rollback ever brings it back down, and prior
        // link state is not recorded. By teardown time other traffic may
        // depend on that link, and downing a NIC out from under it is a
        // worse failure than leaving an idle one up. Consequence an operator
        // should know: a NIC deliberately held admin-down is left UP after
        // `vlanctl down`, and after a failed apply that rolled back.
        //
        // `ip addr del <cidr> dev <parent>` removes exactly what was added.
        true
    }

    fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
        let out = runner.run(&Cmd::new("ip", &["-json", "link", "show"]))?;
        let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
        Ok(entries
            .iter()
            .filter_map(|e| e.get("ifname")?.as_str().map(str::to_owned))
            .collect())
    }

    fn addresses_on(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<Vec<IpNet>> {
        let out = runner.run(&Cmd::new("ip", &["-json", "addr", "show", "dev", device]))?;
        let entries: Vec<serde_json::Value> = serde_json::from_str(&out)?;
        let mut nets = Vec::new();
        for e in &entries {
            for a in e
                .get("addr_info")
                .and_then(|v| v.as_array())
                .into_iter()
                .flatten()
            {
                if a.get("family").and_then(|f| f.as_str()) != Some("inet") {
                    continue;
                }
                let (Some(local), Some(len)) = (
                    a.get("local").and_then(|l| l.as_str()),
                    a.get("prefixlen").and_then(|p| p.as_u64()),
                ) else {
                    continue;
                };
                if let Ok(net) = format!("{local}/{len}").parse::<IpNet>() {
                    nets.push(net);
                }
            }
        }
        Ok(nets)
    }

    fn is_wireless(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
        // `/sys/class/net/<dev>/wireless` exists only for wireless devices.
        // Look for it in a directory listing rather than encoding the answer
        // in an exit status (`test -d`): a runner that answers every command
        // with empty output — a dry run, an unmapped stub — then reports
        // wired, the safe default, instead of turning every NIC wireless. A
        // listing that fails outright (no such device) is still an error.
        let out = runner.run(&Cmd::new("ls", &[&format!("/sys/class/net/{device}")]))?;
        Ok(out.split_whitespace().any(|entry| entry == "wireless"))
    }

    fn link_is_active(&self, runner: &mut dyn CommandRunner, device: &str) -> Result<bool> {
        // `carrier` is the recipe's proven signal (`cat carrier 2>/dev/null
        // || echo 0`). The kernel answers EINVAL for it while the interface
        // is admin-down, so the read fails; that is the answer "no link",
        // not a failure to answer. `operstate` would always be readable but
        // reports `unknown` for drivers that do not maintain it, which
        // would misfile a live NIC as inactive — so keep carrier and treat
        // an unreadable one as down.
        let carrier = runner.run(&Cmd::new(
            "cat",
            &[&format!("/sys/class/net/{device}/carrier")],
        ));
        if let Ok(s) = &carrier {
            return Ok(s.trim() == "1");
        }
        // Carrier was unreadable. That is USUALLY the admin-down EINVAL
        // above, i.e. the answer "no link" — but it is also what a broken
        // probe looks like (no `/sys`, no `cat`, permission denied), and the
        // trait contract says only a genuine failure to ask is an `Err`.
        // `operstate` tells them apart: it stays readable on an admin-down
        // device. Its VALUE is deliberately ignored — it reports `unknown`
        // for drivers that do not maintain it, which is exactly why carrier
        // is the signal — so only its readability is used here.
        runner
            .run(&Cmd::new(
                "cat",
                &[&format!("/sys/class/net/{device}/operstate")],
            ))
            .with_context(|| {
                format!(
                    "cannot determine link state for {device}: neither carrier nor \
                     operstate is readable"
                )
            })?;
        Ok(false)
    }

    fn records_created_interface(&self, cmd: &Cmd) -> bool {
        cmd.program == "ip"
            && cmd.args.first().map(|a| a == "link").unwrap_or(false)
            && cmd.args.get(1).map(|a| a == "add").unwrap_or(false)
    }
}

/// The platform this build targets, for a **real (mutating)** operation —
/// `apply` or `down` without `--dry-run`.
///
/// Returns [`MacOs`] on macOS, [`Linux`] on Linux and [`WindowsHyperV`] on
/// Windows. Every other platform returns an `Err`: returning a
/// silently-wrong platform to run mutating commands against a real network
/// stack would be far worse than refusing. A caller that already has a
/// `Platform` for this OS (for example, an embedder with its own backend)
/// should construct it explicitly rather than calling this function.
///
/// This is deliberately not used to render a **preview** (`show`, `apply
/// --dry-run`, `down --dry-run`): a preview touches no real system and must
/// keep working on every host, so it renders through [`preview_platform`]
/// instead. See that function's doc for why the two must not be conflated.
pub fn host_platform() -> Result<Box<dyn Platform>> {
    // `consts::OS` is fixed at compile time, so this is the `cfg` dispatch it
    // reads as — written as a match so the refusal below is compiled, and
    // testable, on every host rather than only on one without a backend.
    match std::env::consts::OS {
        "macos" => Ok(Box::new(MacOs)),
        "linux" => Ok(Box::new(Linux)),
        "windows" => Ok(Box::new(WindowsHyperV)),
        os => Err(no_backend_error(os)),
    }
}

/// The refusal [`host_platform`] returns on a host with no backend. Its
/// wording is a small contract of its own: it must name the platforms that
/// are supported and must not leak internal planning labels, and the test
/// for that runs on every host.
fn no_backend_error(os: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "no Platform implementation for {os}; only '{}', '{}' and '{}' are \
         implemented today. Construct a Platform explicitly if you have one \
         for this OS.",
        MacOs.name(),
        Linux.name(),
        WindowsHyperV.name(),
    )
}

/// The platform used to render a **preview** — `show`, `apply --dry-run`,
/// `down --dry-run`, `status`.
///
/// Resolves the **host's own backend** when this build has one, so a preview
/// renders what the apply it is previewing would actually run. It previously
/// returned `MacOs` unconditionally, which meant that on a Linux host
/// `apply --dry-run` printed `ifconfig vlan10 create …` while the real apply
/// ran `ip link add …` — a preview that disagreed with the thing it was
/// previewing.
///
/// Unlike [`host_platform`], this never fails: a preview must keep working on
/// any host regardless of whether this build has a backend for it, exactly as
/// it did before the `Platform` seam existed. On a host with no backend it
/// falls back to `MacOs` as a fixed reference, so the output is
/// *representative* rather than accurate — which is the same bargain the
/// function has always made, now narrowed to the hosts that genuinely have no
/// better answer.
#[must_use]
pub fn preview_platform() -> Box<dyn Platform> {
    host_platform().unwrap_or_else(|_| Box::new(MacOs))
}

/// The backend a profile of this shape gets on this host, for a real
/// operation.
///
/// Where the host has one backend this is [`host_platform`]. Windows has
/// two, and the profile decides: a single `[[interface]]` entry goes to
/// [`WindowsDriverVlan`], which sets the adapter driver's own VLAN keyword
/// and needs no virtual switch; more than one goes to [`WindowsHyperV`],
/// the only way to hold several VLANs on one adapter at once. A caller
/// that wants the other one constructs it explicitly.
pub fn host_platform_for(profile: &Profile) -> Result<Box<dyn Platform>> {
    match std::env::consts::OS {
        "windows" => Ok(windows_platform_for(profile)),
        _ => host_platform(),
    }
}

/// [`preview_platform`]'s counterpart of [`host_platform_for`]: never
/// fails, and on a host with a backend renders through the one an apply of
/// this profile would use.
#[must_use]
pub fn preview_platform_for(profile: &Profile) -> Box<dyn Platform> {
    host_platform_for(profile).unwrap_or_else(|_| Box::new(MacOs))
}

/// The Windows backend for a profile of this shape — see
/// [`host_platform_for`]. Written as its own function, and free of any
/// `cfg`, so the rule is tested on every host.
#[must_use]
pub fn windows_platform_for(profile: &Profile) -> Box<dyn Platform> {
    if profile.interfaces.len() <= 1 {
        Box::new(WindowsDriverVlan)
    } else {
        Box::new(WindowsHyperV)
    }
}

/// The backend called `name` — the string [`Platform::name`] returns and the
/// state file records — so that `down` runs through the backend that
/// applied, whatever this host would pick for a fresh profile. `None` for a
/// name no backend answers to.
#[must_use]
pub fn platform_named(name: &str) -> Option<Box<dyn Platform>> {
    match name {
        "macos" => Some(Box::new(MacOs)),
        "linux" => Some(Box::new(Linux)),
        "windows-hyperv" => Some(Box::new(WindowsHyperV)),
        "windows-driver-vlan" => Some(Box::new(WindowsDriverVlan)),
        _ => None,
    }
}

/// Interface name this entry configures: `vlan<id>` for a tagged interface,
/// or the parent `device` itself for an untagged one.
///
/// `pub(crate)`: this is macOS's fixed-decision naming, kept only for the
/// free-function equivalence tests; a real caller goes through
/// [`Platform::iface_name`] instead so the naming convention isn't
/// hardcoded on the library's public surface.
pub(crate) fn iface_name(interface: &Interface, device: &str) -> String {
    match interface.vlan {
        Some(id) => format!("vlan{id}"),
        None => device.to_string(),
    }
}

/// Build the ordered bring-up commands for one interface, taking every
/// platform-specific decision from `platform`.
///
/// `Platform::bringup_commands` owns interface creation, address and MTU;
/// [`Platform::route_commands`] owns each route and its static-ARP entry.
/// This function owns only the order and the one piece of context no
/// backend can compute for itself: whether a destination is in the
/// interface's own subnet.
pub fn bringup_commands_for(
    platform: &dyn Platform,
    interface: &Interface,
    device: &str,
) -> Vec<Cmd> {
    let name = platform.iface_name(interface, device);
    let mut cmds = platform.bringup_commands(interface, device);
    for route in &interface.routes {
        let in_subnet = destination_in_subnet(&route.destination, &interface.address);
        cmds.extend(platform.route_commands(route, in_subnet, &name));
    }
    cmds
}

/// Interface creation, address assignment, and MTU only — no routes. Shared
/// by the free [`bringup_commands`] (kept as macOS's fixed-decision baseline
/// for the equivalence test) and by [`MacOs::bringup_commands`], which owns
/// only this part; routes are a [`bringup_commands_for`] concern.
fn create_address_mtu_commands(interface: &Interface, device: &str) -> Vec<Cmd> {
    let name = iface_name(interface, device);
    let addr = interface.address.addr().to_string();
    let netmask = ipv4_netmask(interface.address.prefix_len());

    let mut cmds = Vec::new();
    match interface.vlan {
        // Tagged: create the vlan pseudo-device, then bind tag+parent in a
        // SEPARATE call (a combined `create ... vlandev` leaves it unbound),
        // then assign the address.
        Some(id) => {
            let id = id.to_string();
            cmds.push(Cmd::new("ifconfig", &[&name, "create"]));
            cmds.push(Cmd::new(
                "ifconfig",
                &[&name, "vlan", &id, "vlandev", device],
            ));
            cmds.push(Cmd::new(
                "ifconfig",
                &[&name, "inet", &addr, "netmask", &netmask],
            ));
        }
        // Untagged: add the address as an alias on the parent device. `down`
        // never removes it; apply skips this interface when the address is
        // already configured.
        None => {
            cmds.push(Cmd::new(
                "ifconfig",
                &[&name, "inet", &addr, "netmask", &netmask, "alias"],
            ));
        }
    }
    if let Some(mtu) = interface.mtu {
        cmds.push(Cmd::new("ifconfig", &[&name, "mtu", &mtu.to_string()]));
    }
    cmds
}

/// Append route (and static-ARP) commands for `routes` to `cmds`, with
/// macOS's decision (`!in_subnet`) hardcoded.
///
/// `#[cfg(test)]`: this is the INDEPENDENT baseline that
/// `macos_impl_matches_the_free_functions_it_replaces` compares
/// [`MacOs::route_commands`] against, so it deliberately keeps its own copy
/// of the emission logic. Delegating to `MacOs::route_commands` would make
/// that equivalence test compare macOS against itself and pass vacuously.
/// Production route emission goes through [`Platform::route_commands`].
#[cfg(test)]
fn append_route_commands(cmds: &mut Vec<Cmd>, routes: &[Route], addr: &IpNet, iface: &str) {
    for route in routes {
        match &route.gateway {
            Some(gateway) => {
                let gateway = gateway.to_string();
                cmds.push(Cmd::new("route", &["add", &route.destination, &gateway]));
            }
            None => {
                // A gatewayless destination inside this interface's own
                // connected subnet is reached by the connected route; an
                // explicit `-host ... -interface` route would install a
                // self-MAC ARP entry that breaks resolution, so a platform
                // that shares that hazard skips it.
                let in_subnet = destination_in_subnet(&route.destination, addr);
                if !in_subnet {
                    cmds.push(interface_route_command(&route.destination, iface));
                }
                // Static ARP for an on-link host the kernel can't resolve. The
                // `-host ... -interface` route above leaves an LLINFO entry that
                // would otherwise resolve to our own MAC (a self-MAC black-hole);
                // `arp -s` overwrites it with the real MAC. (No preceding
                // `arp -d`: on macOS that deletes the freshly-added host route,
                // breaking the `arp -s`.) Validation guarantees mac => gatewayless
                // /32, so the address parse below always succeeds.
                if let Some(mac) = &route.mac
                    && let Ok(net) = route.destination.parse::<IpNet>()
                {
                    let host = net.addr().to_string();
                    cmds.push(Cmd::new("arp", &["-s", &host, mac]));
                }
            }
        }
    }
}

/// Build the ordered commands to bring up one interface on `device`.
///
/// This is macOS's hardcoded decision (`!in_subnet`), kept as the baseline
/// the equivalence test compares `bringup_commands_for(&MacOs, ...)`
/// against. [`bringup_commands_for`] is the platform-aware equivalent used
/// by every production call site (`commands::apply`/`down`/`show_plan`).
///
/// `pub(crate)` and `#[cfg(test)]`: macOS's fixed-decision baseline, kept
/// only for that equivalence test; no production caller uses this directly
/// any more.
#[cfg(test)]
pub(crate) fn bringup_commands(interface: &Interface, device: &str) -> Vec<Cmd> {
    let name = iface_name(interface, device);
    let mut cmds = create_address_mtu_commands(interface, device);
    append_route_commands(&mut cmds, &interface.routes, &interface.address, &name);
    cmds
}

/// **macOS's** names for a profile's tagged entries (`vlan<id>`), in order.
/// Untagged entries configure the parent device and are not named here.
///
/// This is not what the profile creates on every platform: Linux names a
/// sub-interface `<parent>.<id>` when that fits, and Windows differently
/// again. It must not be used to build the collision guard or anything else
/// that has to agree with what bring-up actually creates — a guard built on
/// it would never match a live `eth0.11` and would silently never fire. The
/// only correct source for such names is [`Platform::iface_name`] on the
/// resolved device, as `commands::apply` does.
///
/// `#[cfg(test)]` and private: kept for the naming test below alone; no
/// production code has any business calling it.
#[cfg(test)]
fn interface_names(profile: &Profile) -> Vec<String> {
    profile
        .interfaces
        .iter()
        .filter_map(|i| i.vlan.map(|id| format!("vlan{id}")))
        .collect()
}

/// True when `destination` (a CIDR or bare address, e.g. `192.168.11.151/32`)
/// falls entirely within the VLAN's own connected subnet `addr`. Such a
/// destination is reached by the connected route and needs no explicit route.
/// Non-CIDR destinations like `default` are never contained.
fn destination_in_subnet(destination: &str, addr: &IpNet) -> bool {
    destination
        .parse::<IpNet>()
        .map(|dest| addr.contains(&dest))
        .unwrap_or(false)
}

/// Build a `route add ... -interface <iface>` command for a destination with no
/// gateway. A single-host destination (e.g. a `/32`) uses `-host` with the bare
/// address; anything else uses `-net` with the original CIDR.
fn interface_route_command(destination: &str, iface: &str) -> Cmd {
    if destination == "default" {
        return Cmd::new("route", &["add", "default", "-interface", iface]);
    }
    if let Ok(net) = destination.parse::<IpNet>()
        && net.prefix_len() == net.max_prefix_len()
    {
        let host = net.addr().to_string();
        return Cmd::new("route", &["add", "-host", &host, "-interface", iface]);
    }
    Cmd::new("route", &["add", "-net", destination, "-interface", iface])
}

/// Commands to tear down a single interface. Destroying the vlan interface
/// also drops its addresses and routes.
///
/// `pub(crate)`: macOS's fixed-decision teardown, kept for the free-function
/// equivalence tests; a real caller goes through
/// [`Platform::teardown_commands`] instead.
pub(crate) fn teardown_commands(iface: &str) -> Vec<Cmd> {
    vec![Cmd::new("ifconfig", &[iface, "destroy"])]
}

/// Render a dotted-quad netmask from an IPv4 prefix length.
fn ipv4_netmask(prefix: u8) -> String {
    let bits: u32 = if prefix == 0 {
        0
    } else {
        u32::MAX << (32 - prefix as u32)
    };
    format!(
        "{}.{}.{}.{}",
        (bits >> 24) & 0xff,
        (bits >> 16) & 0xff,
        (bits >> 8) & 0xff,
        bits & 0xff
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Interface, Route};
    use crate::net::RecordingRunner;
    use std::net::IpAddr;

    /// `host_platform()` must refuse cleanly (`Err`, never a panic) on a host
    /// with no `Platform` implementation at all (a BSD, say).
    ///
    /// macOS, Linux and Windows all have real backends now, so this can only
    /// be asserted on a host with none of them — which is no host this crate
    /// is developed or tested on. The wording of the refusal is checked
    /// unconditionally in
    /// `no_backend_error_names_supported_platforms_without_phase_labels`.
    #[test]
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    fn host_platform_refuses_cleanly_with_no_backend() {
        let err = host_platform()
            .map(|_| ())
            .expect_err("no Platform implementation exists for this OS yet");
        assert_eq!(
            err.to_string(),
            no_backend_error(std::env::consts::OS).to_string()
        );
    }

    /// The refusal must name a supported platform and the host it refused,
    /// and must not leak internal planning labels. Tested through the helper
    /// so this holds on every host, not only on one where `host_platform()`
    /// actually refuses — that test never runs where this crate is developed.
    #[test]
    fn no_backend_error_names_supported_platforms_without_phase_labels() {
        let msg = no_backend_error("freebsd").to_string();
        assert!(msg.contains("freebsd"), "must name the host OS: {msg}");
        assert!(
            msg.contains("macos") && msg.contains("linux") && msg.contains("windows"),
            "expected the error to name the supported platforms: {msg}"
        );
        assert!(
            !msg.contains("1a") && !msg.contains("1b"),
            "error text must not leak internal plan-phase labels: {msg}"
        );
    }

    /// On Linux, `host_platform()` now resolves to the Linux backend instead
    /// of refusing — the complement of the refuse-cleanly case above.
    #[test]
    #[cfg(target_os = "linux")]
    fn host_platform_resolves_to_linux_on_linux() {
        let platform = host_platform().expect("Linux backend must be available on Linux");
        assert_eq!(platform.name(), "linux");
    }

    /// The preview platform must always succeed, unlike `host_platform()` —
    /// a preview must keep working on any host, including one with no
    /// backend of its own.
    #[test]
    fn preview_platform_is_always_available() {
        // Whatever it resolves to, it resolves to something.
        assert!(!preview_platform().name().is_empty());
    }

    /// Every backend's `name()` must resolve back to that backend, since the
    /// state file records the name and `down` runs through whatever it
    /// resolves to. A backend whose name is not in the table would be
    /// applied by one backend and torn down by the host's default.
    #[test]
    fn every_backend_name_resolves_back_to_itself() {
        let backends: [Box<dyn Platform>; 4] = [
            Box::new(MacOs),
            Box::new(Linux),
            Box::new(WindowsHyperV),
            Box::new(WindowsDriverVlan),
        ];
        for backend in &backends {
            let named = platform_named(backend.name())
                .unwrap_or_else(|| panic!("{} is not in platform_named", backend.name()));
            assert_eq!(named.name(), backend.name());
        }
        assert!(platform_named("freebsd").is_none());
        assert!(platform_named("").is_none());
    }

    /// The Windows choice is by entry count: one entry fits in the adapter
    /// driver's single VLAN keyword, more needs the switch.
    #[test]
    fn windows_backend_is_chosen_by_the_profiles_entry_count() {
        let one: Profile =
            toml::from_str("name=\"live\"\n[[interface]]\nvlan=11\naddress=\"192.168.11.87/24\"\n")
                .unwrap();
        let two: Profile = toml::from_str(
            "name=\"lab\"\n[[interface]]\nvlan=10\naddress=\"192.168.10.90/24\"\n\
             [[interface]]\nvlan=11\naddress=\"192.168.11.87/24\"\n",
        )
        .unwrap();
        assert_eq!(windows_platform_for(&one).name(), "windows-driver-vlan");
        assert_eq!(windows_platform_for(&two).name(), "windows-hyperv");
        // Off Windows the profile changes nothing: both resolve to the
        // host's one backend (or refuse together where there is none).
        if std::env::consts::OS != "windows" {
            assert_eq!(
                host_platform_for(&one).map(|p| p.name()).ok(),
                host_platform().map(|p| p.name()).ok()
            );
        }
    }

    /// A preview must render the platform the apply would actually use.
    /// Previously this was pinned to `MacOs` on every host, so on Linux
    /// `apply --dry-run` printed `ifconfig vlan10 create …` while the real
    /// apply ran `ip link add …` — a preview that disagreed with what it was
    /// previewing (seam gap 7).
    #[test]
    #[cfg(target_os = "linux")]
    fn preview_platform_follows_the_host_backend_on_linux() {
        assert_eq!(preview_platform().name(), "linux");
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn preview_platform_follows_the_host_backend_on_macos() {
        assert_eq!(preview_platform().name(), "macos");
    }

    /// On Windows, `host_platform()` resolves to the Hyper-V backend, and a
    /// preview renders the PowerShell and `netsh` an apply would run rather
    /// than the macOS `ifconfig` it fell back to before the backend existed.
    #[test]
    #[cfg(target_os = "windows")]
    fn host_and_preview_platform_resolve_to_windows_on_windows() {
        let platform = host_platform().expect("Windows backend must be available on Windows");
        assert_eq!(platform.name(), "windows-hyperv");
        assert_eq!(preview_platform().name(), "windows-hyperv");
    }

    /// The macOS regression net, replacing the four scratch baseline files
    /// that were captured by running the binary. Those diffed whatever the
    /// binary rendered on the capturing host, so once the preview follows the
    /// host backend they would have rendered Linux commands here and stopped
    /// proving anything. Rendering through `&MacOs` explicitly is
    /// deterministic on every host, needs no binary, and is immune to
    /// platform selection.
    #[test]
    fn macos_rendering_of_a_tagged_profile_with_routes_is_pinned() {
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![
                Route {
                    destination: "192.168.11.151/32".to_string(),
                    gateway: None,
                    mac: None,
                },
                Route {
                    destination: "239.255.0.255/32".to_string(),
                    gateway: None,
                    mac: None,
                },
            ],
        };
        let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ifconfig vlan11 create",
                "ifconfig vlan11 vlan 11 vlandev en7",
                "ifconfig vlan11 inet 192.168.11.87 netmask 255.255.255.0",
                // In-subnet gatewayless: no route (self-MAC black-hole).
                // Out-of-subnet multicast group: an interface-scoped host route.
                "route add -host 239.255.0.255 -interface vlan11",
            ],
            "macOS rendering changed"
        );
    }

    #[test]
    fn macos_rendering_of_an_untagged_profile_with_static_arp_is_pinned() {
        let i = Interface {
            vlan: None,
            address: "192.168.1.100/24".parse().unwrap(),
            mtu: None,
            routes: vec![Route {
                destination: "192.168.10.151/32".to_string(),
                gateway: None,
                mac: Some("00:00:5e:00:53:01".to_string()),
            }],
        };
        let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ifconfig en7 inet 192.168.1.100 netmask 255.255.255.0 alias",
                "route add -host 192.168.10.151 -interface en7",
                "arp -s 192.168.10.151 00:00:5e:00:53:01",
            ],
            "macOS rendering changed"
        );
    }

    fn tagged(id: u16, cidr: &str) -> Interface {
        Interface {
            vlan: Some(id),
            address: cidr.parse().unwrap(),
            mtu: None,
            routes: vec![],
        }
    }

    #[test]
    fn netmask_from_prefix() {
        assert_eq!(ipv4_netmask(24), "255.255.255.0");
        assert_eq!(ipv4_netmask(16), "255.255.0.0");
        assert_eq!(ipv4_netmask(8), "255.0.0.0");
    }

    #[test]
    fn tagged_creates_assigns_and_routes() {
        let mut v = tagged(100, "192.168.10.2/24");
        v.mtu = Some(1500);
        v.routes.push(Route {
            destination: "192.168.20.0/24".to_string(),
            gateway: Some("192.168.10.1".parse::<IpAddr>().unwrap()),
            mac: None,
        });
        let rendered: Vec<String> = bringup_commands(&v, "en10")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ifconfig vlan100 create",
                "ifconfig vlan100 vlan 100 vlandev en10",
                "ifconfig vlan100 inet 192.168.10.2 netmask 255.255.255.0",
                "ifconfig vlan100 mtu 1500",
                "route add 192.168.20.0/24 192.168.10.1",
            ]
        );
    }

    #[test]
    fn tagged_routes_without_gateway() {
        let mut v = tagged(10, "192.168.10.90/24");
        v.routes.push(Route {
            destination: "192.168.10.150/32".to_string(),
            gateway: None,
            mac: None,
        });
        v.routes.push(Route {
            destination: "10.9.9.9/32".to_string(),
            gateway: None,
            mac: None,
        });
        v.routes.push(Route {
            destination: "239.255.0.0/24".to_string(),
            gateway: None,
            mac: None,
        });
        let rendered: Vec<String> = bringup_commands(&v, "en10")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(!rendered.iter().any(|c| c.contains("192.168.10.150"))); // in-subnet -> skipped
        assert!(rendered.contains(&"route add -host 10.9.9.9 -interface vlan10".to_string()));
        assert!(rendered.contains(&"route add -net 239.255.0.0/24 -interface vlan10".to_string()));
    }

    #[test]
    fn untagged_configures_parent_with_alias_and_routes() {
        let mut u = Interface {
            vlan: None,
            address: "192.168.1.100/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        u.routes.push(Route {
            destination: "192.168.10.151/32".to_string(),
            gateway: None,
            mac: None,
        });
        let rendered: Vec<String> = bringup_commands(&u, "en16")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ifconfig en16 inet 192.168.1.100 netmask 255.255.255.0 alias",
                "route add -host 192.168.10.151 -interface en16",
            ]
        );
    }

    #[test]
    fn untagged_skips_in_subnet_gatewayless_route() {
        let mut u = Interface {
            vlan: None,
            address: "192.168.10.1/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        u.routes.push(Route {
            destination: "192.168.10.152/32".to_string(),
            gateway: None,
            mac: None,
        });
        let rendered: Vec<String> = bringup_commands(&u, "en16")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec!["ifconfig en16 inet 192.168.10.1 netmask 255.255.255.0 alias"]
        );
    }

    #[test]
    fn destination_in_subnet_detects_containment() {
        let addr: IpNet = "192.168.11.87/24".parse().unwrap();
        assert!(destination_in_subnet("192.168.11.151/32", &addr));
        assert!(!destination_in_subnet("239.255.0.255/32", &addr));
        assert!(!destination_in_subnet("10.0.0.1/32", &addr));
        assert!(!destination_in_subnet("default", &addr));
    }

    #[test]
    fn teardown_destroys_interface() {
        assert_eq!(
            teardown_commands("vlan3")[0].display(),
            "ifconfig vlan3 destroy"
        );
    }

    #[test]
    fn interface_names_match_vlan_ids() {
        let p: Profile = toml::from_str(
            "name=\"t\"\n[[interface]]\nvlan=10\naddress=\"1.1.1.1/24\"\n[[interface]]\nvlan=11\naddress=\"2.2.2.2/24\"\n",
        )
        .unwrap();
        p.validate().unwrap();
        assert_eq!(interface_names(&p), vec!["vlan10", "vlan11"]);
    }

    #[test]
    fn gatewayless_host_route_with_mac_emits_static_arp() {
        let mut u = Interface {
            vlan: None,
            address: "192.168.1.100/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        u.routes.push(Route {
            destination: "192.168.10.151/32".to_string(),
            gateway: None,
            mac: Some("00:00:5e:00:53:01".to_string()),
        });
        let cmds = bringup_commands(&u, "en16");
        let rendered: Vec<String> = cmds.iter().map(|c| c.display()).collect();
        assert_eq!(
            rendered,
            vec![
                "ifconfig en16 inet 192.168.1.100 netmask 255.255.255.0 alias",
                "route add -host 192.168.10.151 -interface en16",
                "arp -s 192.168.10.151 00:00:5e:00:53:01",
            ]
        );
    }

    /// A platform whose answers are the opposite of macOS on both decisions,
    /// proving the trait actually drives behavior rather than documenting it.
    struct Contrarian;

    impl Platform for Contrarian {
        fn name(&self) -> &'static str {
            "contrarian"
        }
        fn iface_name(&self, interface: &Interface, device: &str) -> String {
            match interface.vlan {
                Some(id) => format!("{device}.{id}"),
                None => device.to_string(),
            }
        }
        fn bringup_commands(&self, _i: &Interface, _d: &str) -> Vec<Cmd> {
            vec![Cmd::new("true", &[])]
        }
        fn teardown_commands(&self, iface: &str) -> Vec<Cmd> {
            vec![Cmd::new("false", &[iface])]
        }
        // Opposite of macOS's `!in_subnet`, and DERIVED from the flag
        // rather than constant, so a test can tell whether `in_subnet` is
        // actually plumbed through. The program name is deliberately
        // neither `route` nor `ip`: this is a test double proving the seam
        // is honored, not a second Linux backend.
        fn route_commands(&self, route: &Route, in_subnet: bool, iface: &str) -> Vec<Cmd> {
            if !in_subnet {
                return vec![];
            }
            vec![Cmd::new(
                "contrarian-route",
                &["add", &route.destination, "dev", iface],
            )]
        }
        fn existing_vlans(
            &self,
            _runner: &mut dyn CommandRunner,
            _parent: &str,
        ) -> Result<Vec<(u16, String)>> {
            Ok(Vec::new())
        }
        fn is_candidate_device(&self, name: &str) -> bool {
            // Opposite of every real platform: only names starting `x` are
            // candidates, so a test can tell the decision is plumbed.
            name.starts_with('x')
        }
        fn reverts_parent_config(&self) -> bool {
            true
        }
        // Host-state reads are untested through Contrarian — it exists to
        // prove the emission/decision methods are honored, not to exercise
        // parsing. Fixed answers are enough to keep it implementing the
        // trait.
        // Reads through the runner with a vocabulary that is neither BSD
        // nor Linux, so a test can drive the listing without borrowing
        // another platform's probe.
        fn list_devices(&self, runner: &mut dyn CommandRunner) -> Result<Vec<String>> {
            let out = runner.run(&Cmd::new("contrarian-list", &[]))?;
            Ok(out.split_whitespace().map(|s| s.to_string()).collect())
        }
        fn addresses_on(
            &self,
            _runner: &mut dyn CommandRunner,
            _device: &str,
        ) -> Result<Vec<IpNet>> {
            Ok(vec![])
        }
        fn is_wireless(&self, _runner: &mut dyn CommandRunner, _device: &str) -> Result<bool> {
            Ok(false)
        }
        fn link_is_active(&self, _runner: &mut dyn CommandRunner, _device: &str) -> Result<bool> {
            Ok(false)
        }
        fn records_created_interface(&self, cmd: &Cmd) -> bool {
            cmd.program == "ip"
                && cmd.args.first().map(|a| a == "link").unwrap_or(false)
                && cmd.args.get(1).map(|a| a == "add").unwrap_or(false)
        }
    }

    #[test]
    fn a_platform_controls_interface_naming() {
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        assert_eq!(Contrarian.iface_name(&i, "eth0"), "eth0.11");
    }

    #[test]
    fn a_platform_derives_the_onlink_decision_from_in_subnet() {
        // Same route, both values of `in_subnet`: emission must follow the
        // flag, which is what proves `bringup_commands_for` plumbs it.
        let route = Route {
            destination: "192.168.11.200/32".to_string(),
            gateway: None,
            mac: None,
        };
        assert_eq!(
            Contrarian
                .route_commands(&route, true, "eth0.11")
                .iter()
                .map(|c| c.display())
                .collect::<Vec<_>>(),
            vec!["contrarian-route add 192.168.11.200/32 dev eth0.11"]
        );
        assert!(
            Contrarian
                .route_commands(&route, false, "eth0.11")
                .is_empty()
        );
    }

    #[test]
    fn a_platform_controls_reverting_parent_config() {
        assert!(Contrarian.reverts_parent_config());
    }

    #[test]
    fn linux_emits_ip_route_and_ip_neigh_not_bsd_route_and_arp() {
        let route = Route {
            destination: "192.168.11.151/32".to_string(),
            gateway: None,
            mac: Some("00:00:5e:00:53:01".to_string()),
        };
        let rendered: Vec<String> = Linux
            .route_commands(&route, true, "eth0.11")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ip route add 192.168.11.151/32 dev eth0.11",
                "ip neigh replace 192.168.11.151 lladdr 00:00:5e:00:53:01 dev eth0.11",
            ],
            "got {rendered:?}"
        );
        assert!(!rendered.iter().any(|c| c.contains("arp -s")));
    }

    #[test]
    fn macos_route_emission_is_unchanged_by_the_move() {
        let route = Route {
            destination: "192.168.11.151/32".to_string(),
            gateway: None,
            mac: Some("00:00:5e:00:53:01".to_string()),
        };
        // In-subnet on macOS: no route at all (self-MAC black-hole), arp only.
        let rendered: Vec<String> = MacOs
            .route_commands(&route, true, "vlan11")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(
            !rendered.iter().any(|c| c.starts_with("route ")),
            "got {rendered:?}"
        );
        assert!(
            rendered
                .iter()
                .any(|c| c == "arp -s 192.168.11.151 00:00:5e:00:53:01")
        );
    }

    #[test]
    fn macos_out_of_subnet_still_emits_host_route_then_arp_in_that_order() {
        let route = Route {
            destination: "192.168.10.151/32".to_string(),
            gateway: None,
            mac: Some("00:00:5e:00:53:01".to_string()),
        };
        let rendered: Vec<String> = MacOs
            .route_commands(&route, false, "en7")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "route add -host 192.168.10.151 -interface en7",
                "arp -s 192.168.10.151 00:00:5e:00:53:01",
            ],
            "order matters: arp -s overwrites the self-MAC entry the route installs, \
             and an `arp -d` between them deletes the route"
        );
    }

    #[test]
    fn macos_impl_matches_the_free_functions_it_replaces() {
        let tagged = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: Some(1500),
            routes: vec![
                Route {
                    destination: "239.255.0.255/32".to_string(),
                    gateway: None,
                    mac: None,
                },
                // In-subnet gatewayless: the in-subnet decision must come
                // out the same on both sides, or this fixture would not
                // actually be exercising it (all other routes here are
                // out-of-subnet).
                Route {
                    destination: "192.168.11.151/32".to_string(),
                    gateway: None,
                    mac: None,
                },
            ],
        };
        let untagged = Interface {
            vlan: None,
            address: "192.168.1.100/24".parse().unwrap(),
            mtu: None,
            routes: vec![Route {
                destination: "192.168.10.151/32".to_string(),
                gateway: None,
                mac: Some("00:00:5e:00:53:01".to_string()),
            }],
        };
        for i in [&tagged, &untagged] {
            assert_eq!(
                bringup_commands_for(&MacOs, i, "en7"),
                bringup_commands(i, "en7"),
                "routing bring-up through the platform must not change macOS output"
            );
            assert_eq!(MacOs.iface_name(i, "en7"), iface_name(i, "en7"));
        }
        assert_eq!(
            MacOs.teardown_commands("vlan11"),
            teardown_commands("vlan11")
        );
    }

    #[test]
    fn macos_skips_an_in_subnet_gatewayless_route_and_keeps_parent_config() {
        let route = Route {
            destination: "192.168.11.151/32".to_string(),
            gateway: None,
            mac: None,
        };
        assert!(
            MacOs.route_commands(&route, true, "en7").is_empty(),
            "an in-subnet interface-scoped host route self-MACs on macOS"
        );
        assert!(
            !MacOs.route_commands(&route, false, "en7").is_empty(),
            "out-of-subnet still needs the route"
        );
        assert!(
            !MacOs.reverts_parent_config(),
            "untagged parent config persists by design on macOS"
        );
    }

    #[test]
    fn macos_emits_no_route_for_a_gatewayless_in_subnet_destination() {
        // Retargeted from `MacOs.bringup_commands(...)`: routes now live in
        // `bringup_commands_for`, so exercising `MacOs.bringup_commands`
        // directly would pass this assertion vacuously — no platform impl
        // emits routes any more, in-subnet or not. Going through
        // `bringup_commands_for` still exercises the real hazard this test
        // guards: `Contrarian::route_commands` proves the same route WOULD
        // be emitted for a platform that wants on-link host routes, so this
        // is the in-subnet decision actually being honored, not a route loop
        // that no longer runs.
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![Route {
                destination: "192.168.11.151/32".to_string(),
                gateway: None,
                mac: None,
            }],
        };
        let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(
            !rendered.iter().any(|c| c.starts_with("route ")),
            "an in-subnet gatewayless destination must not get an interface-scoped \
             host route (it self-MACs and black-holes on macOS): {rendered:?}"
        );

        // Guard against the assertion above becoming vacuous: the same
        // in-subnet route, through a platform that wants on-link host
        // routes, must still be emitted.
        let other: Vec<String> = bringup_commands_for(&Contrarian, &i, "eth0")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(
            other.iter().any(|c| c.contains("192.168.11.151")),
            "sanity check failed: a platform that wants on-link host routes \
             must still emit one for the same in-subnet destination: {other:?}"
        );
    }

    #[test]
    fn macos_emits_a_route_add_for_a_gatewayed_destination() {
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![Route {
                destination: "192.168.20.0/24".to_string(),
                gateway: Some("192.168.11.1".parse().unwrap()),
                mac: None,
            }],
        };
        let rendered: Vec<String> = bringup_commands_for(&MacOs, &i, "en7")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(
            rendered.contains(&"route add 192.168.20.0/24 192.168.11.1".to_string()),
            "expected a route add for the gatewayed destination: {rendered:?}"
        );
    }

    #[test]
    fn a_non_ifconfig_platform_still_records_what_it_created() {
        // The bug: recording keyed off `args[1] == "create"`, which is
        // ifconfig-shaped. A Linux-shaped `ip link add link eth0 name
        // eth0.11 ...` has `link` there, so nothing was recorded and
        // rollback/down silently became no-ops.
        let create = Cmd::new(
            "ip",
            &[
                "link", "add", "link", "eth0", "name", "eth0.11", "type", "vlan", "id", "11",
            ],
        );
        assert!(
            Contrarian.records_created_interface(&create),
            "a platform must be able to recognize its own creation command"
        );
        let not_create = Cmd::new("ip", &["addr", "add", "192.168.11.87/24", "dev", "eth0.11"]);
        assert!(!Contrarian.records_created_interface(&not_create));
    }

    #[test]
    fn macos_still_recognizes_ifconfig_create_and_nothing_else() {
        assert!(MacOs.records_created_interface(&Cmd::new("ifconfig", &["vlan11", "create"])));
        assert!(!MacOs.records_created_interface(&Cmd::new(
            "ifconfig",
            &[
                "vlan11",
                "inet",
                "192.168.11.87",
                "netmask",
                "255.255.255.0"
            ]
        )));
    }

    #[test]
    fn the_collision_guard_uses_the_platforms_own_interface_names() {
        // The bug: the guard hardcoded vlan<id>, so a platform naming
        // interfaces eth0.11 was never guarded at all. Drive the real guard
        // in `commands::apply` with a platform whose naming is not macOS's,
        // and check both directions: its own name is refused, and macOS's
        // name for the same entry is not mistaken for a collision.
        let p = Profile {
            name: "t".to_owned(),
            description: None,
            device: Some("eth0".to_owned()),
            interfaces: vec![tagged(11, "192.168.11.87/24")],
        };
        let state_path = std::env::temp_dir().join("vlanctl-plan-guard-naming.json");
        let _ = std::fs::remove_file(&state_path);

        // `apply` lists live interfaces through `Platform::list_devices`,
        // so drive Contrarian's own probe with eth0.11 already present.
        let mut r = RecordingRunner::default();
        r.stdout
            .insert("contrarian-list".to_owned(), "lo0 eth0 eth0.11".to_owned());
        let err = crate::commands::apply(&mut r, &Contrarian, &p, None, &state_path, true)
            .expect_err("the platform's own interface name must be refused");
        assert!(
            err.to_string().contains("eth0.11 already exists"),
            "expected the guard to name eth0.11: {err}"
        );

        // A live vlan11 is what macOS would call this entry; under a
        // platform that names it eth0.11 it is somebody else's interface.
        let mut r = RecordingRunner::default();
        r.stdout
            .insert("contrarian-list".to_owned(), "lo0 eth0 vlan11".to_owned());
        crate::commands::apply(&mut r, &Contrarian, &p, None, &state_path, true)
            .expect("a foreign naming scheme's interface is not a collision");
    }

    #[test]
    fn the_route_decision_comes_from_the_platform_not_hardcoded() {
        // A gatewayless destination INSIDE the interface's own subnet.
        // macOS must skip it; a platform that wants on-link host routes must
        // emit it. Same profile, different commands.
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![Route {
                destination: "192.168.11.151/32".to_string(),
                gateway: None,
                mac: None,
            }],
        };

        let mac = bringup_commands_for(&MacOs, &i, "en7");
        assert!(
            !mac.iter().any(|c| c.display().contains("-host")),
            "macOS must not emit an in-subnet host route: {mac:?}"
        );

        let other = bringup_commands_for(&Contrarian, &i, "eth0");
        assert!(
            other.iter().any(|c| c.display().contains("192.168.11.151")),
            "a platform wanting on-link host routes must emit one: {other:?}"
        );
    }

    #[test]
    fn linux_names_vlan_interfaces_after_the_parent() {
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        assert_eq!(Linux.iface_name(&i, "eth0"), "eth0.11");
        let untagged = Interface {
            vlan: None,
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        assert_eq!(Linux.iface_name(&untagged, "eth0"), "eth0");
    }

    /// `<parent>.<id>` is kept only while the *parent* fits
    /// [`LINUX_MAX_DOTTED_PARENT_LEN`] (10 bytes: the kernel's 15-byte
    /// `IFNAMSIZ` limit less the widest possible suffix, `.4094`); past
    /// that the name falls back to `vlan<id>`. The decision depends only on
    /// the parent's length, never on this interface's own id, so every
    /// VLAN configured on one parent gets the same naming scheme.
    #[test]
    fn linux_falls_back_to_vlan_id_when_the_dotted_name_would_overflow_ifnamsiz() {
        // A short parent is always dotted, whatever the id's width.
        assert_eq!(
            Linux.iface_name(&tagged(11, "10.0.0.1/24"), "eth0"),
            "eth0.11"
        );
        assert_eq!(
            Linux.iface_name(&tagged(4094, "10.0.0.1/24"), "eth0"),
            "eth0.4094"
        );

        // Exactly at the boundary: a 10-byte parent + the widest suffix
        // (".4094") is 15 bytes, which still fits.
        let parent10 = "enp0s31f6a";
        assert_eq!(parent10.len(), 10);
        assert_eq!(
            Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent10),
            "enp0s31f6a.4094"
        );
        assert_eq!(
            Linux.iface_name(&tagged(1, "10.0.0.1/24"), parent10),
            "enp0s31f6a.1"
        );

        // One byte over the boundary: an 11-byte parent falls back for
        // *every* id, including a short one that would itself have fit
        // (`enp0s31f6ab.999` is only 15 bytes). This is the case the old
        // per-interface rule got wrong, mixing schemes on one parent; the
        // new rule keeps both ids on the same scheme.
        let parent11 = "enp0s31f6ab";
        assert_eq!(parent11.len(), 11);
        let short_id_name = Linux.iface_name(&tagged(999, "10.0.0.1/24"), parent11);
        let max_id_name = Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent11);
        assert_eq!(short_id_name, "vlan999");
        assert_eq!(max_id_name, "vlan4094");
        // Same scheme: both fall back, neither is dotted with the parent.
        assert!(!short_id_name.starts_with(parent11));
        assert!(!max_id_name.starts_with(parent11));
        assert!(short_id_name.starts_with("vlan") && max_id_name.starts_with("vlan"));

        // A 15-byte `enx`-style parent overflows at both id-width extremes.
        let parent15 = "enx001122334455";
        assert_eq!(parent15.len(), 15);
        assert_eq!(
            Linux.iface_name(&tagged(1, "10.0.0.1/24"), parent15),
            "vlan1"
        );
        assert_eq!(
            Linux.iface_name(&tagged(4094, "10.0.0.1/24"), parent15),
            "vlan4094"
        );

        // The fallback never overflows itself, and the untagged entry is
        // still the parent, however long.
        assert!(
            Linux
                .iface_name(&tagged(4094, "10.0.0.1/24"), parent15)
                .len()
                <= 15
        );
        let untagged = Interface {
            vlan: None,
            address: "10.0.0.1/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        assert_eq!(Linux.iface_name(&untagged, parent15), parent15);
    }

    /// The fallback name flows into every command that names the
    /// sub-interface — creation, up, address — because they all read it
    /// from `iface_name` rather than re-deriving it.
    #[test]
    fn linux_bringup_uses_the_fallback_name_consistently() {
        let cmds = Linux.bringup_commands(&tagged(11, "192.168.11.87/24"), "enx001122334455");
        let rendered: Vec<String> = cmds.iter().map(|c| c.display()).collect();
        assert_eq!(
            rendered,
            vec![
                "ip link set enx001122334455 up",
                "ip link add link enx001122334455 name vlan11 type vlan id 11",
                "ip link set vlan11 up",
                "ip addr add 192.168.11.87/24 dev vlan11",
            ]
        );
        assert!(
            !rendered.iter().any(|c| c.contains("enx001122334455.11")),
            "no command may re-derive the dotted name: {rendered:?}"
        );
    }

    #[test]
    fn linux_tagged_bringup_raises_the_parent_then_adds_ups_and_addresses() {
        // The parent must come up first, as the proven recipe does: on a
        // host whose NIC sits admin-down after boot, sub-interfaces created
        // on it are set up successfully yet stay LOWERLAYERDOWN — every
        // command succeeds and nothing works.
        let i = Interface {
            vlan: Some(11),
            address: "192.168.11.87/24".parse().unwrap(),
            mtu: Some(9000),
            routes: vec![],
        };
        let rendered: Vec<String> = Linux
            .bringup_commands(&i, "eth0")
            .iter()
            .map(|c| c.display())
            .collect();
        assert_eq!(
            rendered,
            vec![
                "ip link set eth0 up",
                "ip link add link eth0 name eth0.11 type vlan id 11",
                "ip link set eth0.11 up",
                "ip addr add 192.168.11.87/24 dev eth0.11",
                "ip link set eth0.11 mtu 9000",
            ]
        );
    }

    #[test]
    fn linux_untagged_raises_the_parent_and_creates_nothing() {
        let i = Interface {
            vlan: None,
            address: "192.168.1.100/24".parse().unwrap(),
            mtu: None,
            routes: vec![],
        };
        let rendered: Vec<String> = Linux
            .bringup_commands(&i, "eth0")
            .iter()
            .map(|c| c.display())
            .collect();
        assert!(
            !rendered.iter().any(|c| c.contains("link add")),
            "got {rendered:?}"
        );
        // The parent must be raised here too, not only on the tagged path. An
        // untagged entry configures the parent device directly, and
        // `ip addr add` SUCCEEDS on an admin-down link — then the entry's own
        // routes are emitted against a down device and the kernel rejects them
        // with ENETDOWN, aborting the apply. An untagged-only profile has no
        // later tagged entry to raise the parent at all -- and a sensor whose
        // data path is untagged puts exactly that entry first.
        assert_eq!(
            rendered,
            vec![
                "ip link set eth0 up",
                "ip addr add 192.168.1.100/24 dev eth0",
            ],
            "got {rendered:?}"
        );
    }

    #[test]
    fn linux_teardown_deletes_the_link() {
        assert_eq!(
            Linux
                .teardown_commands("eth0.11")
                .iter()
                .map(|c| c.display())
                .collect::<Vec<_>>(),
            vec!["ip link del eth0.11"]
        );
    }

    #[test]
    fn linux_wants_the_onlink_host_route_that_macos_refuses() {
        // The platform split that justifies the seam: on Linux
        // `ip route add X/32 dev Y` makes X genuinely on-link and the kernel
        // ARPs for it, which is how several hosts sharing one subnet across
        // different VLANs are reached at all. macOS answers the opposite
        // because an interface-scoped host route there installs a self-MAC
        // entry and black-holes the traffic.
        let route = Route {
            destination: "192.168.11.151/32".to_string(),
            gateway: None,
            mac: None,
        };
        assert!(!Linux.route_commands(&route, true, "eth0.11").is_empty());
        assert!(!Linux.route_commands(&route, false, "eth0.11").is_empty());
        assert!(MacOs.route_commands(&route, true, "vlan11").is_empty());
    }

    #[test]
    fn linux_reverts_parent_config_because_it_can_delete_one_address() {
        // `ip addr del <cidr> dev <parent>` removes exactly the address we
        // added, unlike macOS where an alias teardown needs `-alias` the
        // generic path cannot express.
        assert!(Linux.reverts_parent_config());
    }

    #[test]
    fn linux_recognizes_its_own_creation_command() {
        assert!(Linux.records_created_interface(&Cmd::new(
            "ip",
            &[
                "link", "add", "link", "eth0", "name", "eth0.11", "type", "vlan", "id", "11"
            ]
        )));
        assert!(!Linux.records_created_interface(&Cmd::new(
            "ip",
            &["addr", "add", "192.168.11.87/24", "dev", "eth0.11"]
        )));
        // Raising the parent creates nothing, so it must not be recorded —
        // otherwise rollback would `ip link del` the physical NIC.
        assert!(!Linux.records_created_interface(&Cmd::new("ip", &["link", "set", "eth0", "up"])));
    }

    #[test]
    fn linux_link_is_active_reads_carrier() {
        let mut r = RecordingRunner::default();
        r.stdout.insert(
            "cat /sys/class/net/eth0/carrier".to_string(),
            "1\n".to_string(),
        );
        r.stdout.insert(
            "cat /sys/class/net/eth1/carrier".to_string(),
            "0\n".to_string(),
        );
        assert!(Linux.link_is_active(&mut r, "eth0").unwrap());
        assert!(!Linux.link_is_active(&mut r, "eth1").unwrap());
    }

    #[test]
    fn linux_link_is_active_treats_an_unreadable_carrier_as_down() {
        // The kernel answers EINVAL for `carrier` on an admin-down
        // interface, so `cat` exits non-zero and the runner reports an
        // error. That is the answer "no link", not a failure to answer;
        // propagating it would abort device detection on any host with an
        // idle NIC.
        let mut r = RecordingRunner {
            fail_at: Some(0),
            ..Default::default()
        };
        assert!(
            !Linux
                .link_is_active(&mut r, "eth0")
                .expect("an unreadable carrier is not an error"),
        );
        assert_eq!(
            r.commands.len(),
            2,
            "carrier must be attempted, then operstate consulted to tell \
             admin-down apart from a device that cannot be asked at all"
        );
        assert!(
            r.commands[1].display().contains("operstate"),
            "{:?}",
            r.commands
        );
    }

    /// Fails EVERY command, which `RecordingRunner::fail_at` cannot express
    /// (it fails one index). Needed to prove the difference between "the
    /// device is down" and "the probe itself is broken".
    struct AllFailRunner {
        calls: usize,
    }

    impl CommandRunner for AllFailRunner {
        fn run(&mut self, cmd: &Cmd) -> Result<String> {
            self.calls += 1;
            anyhow::bail!("simulated total failure running `{}`", cmd.display())
        }
    }

    #[test]
    fn linux_link_is_active_errors_when_the_device_cannot_be_asked_at_all() {
        // The trait contract: "only a genuine failure to ask is an `Err`".
        // An admin-down NIC has a readable `operstate`, so if BOTH reads
        // fail the device is not merely down — /sys is missing, `cat` is
        // absent, or permission is denied. Swallowing that reports "no
        // interface is active", which either mis-refuses or auto-picks the
        // wrong NIC. For something that reconfigures networking, the failure
        // must be loud.
        let mut r = AllFailRunner { calls: 0 };
        let err = Linux
            .link_is_active(&mut r, "eth0")
            .expect_err("a wholly unaskable device must be an Err, not `false`");
        assert_eq!(r.calls, 2, "both carrier and operstate must be attempted");
        assert!(
            err.to_string().contains("eth0"),
            "the error should name the device: {err}"
        );
    }

    #[test]
    fn linux_is_wireless_looks_for_the_wireless_sysfs_entry() {
        let mut r = RecordingRunner::default();
        r.stdout.insert(
            "ls /sys/class/net/wlan0".to_string(),
            "address\ncarrier\nphy80211\nwireless\n".to_string(),
        );
        r.stdout.insert(
            "ls /sys/class/net/eth0".to_string(),
            "address\ncarrier\ndevice\n".to_string(),
        );
        assert!(Linux.is_wireless(&mut r, "wlan0").unwrap());
        assert!(!Linux.is_wireless(&mut r, "eth0").unwrap());
    }

    #[test]
    fn linux_is_wireless_defaults_to_wired_for_an_unstubbed_device() {
        // The answer comes from the listing's contents, not from whether the
        // command succeeded: a runner that answers every command with empty
        // output (a dry run, an unmapped stub) must not turn every NIC
        // wireless.
        let mut r = RecordingRunner::default();
        assert!(!Linux.is_wireless(&mut r, "eth0").unwrap());
    }

    #[test]
    fn linux_candidate_devices_exclude_loopback_virtual_and_vlan_subinterfaces() {
        // Mirrors that same predicate. `eth0` is the real
        // parent on this hardware and the macOS `starts_with("en")` filter
        // would have excluded it outright, which is why candidate selection
        // has to live behind the seam.
        for ok in ["eth0", "enp0s31f6", "enx00e04c680001", "eno1", "ens5"] {
            assert!(Linux.is_candidate_device(ok), "{ok} should be a candidate");
        }
        for no in [
            "lo",
            "docker0",
            "veth1a2b",
            "br-abc123",
            "virbr0",
            "vlan11",
            "tun0",
            "tap0",
            "bond0",
            "wlp0s20f3",
        ] {
            assert!(
                !Linux.is_candidate_device(no),
                "{no} must not be a candidate"
            );
        }
        // A VLAN sub-interface we created is never a parent candidate.
        assert!(!Linux.is_candidate_device("eth0.11"));
    }

    #[test]
    fn macos_candidates_are_en_prefixed_and_exclude_vlan_subinterfaces() {
        assert!(MacOs.is_candidate_device("en7"));
        assert!(!MacOs.is_candidate_device("lo0"));
        assert!(!MacOs.is_candidate_device("bridge0"));
        // Pre-existing gap: `en0.100` is a VLAN sub-interface, not a parent,
        // and the bare `starts_with("en")` filter counted it as a candidate.
        assert!(
            !MacOs.is_candidate_device("en0.100"),
            "a vlan sub-interface is not a parent candidate"
        );
    }

    #[test]
    fn linux_existing_vlans_reports_ids_with_the_names_holding_them() {
        // Fixture is real `ip -d -json link show` output from the bench.
        let mut r = RecordingRunner::default();
        r.stdout.insert(
            "ip -d -json link show".to_string(),
            r#"[
              {"ifname":"lo"},
              {"ifname":"eth0"},
              {"ifname":"vlan11","link":"eth0",
               "linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":11}}},
              {"ifname":"vlan10","link":"eth0",
               "linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":10}}},
              {"ifname":"other.7","link":"eth9",
               "linkinfo":{"info_kind":"vlan","info_data":{"protocol":"802.1Q","id":7}}}
            ]"#
            .to_string(),
        );
        let mut got = Linux.existing_vlans(&mut r, "eth0").unwrap();
        got.sort();
        assert_eq!(
            got,
            vec![(10, "vlan10".to_string()), (11, "vlan11".to_string())],
            "only VLANs on the named parent count; eth9's id 7 must not appear"
        );
    }

    #[test]
    fn macos_reports_no_vlan_id_constraint() {
        // Documented as "no constraint we know of beyond names": macOS
        // addresses VLANs by name and the name guard already covers that.
        // Returning empty keeps macOS behaviour and its baselines untouched
        // rather than inventing a constraint we have not verified on BSD.
        let mut r = RecordingRunner::default();
        assert!(MacOs.existing_vlans(&mut r, "en7").unwrap().is_empty());
        assert!(
            r.commands.is_empty(),
            "macOS must not issue a probe for a constraint it does not enforce"
        );
    }

    #[test]
    fn linux_host_state_reads_use_ip_json_not_ifconfig() {
        let mut r = RecordingRunner::default();
        r.stdout.insert(
            "ip -json link show".to_string(),
            r#"[{"ifname":"lo"},{"ifname":"eth0"}]"#.to_string(),
        );
        assert_eq!(Linux.list_devices(&mut r).unwrap(), vec!["lo", "eth0"]);
    }

    #[test]
    fn linux_addresses_on_keeps_only_complete_inet_entries() {
        let mut r = RecordingRunner::default();
        r.stdout.insert(
            "ip -json addr show dev eth0".to_string(),
            r#"[{
                "ifname": "eth0",
                "addr_info": [
                    {"family": "inet", "local": "192.168.11.87", "prefixlen": 24},
                    {"family": "inet6", "local": "fe80::1", "prefixlen": 64},
                    {"family": "inet", "prefixlen": 24},
                    {"family": "inet", "local": "192.168.11.88"}
                ]
            }]"#
            .to_string(),
        );
        let nets = Linux.addresses_on(&mut r, "eth0").unwrap();
        assert_eq!(
            nets,
            vec!["192.168.11.87/24".parse::<IpNet>().unwrap()],
            "expected the inet6 entry excluded and both incomplete inet \
             entries (missing local, missing prefixlen) skipped: {nets:?}"
        );
    }
}