coding-agent-search 0.6.0

Unified TUI search over local coding agent histories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
//! Configuration types for remote sources.
//!
//! This module defines the data structures for configuring remote sources
//! that cass can sync agent sessions from. Configuration is stored in TOML
//! format at `~/.config/cass/sources.toml` (or XDG equivalent).
//!
//! # Example Configuration
//!
//! ```toml
//! [[sources]]
//! name = "laptop"
//! type = "ssh"
//! host = "user@laptop.local"
//! paths = ["~/.claude/projects", "~/.cursor"]
//! sync_schedule = "manual"
//!
//! [[sources]]
//! name = "workstation"
//! type = "ssh"
//! host = "user@work.example.com"
//! paths = ["~/.claude/projects"]
//! sync_schedule = "daily"
//!
//! # Path mappings rewrite remote paths to local equivalents
//! [[sources.path_mappings]]
//! from = "/home/user/projects"
//! to = "/Users/me/projects"
//!
//! # Agent-specific mappings only apply when viewing specific agent sessions
//! [[sources.path_mappings]]
//! from = "/opt/work"
//! to = "/Volumes/Work"
//! agents = ["claude-code"]
//!
//! # Disable noisy connectors globally, including the built-in local source.
//! disabled_agents = ["openclaw"]
//! ```

use serde::{Deserialize, Serialize};
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

use super::provenance::SourceKind;

// Re-export types from franken_agent_detection.
pub use franken_agent_detection::{PathMapping, Platform};

const BUILT_IN_LOCAL_SOURCE_NAME: &str = "local";
const RESERVED_REMOTE_SOURCE_SUFFIX: &str = "-ssh";

pub(crate) fn source_name_key(name: &str) -> String {
    name.trim().to_ascii_lowercase()
}

pub(crate) fn source_names_equal(lhs: &str, rhs: &str) -> bool {
    source_name_key(lhs) == source_name_key(rhs)
}

pub(crate) fn agent_name_key(name: &str) -> String {
    name.trim().to_ascii_lowercase().replace('-', "_")
}

fn normalize_agent_config_name(name: &str) -> Option<String> {
    let normalized = match agent_name_key(name).as_str() {
        "claude_code" => "claude".to_string(),
        "open_claw" => "openclaw".to_string(),
        other => other.to_string(),
    };
    (!normalized.is_empty()).then_some(normalized)
}

fn agent_config_names_equal(lhs: &str, rhs: &str) -> bool {
    match (
        normalize_agent_config_name(lhs),
        normalize_agent_config_name(rhs),
    ) {
        (Some(lhs), Some(rhs)) => lhs == rhs,
        _ => false,
    }
}

fn path_mapping_applies_to_agent(mapping: &PathMapping, agent: Option<&str>) -> bool {
    match (
        mapping.agents.as_ref(),
        agent.and_then(|value| {
            let trimmed = value.trim();
            (!trimmed.is_empty()).then_some(trimmed)
        }),
    ) {
        (Some(agents), _) if agents.is_empty() => false,
        (None, _) | (Some(_), None) => true,
        (Some(agents), Some(actual)) => agents
            .iter()
            .any(|allowed| agent_config_names_equal(allowed, actual)),
    }
}

/// Errors that can occur when loading or saving source configuration.
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Failed to read config file: {0}")]
    Read(#[from] std::io::Error),

    #[error("Failed to parse config file: {0}")]
    Parse(#[from] toml::de::Error),

    #[error("Failed to serialize config: {0}")]
    Serialize(#[from] toml::ser::Error),

    #[error("Could not determine config directory")]
    NoConfigDir,

    #[error("Validation error: {0}")]
    Validation(String),
}

/// Root configuration containing all source definitions.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SourcesConfig {
    /// List of configured sources.
    #[serde(default)]
    pub sources: Vec<SourceDefinition>,

    /// Connectors to skip during indexing even if their files exist locally or
    /// in configured remote mirrors.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub disabled_agents: Vec<String>,
}

/// Definition of a single source (local or remote).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SourceDefinition {
    /// Friendly name for this source (e.g., "laptop", "workstation").
    /// This becomes the `source_id` used throughout the system.
    pub name: String,

    /// Connection type (local, ssh, etc.).
    #[serde(rename = "type", default)]
    pub source_type: SourceKind,

    /// Remote host for SSH connections (e.g., "user@laptop.local").
    #[serde(default)]
    pub host: Option<String>,

    /// Paths to sync from this source.
    /// For SSH sources, these are remote paths.
    /// Supports ~ expansion.
    #[serde(default)]
    pub paths: Vec<String>,

    /// When to automatically sync this source.
    #[serde(default)]
    pub sync_schedule: SyncSchedule,

    /// Path mappings for workspace rewriting.
    /// Maps remote paths to local equivalents.
    /// Example: "/home/user/projects" -> "/Users/me/projects"
    #[serde(default)]
    pub path_mappings: Vec<PathMapping>,

    /// Platform hint for default paths (macos, linux).
    #[serde(default)]
    pub platform: Option<Platform>,
}

impl SourceDefinition {
    /// Create a new local source definition.
    pub fn local(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            source_type: SourceKind::Local,
            ..Default::default()
        }
    }

    /// Create a new SSH source definition.
    pub fn ssh(name: impl Into<String>, host: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            source_type: SourceKind::Ssh,
            host: Some(host.into()),
            ..Default::default()
        }
    }

    /// Check if this source requires SSH connectivity.
    pub fn is_remote(&self) -> bool {
        matches!(self.source_type, SourceKind::Ssh)
    }

    /// Validate the source definition.
    pub fn validate(&self) -> Result<(), ConfigError> {
        self.validate_structure()?;
        self.validate_paths()
    }

    pub(crate) fn validate_name(&self) -> Result<(), ConfigError> {
        validate_source_name(&self.name)
    }

    pub(crate) fn validate_structure(&self) -> Result<(), ConfigError> {
        self.validate_name()?;

        if self.is_remote() && self.host.is_none() {
            return Err(ConfigError::Validation("SSH sources require a host".into()));
        }

        if self.is_remote()
            && let Some(host) = self.host.as_deref()
        {
            validate_ssh_host(host)?;
        }

        for (idx, mapping) in self.path_mappings.iter().enumerate() {
            if mapping.from.trim().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "path_mappings[{idx}].from cannot be empty"
                )));
            }

            if mapping.to.trim().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "path_mappings[{idx}].to cannot be empty"
                )));
            }

            if let Some(agents) = mapping.agents.as_ref() {
                if agents.is_empty() {
                    return Err(ConfigError::Validation(format!(
                        "path_mappings[{idx}].agents cannot be empty"
                    )));
                }

                if agents.iter().any(|agent| agent.trim().is_empty()) {
                    return Err(ConfigError::Validation(format!(
                        "path_mappings[{idx}].agents cannot contain empty agent names"
                    )));
                }
            }
        }

        Ok(())
    }

    fn validate_paths(&self) -> Result<(), ConfigError> {
        for (idx, path) in self.paths.iter().enumerate() {
            validate_source_path_entry(idx, path)?;
        }

        Ok(())
    }

    /// Apply path mapping to rewrite a workspace path.
    ///
    /// Uses longest-prefix matching. If an agent is specified,
    /// only mappings that apply to that agent are considered.
    pub fn rewrite_path(&self, path: &str) -> String {
        self.rewrite_path_for_agent(path, None)
    }

    /// Apply path mapping for a specific agent.
    ///
    /// Uses longest-prefix matching, filtering by agent.
    pub fn rewrite_path_for_agent(&self, path: &str, agent: Option<&str>) -> String {
        // Sort by prefix length descending for longest-prefix match
        let mut mappings: Vec<_> = self
            .path_mappings
            .iter()
            .filter(|m| path_mapping_applies_to_agent(m, agent))
            .collect();
        mappings.sort_by_key(|m| std::cmp::Reverse(m.from.len()));

        for mapping in mappings {
            if let Some(rewritten) = mapping.apply(path) {
                return rewritten;
            }
        }

        path.to_string()
    }
}

/// Adjust an auto-generated remote source name to avoid reserved built-in IDs.
pub(crate) fn normalize_generated_remote_source_name(name: &str) -> String {
    let name = name.trim();
    if source_names_equal(name, BUILT_IN_LOCAL_SOURCE_NAME) {
        format!("{name}{RESERVED_REMOTE_SOURCE_SUFFIX}")
    } else {
        name.to_string()
    }
}

fn has_dot_components(path: &Path) -> bool {
    path.components()
        .any(|c| matches!(c, Component::CurDir | Component::ParentDir))
}

fn validate_source_name(name: &str) -> Result<(), ConfigError> {
    if name.trim().is_empty() {
        return Err(ConfigError::Validation(
            "Source name cannot be empty".into(),
        ));
    }

    if name.trim() != name {
        return Err(ConfigError::Validation(
            "Source name cannot have leading or trailing whitespace".into(),
        ));
    }

    if source_names_equal(name, BUILT_IN_LOCAL_SOURCE_NAME) {
        return Err(ConfigError::Validation(format!(
            "Source name '{}' is reserved for the built-in local source",
            BUILT_IN_LOCAL_SOURCE_NAME
        )));
    }

    if name.contains('/') || name.contains('\\') {
        return Err(ConfigError::Validation(
            "Source name cannot contain path separators".into(),
        ));
    }

    if has_dot_components(Path::new(name)) {
        return Err(ConfigError::Validation(
            "Source name cannot be '.' or '..'".into(),
        ));
    }

    Ok(())
}

fn validate_ssh_host(host: &str) -> Result<(), ConfigError> {
    let trimmed = host.trim();

    if trimmed.is_empty() {
        return Err(ConfigError::Validation("SSH host cannot be empty".into()));
    }

    if trimmed != host {
        return Err(ConfigError::Validation(
            "SSH host cannot have leading or trailing whitespace".into(),
        ));
    }

    let host = trimmed;

    if host.starts_with('-') {
        return Err(ConfigError::Validation(
            "SSH host cannot start with '-' (would be parsed as an ssh option)".into(),
        ));
    }

    if host.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err(ConfigError::Validation(
            "SSH host cannot contain whitespace or control characters".into(),
        ));
    }

    if !ssh_host_has_safe_token_chars(host) {
        return Err(ConfigError::Validation(
            "SSH host may only contain ASCII letters, digits, '.', '-', '_', and '@'".into(),
        ));
    }

    validate_optional_user_host_shape(host).map_err(ConfigError::Validation)?;

    Ok(())
}

pub(crate) fn source_path_entry_error(index: usize, path: &str) -> Option<String> {
    if path.trim().is_empty() {
        return Some(format!("paths[{index}] cannot be empty"));
    }

    if path.trim() != path {
        return Some(format!(
            "paths[{index}] cannot have leading or trailing whitespace"
        ));
    }

    if path.chars().any(char::is_control) {
        return Some(format!("paths[{index}] cannot contain control characters"));
    }

    None
}

fn validate_source_path_entry(index: usize, path: &str) -> Result<(), ConfigError> {
    match source_path_entry_error(index, path) {
        Some(message) => Err(ConfigError::Validation(message)),
        None => Ok(()),
    }
}

pub(crate) fn ssh_host_has_safe_token_chars(host: &str) -> bool {
    host.chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '@'))
}

pub(crate) fn validate_optional_user_host_shape(host: &str) -> Result<(), String> {
    match host.split_once('@') {
        Some((user, hostname)) if user.is_empty() || hostname.is_empty() => {
            Err("SSH host must not have an empty user or hostname around '@'".into())
        }
        Some((_, hostname)) if hostname.contains('@') => {
            Err("SSH host must contain at most one '@' separator".into())
        }
        _ => Ok(()),
    }
}

/// Sync schedule for remote sources.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SyncSchedule {
    /// Only sync when explicitly requested.
    #[default]
    Manual,
    /// Sync every hour.
    Hourly,
    /// Sync once per day.
    Daily,
}

const SYNC_SCHEDULE_MANUAL: &str = "manual";
const SYNC_SCHEDULE_HOURLY: &str = "hourly";
const SYNC_SCHEDULE_DAILY: &str = "daily";

impl std::fmt::Display for SyncSchedule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Manual => SYNC_SCHEDULE_MANUAL,
            Self::Hourly => SYNC_SCHEDULE_HOURLY,
            Self::Daily => SYNC_SCHEDULE_DAILY,
        })
    }
}

impl SourcesConfig {
    /// Load configuration from the default location.
    ///
    /// Returns an empty config if the file doesn't exist.
    pub fn load() -> Result<Self, ConfigError> {
        let config_path = Self::config_path()?;

        if !config_path.exists() {
            return Ok(Self::default());
        }

        let content = std::fs::read_to_string(&config_path)?;
        let config: Self = toml::from_str(&content)?;

        config.validate_for_load()?;

        Ok(config)
    }

    /// Load configuration from a specific path.
    pub fn load_from(path: &PathBuf) -> Result<Self, ConfigError> {
        if !path.exists() {
            return Ok(Self::default());
        }

        let content = std::fs::read_to_string(path)?;
        let config: Self = toml::from_str(&content)?;
        config.validate_for_load()?;

        Ok(config)
    }

    /// Save configuration to the default location.
    pub fn save(&self) -> Result<(), ConfigError> {
        let config_path = Self::config_path()?;

        // Create parent directories if needed
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        self.validate()?;
        let content = toml::to_string_pretty(self)?;
        let _: SourcesConfig = toml::from_str(&content)?;
        let temp_path = unique_atomic_temp_path(&config_path);
        std::fs::write(&temp_path, content)?;
        sync_file_path(&temp_path)?;
        replace_file_from_temp(&temp_path, &config_path)?;

        Ok(())
    }

    /// Save configuration to a specific path.
    pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        self.validate()?;
        let content = toml::to_string_pretty(self)?;
        let _: SourcesConfig = toml::from_str(&content)?;
        let temp_path = unique_atomic_temp_path(path);
        std::fs::write(&temp_path, content)?;
        sync_file_path(&temp_path)?;
        replace_file_from_temp(&temp_path, path)?;

        Ok(())
    }

    /// Get the default configuration file path.
    ///
    /// Uses XDG conventions:
    /// - Primary: `$XDG_CONFIG_HOME/cass/sources.toml`
    /// - Fallback: platform-specific config dir (e.g., `~/.config/cass/sources.toml` on Linux)
    pub fn config_path() -> Result<PathBuf, ConfigError> {
        config_path_from_parts(
            dotenvy::var("XDG_CONFIG_HOME").ok().map(PathBuf::from),
            dirs::config_dir(),
            dirs::home_dir(),
        )
    }

    /// Validate all sources in the configuration.
    pub fn validate(&self) -> Result<(), ConfigError> {
        self.validate_with_path_entries(true)
    }

    fn validate_for_load(&self) -> Result<(), ConfigError> {
        self.validate_with_path_entries(false)
    }

    fn validate_with_path_entries(&self, validate_paths: bool) -> Result<(), ConfigError> {
        // Check for duplicate names
        let mut seen_names = std::collections::HashSet::new();
        for source in &self.sources {
            if validate_paths {
                source.validate()?;
            } else {
                source.validate_structure()?;
            }

            if !seen_names.insert(source_name_key(&source.name)) {
                return Err(ConfigError::Validation(format!(
                    "Duplicate source name: {}",
                    source.name
                )));
            }
        }

        for (idx, agent) in self.disabled_agents.iter().enumerate() {
            if normalize_agent_config_name(agent).is_none() {
                return Err(ConfigError::Validation(format!(
                    "disabled_agents[{idx}] cannot be empty"
                )));
            }
        }

        Ok(())
    }

    /// Find a source by name.
    pub fn find_source(&self, name: &str) -> Option<&SourceDefinition> {
        self.sources
            .iter()
            .find(|s| source_names_equal(&s.name, name))
    }

    /// Find a source by name (mutable).
    pub fn find_source_mut(&mut self, name: &str) -> Option<&mut SourceDefinition> {
        self.sources
            .iter_mut()
            .find(|s| source_names_equal(&s.name, name))
    }

    /// Add a new source. Returns error if name already exists.
    pub fn add_source(&mut self, source: SourceDefinition) -> Result<(), ConfigError> {
        source.validate()?;

        if self
            .sources
            .iter()
            .any(|s| source_names_equal(&s.name, &source.name))
        {
            return Err(ConfigError::Validation(format!(
                "Source '{}' already exists",
                source.name
            )));
        }

        self.sources.push(source);
        Ok(())
    }

    /// Remove a source by name. Returns true if found and removed.
    pub fn remove_source(&mut self, name: &str) -> bool {
        let initial_len = self.sources.len();
        self.sources.retain(|s| !source_names_equal(&s.name, name));
        self.sources.len() < initial_len
    }

    /// Get all remote sources (SSH type).
    pub fn remote_sources(&self) -> impl Iterator<Item = &SourceDefinition> {
        self.sources.iter().filter(|s| s.is_remote())
    }

    pub fn configured_disabled_agents(&self) -> Vec<String> {
        let mut disabled = self
            .disabled_agents
            .iter()
            .filter_map(|agent| normalize_agent_config_name(agent))
            .collect::<Vec<_>>();
        disabled.sort();
        disabled.dedup();
        disabled
    }

    pub fn is_agent_disabled(&self, agent: &str) -> bool {
        let Some(normalized) = normalize_agent_config_name(agent) else {
            return false;
        };
        self.disabled_agents
            .iter()
            .filter_map(|candidate| normalize_agent_config_name(candidate))
            .any(|candidate| candidate == normalized)
    }

    pub fn exclude_agent_from_indexing(&mut self, agent: &str) -> Result<bool, ConfigError> {
        let normalized = normalize_agent_config_name(agent)
            .ok_or_else(|| ConfigError::Validation("agent name cannot be empty".into()))?;
        if self.is_agent_disabled(&normalized) {
            return Ok(false);
        }
        self.disabled_agents.push(normalized);
        Ok(true)
    }

    pub fn include_agent_in_indexing(&mut self, agent: &str) -> Result<bool, ConfigError> {
        let normalized = normalize_agent_config_name(agent)
            .ok_or_else(|| ConfigError::Validation("agent name cannot be empty".into()))?;
        let initial_len = self.disabled_agents.len();
        self.disabled_agents.retain(|existing| {
            normalize_agent_config_name(existing).as_deref() != Some(&normalized)
        });
        Ok(self.disabled_agents.len() != initial_len)
    }
}

fn config_path_from_parts(
    xdg_config_home: Option<PathBuf>,
    platform_config_dir: Option<PathBuf>,
    home_dir: Option<PathBuf>,
) -> Result<PathBuf, ConfigError> {
    // Respect XDG_CONFIG_HOME first (important for testing and Linux users).
    if let Some(xdg_config) = xdg_config_home {
        return Ok(xdg_config.join("cass").join("sources.toml"));
    }

    // Check the platform-specific config dir (e.g. ~/Library/Application Support/ on macOS).
    let platform_path = platform_config_dir.map(|p| p.join("cass").join("sources.toml"));
    if let Some(ref path) = platform_path
        && path.exists()
    {
        return Ok(path.clone());
    }

    // Fallback: check ~/.config/cass/sources.toml for users who follow XDG
    // conventions without setting XDG_CONFIG_HOME.
    if let Some(home) = home_dir {
        let dot_config_path = home.join(".config").join("cass").join("sources.toml");
        if dot_config_path.exists() {
            return Ok(dot_config_path);
        }
    }

    // Neither exists: return the platform path for creation (original behavior).
    platform_path.ok_or(ConfigError::NoConfigDir)
}

/// Get preset paths for a given platform.
///
/// These are the default agent session directories for each platform.
pub fn get_preset_paths(preset: &str) -> Result<Vec<String>, ConfigError> {
    match preset {
        "macos-defaults" | "macos" => Ok(vec![
            "~/.claude/projects".into(),
            "~/.codex/sessions".into(),
            "~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev".into(),
            "~/Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline"
                .into(),
            "~/Library/Application Support/Cursor/User/globalStorage/saoudrizwan.claude-dev".into(),
            "~/Library/Application Support/Cursor/User/globalStorage/rooveterinaryinc.roo-cline"
                .into(),
            "~/Library/Application Support/com.openai.chat".into(),
            "~/.gemini/tmp".into(),
            "~/.pi/agent/sessions".into(),
            "~/Library/Application Support/opencode/storage".into(),
            "~/.continue/sessions".into(),
            "~/.aider.chat.history.md".into(),
            "~/.goose/sessions".into(),
        ]),
        "linux-defaults" | "linux" => Ok(vec![
            "~/.claude/projects".into(),
            "~/.codex/sessions".into(),
            "~/.config/Code/User/globalStorage/saoudrizwan.claude-dev".into(),
            "~/.config/Code/User/globalStorage/rooveterinaryinc.roo-cline".into(),
            "~/.config/Cursor/User/globalStorage/saoudrizwan.claude-dev".into(),
            "~/.config/Cursor/User/globalStorage/rooveterinaryinc.roo-cline".into(),
            "~/.gemini/tmp".into(),
            "~/.pi/agent/sessions".into(),
            "~/.local/share/opencode/storage".into(),
            "~/.continue/sessions".into(),
            "~/.aider.chat.history.md".into(),
            "~/.goose/sessions".into(),
        ]),
        _ => Err(ConfigError::Validation(format!(
            "Unknown preset: '{}'. Valid presets: macos-defaults, linux-defaults",
            preset
        ))),
    }
}

// =============================================================================
// SSH Config Discovery
// =============================================================================

/// Discovered SSH host from ~/.ssh/config
#[derive(Debug, Clone)]
pub struct DiscoveredHost {
    /// Host alias from SSH config
    pub name: String,
    /// Hostname or IP address
    pub hostname: Option<String>,
    /// Username
    pub user: Option<String>,
    /// Port (defaults to 22)
    pub port: Option<u16>,
    /// Identity file path
    pub identity_file: Option<String>,
}

impl DiscoveredHost {
    /// Get the SSH connection string (user@host or just host)
    pub fn connection_string(&self) -> String {
        if let Some(user) = &self.user {
            format!("{}@{}", user, self.name)
        } else {
            self.name.clone()
        }
    }
}

/// Discover SSH hosts from ~/.ssh/config.
///
/// Parses the SSH config file and returns a list of discovered hosts
/// that could be used as remote sources.
pub fn discover_ssh_hosts() -> Vec<DiscoveredHost> {
    let ssh_config_path = dirs::home_dir()
        .map(|h| h.join(".ssh").join("config"))
        .unwrap_or_default();

    if !ssh_config_path.exists() {
        return Vec::new();
    }

    let content = match std::fs::read_to_string(&ssh_config_path) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };

    parse_ssh_config(&content)
}

/// Parse SSH config file content into discovered hosts.
fn parse_ssh_config(content: &str) -> Vec<DiscoveredHost> {
    let mut hosts = Vec::new();
    let mut current_hosts: Vec<DiscoveredHost> = Vec::new();

    for line in content.lines() {
        let line = line.trim();

        // Skip comments and empty lines
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Parse key-value pairs
        let (key, value) = if let Some(idx) = line.find(|c: char| c.is_whitespace() || c == '=') {
            let k = &line[..idx];
            let v = line[idx..].trim_start_matches(|c: char| c.is_whitespace() || c == '=');
            (k.to_lowercase(), v)
        } else {
            continue;
        };

        match key.as_str() {
            "host" => {
                hosts.append(&mut current_hosts);
                current_hosts = value
                    .split_whitespace()
                    .filter(|name| {
                        !name.starts_with('!') && !name.contains('*') && !name.contains('?')
                    })
                    .map(|name| DiscoveredHost {
                        name: name.to_string(),
                        hostname: None,
                        user: None,
                        port: None,
                        identity_file: None,
                    })
                    .collect();
            }
            "hostname" => {
                for host in &mut current_hosts {
                    host.hostname = Some(value.to_string());
                }
            }
            "user" => {
                for host in &mut current_hosts {
                    host.user = Some(value.to_string());
                }
            }
            "port" => {
                for host in &mut current_hosts {
                    host.port = value.parse().ok();
                }
            }
            "identityfile" => {
                for host in &mut current_hosts {
                    host.identity_file = Some(value.to_string());
                }
            }
            _ => {}
        }
    }

    // Don't forget the last host block.
    hosts.append(&mut current_hosts);

    hosts
}

// =============================================================================
// Source Configuration Generator
// =============================================================================

use std::collections::HashSet;

use colored::Colorize;

use super::probe::HostProbeResult;

/// Result of merging a source into existing configuration.
#[derive(Debug, Clone)]
pub enum MergeResult {
    /// Source was added successfully.
    Added(SourceDefinition),
    /// Source already exists with this name.
    AlreadyExists(String),
}

/// Reason why a source was skipped during config generation.
#[derive(Debug, Clone)]
pub enum SkipReason {
    /// Already configured in sources.toml.
    AlreadyConfigured,
    /// Another selected host generates the same source name.
    GeneratedNameConflict(String),
    /// Generated source definition failed validation.
    InvalidSourceDefinition(String),
    /// Probe failed (unreachable, timeout, etc.).
    ProbeFailure(String),
    /// User deselected this host.
    UserDeselected,
}

/// Information about a backup created before config modification.
#[derive(Debug, Clone)]
pub struct BackupInfo {
    /// Path to the backup file (None if no existing config).
    pub backup_path: Option<PathBuf>,
    /// Path to the config file.
    pub config_path: PathBuf,
}

/// Preview of configuration changes before writing.
#[derive(Debug, Clone)]
pub struct ConfigPreview {
    /// Sources that will be added.
    pub sources_to_add: Vec<SourceDefinition>,
    /// Sources that were skipped with reasons.
    pub sources_skipped: Vec<(String, SkipReason)>,
}

impl ConfigPreview {
    /// Create a new empty preview.
    pub fn new() -> Self {
        Self {
            sources_to_add: Vec::new(),
            sources_skipped: Vec::new(),
        }
    }

    /// Display the preview to the user.
    pub fn display(&self) {
        println!();
        println!("{}", "Configuration Preview".bold().underline());

        if self.sources_to_add.is_empty() {
            println!("  {}", "No new sources to add.".dimmed());
        } else {
            println!("  The following will be added to sources.toml:\n");

            for source in &self.sources_to_add {
                println!("  {}:", source.name.cyan());
                println!("    {}:", "Paths".dimmed());
                for path in &source.paths {
                    println!("      {}", path);
                }
                if !source.path_mappings.is_empty() {
                    println!("    {}:", "Mappings".dimmed());
                    for mapping in &source.path_mappings {
                        println!("      {} → {}", mapping.from, mapping.to);
                    }
                }
                println!();
            }
        }

        if !self.sources_skipped.is_empty() {
            println!("  {}:", "Skipped".dimmed());
            for (name, reason) in &self.sources_skipped {
                let reason_str = match reason {
                    SkipReason::AlreadyConfigured => "already configured",
                    SkipReason::GeneratedNameConflict(source_name) => {
                        println!(
                            "    {} - {}",
                            name.dimmed(),
                            format!("conflicts with generated source name '{source_name}'")
                                .dimmed()
                        );
                        continue;
                    }
                    SkipReason::InvalidSourceDefinition(e) => e.as_str(),
                    SkipReason::ProbeFailure(e) => e.as_str(),
                    SkipReason::UserDeselected => "not selected",
                };
                println!("    {} - {}", name.dimmed(), reason_str.dimmed());
            }
        }
    }

    /// Check if there are any sources to add.
    pub fn has_changes(&self) -> bool {
        !self.sources_to_add.is_empty()
    }

    /// Get the count of sources to add.
    pub fn add_count(&self) -> usize {
        self.sources_to_add.len()
    }
}

impl Default for ConfigPreview {
    fn default() -> Self {
        Self::new()
    }
}

/// Generator for creating source configurations from probe results.
///
/// Takes probe results and generates appropriate `SourceDefinition` objects
/// with intelligent path and mapping defaults.
pub struct SourceConfigGenerator {
    /// Local home directory for mapping generation.
    local_home: PathBuf,
}

impl SourceConfigGenerator {
    /// Create a new config generator.
    pub fn new() -> Self {
        Self {
            local_home: dirs::home_dir().unwrap_or_else(|| PathBuf::from("~")),
        }
    }

    /// Generate a complete SourceDefinition from a probe result.
    ///
    /// # Arguments
    /// * `host_name` - The SSH config host alias
    /// * `probe` - The probe result containing system and agent info
    pub fn generate_source(&self, host_name: &str, probe: &HostProbeResult) -> SourceDefinition {
        let paths = self.generate_paths(probe);
        let path_mappings = self.generate_mappings(probe);
        let platform = self.detect_platform(probe);
        let name = normalize_generated_remote_source_name(host_name);

        SourceDefinition {
            name,
            source_type: SourceKind::Ssh,
            host: Some(host_name.to_string()), // Use SSH alias
            paths,
            sync_schedule: SyncSchedule::Manual,
            path_mappings,
            platform,
        }
    }

    /// Generate paths based on detected agent data.
    ///
    /// Only includes paths where agent data was actually detected,
    /// rather than guessing all possible paths.
    fn generate_paths(&self, probe: &HostProbeResult) -> Vec<String> {
        let mut paths = Vec::new();

        for agent in &probe.detected_agents {
            // Use the detected path directly
            paths.push(agent.path.clone());
        }

        // Deduplicate while preserving order
        let mut seen = HashSet::new();
        paths.retain(|p| seen.insert(p.clone()));

        paths
    }

    /// Generate path mappings for workspace rewriting.
    ///
    /// Creates mappings from remote paths to local equivalents:
    /// - Remote home/projects → Local home/projects
    /// - /data/projects → Local home/projects (common server pattern)
    fn generate_mappings(&self, probe: &HostProbeResult) -> Vec<PathMapping> {
        let mut mappings = Vec::new();

        // Get remote home from system info
        if let Some(ref sys_info) = probe.system_info {
            // Normalize remote_home by trimming trailing slashes to avoid double slashes
            let remote_home = sys_info.remote_home.trim_end_matches('/');

            // Don't create mappings if remote_home is empty or root
            if !remote_home.is_empty() && remote_home != "/" {
                // Map remote home/projects to local home/projects
                let remote_projects = format!("{}/projects", remote_home);
                let local_projects = self.local_home.join("projects");

                mappings.push(PathMapping::new(
                    remote_projects,
                    local_projects.to_string_lossy().to_string(),
                ));

                // Also map remote home directly (more general fallback)
                mappings.push(PathMapping::new(
                    remote_home,
                    self.local_home.to_string_lossy().to_string(),
                ));
            }
        }

        // Check for /data/projects pattern (common on servers)
        let has_data_projects = probe
            .detected_agents
            .iter()
            .any(|a| a.path.starts_with("/data/"));

        if has_data_projects {
            let local_projects = self.local_home.join("projects");
            mappings.push(PathMapping::new(
                "/data/projects",
                local_projects.to_string_lossy().to_string(),
            ));
        }

        mappings
    }

    /// Detect platform from probe results.
    fn detect_platform(&self, probe: &HostProbeResult) -> Option<Platform> {
        probe
            .system_info
            .as_ref()
            .and_then(|si| match si.os.to_lowercase().as_str() {
                "darwin" => Some(Platform::Macos),
                "linux" => Some(Platform::Linux),
                "windows" => Some(Platform::Windows),
                _ => None,
            })
    }

    /// Generate a ConfigPreview from probe results.
    ///
    /// # Arguments
    /// * `probes` - List of (host_name, probe_result) tuples for selected hosts
    /// * `already_configured` - Set of normalized source-name keys already configured
    pub fn generate_preview(
        &self,
        probes: &[(&str, &HostProbeResult)],
        already_configured: &HashSet<String>,
    ) -> ConfigPreview {
        let mut preview = ConfigPreview::new();
        let configured_name_keys: HashSet<_> = already_configured
            .iter()
            .map(|name| source_name_key(name))
            .collect();
        let mut preview_name_keys = configured_name_keys.clone();

        for (host_name, probe) in probes {
            // Skip if probe failed
            if !probe.reachable {
                let reason = probe
                    .error
                    .clone()
                    .unwrap_or_else(|| "unreachable".to_string());
                preview
                    .sources_skipped
                    .push((host_name.to_string(), SkipReason::ProbeFailure(reason)));
                continue;
            }

            // Generate source definition before duplicate checks so we compare
            // using the same canonical naming rules as the saved config.
            let source = self.generate_source(host_name, probe);
            let source_name_key = source_name_key(&source.name);
            if configured_name_keys.contains(&source_name_key) {
                preview
                    .sources_skipped
                    .push((source.name.clone(), SkipReason::AlreadyConfigured));
                continue;
            }
            if let Err(err) = source.validate() {
                preview.sources_skipped.push((
                    host_name.to_string(),
                    SkipReason::InvalidSourceDefinition(err.to_string()),
                ));
                continue;
            }
            if !preview_name_keys.insert(source_name_key) {
                preview.sources_skipped.push((
                    host_name.to_string(),
                    SkipReason::GeneratedNameConflict(source.name.clone()),
                ));
                continue;
            }
            preview.sources_to_add.push(source);
        }

        preview
    }
}

impl Default for SourceConfigGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl SourcesConfig {
    /// Write configuration with backup.
    ///
    /// Creates a uniquely named backup of the existing config (if any)
    /// before writing the new configuration atomically.
    pub fn write_with_backup(&self) -> Result<BackupInfo, ConfigError> {
        let config_path = Self::config_path()?;

        // Create parent directories if needed
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Create backup if file exists
        let backup_path = if config_path.exists() {
            let backup = unique_backup_path(&config_path);
            std::fs::copy(&config_path, &backup)?;
            Some(backup)
        } else {
            None
        };

        // Validate config before writing (round-trip check included below)
        self.validate()?;
        let toml_str = toml::to_string_pretty(self)?;
        let parsed: SourcesConfig = toml::from_str(&toml_str)?;
        parsed.validate()?;

        // Write atomically (temp file + rename)
        let temp_path = unique_atomic_temp_path(&config_path);
        std::fs::write(&temp_path, &toml_str)?;
        sync_file_path(&temp_path)?;
        replace_file_from_temp(&temp_path, &config_path)?;

        Ok(BackupInfo {
            backup_path,
            config_path,
        })
    }

    /// Merge a source into the configuration.
    ///
    /// Returns `MergeResult::Added` if the source was added,
    /// or `MergeResult::AlreadyExists` if a source with the same name exists.
    pub fn merge_source(&mut self, source: SourceDefinition) -> Result<MergeResult, ConfigError> {
        // Validate the source first
        source.validate()?;

        // Check if already exists
        if self
            .sources
            .iter()
            .any(|s| source_names_equal(&s.name, &source.name))
        {
            return Ok(MergeResult::AlreadyExists(source.name));
        }

        let added = source.clone();
        self.sources.push(source);
        Ok(MergeResult::Added(added))
    }

    /// Merge multiple sources from a preview.
    ///
    /// Returns a tuple of (added_count, skipped_names).
    pub fn merge_preview(
        &mut self,
        preview: &ConfigPreview,
    ) -> Result<(usize, Vec<String>), ConfigError> {
        let mut added = 0;
        let mut skipped = Vec::new();

        for source in &preview.sources_to_add {
            match self.merge_source(source.clone())? {
                MergeResult::Added(_) => added += 1,
                MergeResult::AlreadyExists(name) => skipped.push(name),
            }
        }

        Ok((added, skipped))
    }

    /// Get set of configured source names.
    pub fn configured_names(&self) -> HashSet<String> {
        self.sources.iter().map(|s| s.name.clone()).collect()
    }

    /// Get normalized source-name keys for duplicate detection and lookups.
    pub fn configured_name_keys(&self) -> HashSet<String> {
        self.sources
            .iter()
            .map(|s| source_name_key(&s.name))
            .collect()
    }
}

fn replace_file_from_temp(temp_path: &Path, final_path: &Path) -> Result<(), std::io::Error> {
    #[cfg(windows)]
    {
        match std::fs::rename(temp_path, final_path) {
            Ok(()) => sync_parent_directory(final_path),
            Err(first_err)
                if final_path.exists()
                    && matches!(
                        first_err.kind(),
                        std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::PermissionDenied
                    ) =>
            {
                let backup_path = unique_replace_backup_path(final_path);
                std::fs::rename(final_path, &backup_path).map_err(|backup_err| {
                    let _ = std::fs::remove_file(temp_path);
                    std::io::Error::other(format!(
                        "failed preparing backup {} before replacing {}: first error: {}; backup error: {}",
                        backup_path.display(),
                        final_path.display(),
                        first_err,
                        backup_err
                    ))
                })?;
                match std::fs::rename(temp_path, final_path) {
                    Ok(()) => {
                        let _ = std::fs::remove_file(&backup_path);
                        sync_parent_directory(final_path)
                    }
                    Err(second_err) => {
                        let restore_result = std::fs::rename(&backup_path, final_path);
                        match restore_result {
                            Ok(()) => {
                                let _ = std::fs::remove_file(temp_path);
                                sync_parent_directory(final_path).map_err(|sync_err| {
                                    std::io::Error::other(format!(
                                        "failed replacing {} with {}: first error: {}; second error: {}; restored original file but failed syncing parent directory: {}",
                                        final_path.display(),
                                        temp_path.display(),
                                        first_err,
                                        second_err,
                                        sync_err
                                    ))
                                })?;
                                Err(std::io::Error::new(
                                    second_err.kind(),
                                    format!(
                                        "failed replacing {} with {}: first error: {}; second error: {}; restored original file",
                                        final_path.display(),
                                        temp_path.display(),
                                        first_err,
                                        second_err
                                    ),
                                ))
                            }
                            Err(restore_err) => Err(std::io::Error::other(format!(
                                "failed replacing {} with {}: first error: {}; second error: {}; restore error: {}; temp file retained at {}",
                                final_path.display(),
                                temp_path.display(),
                                first_err,
                                second_err,
                                restore_err,
                                temp_path.display()
                            ))),
                        }
                    }
                }
            }
            Err(rename_err) => Err(rename_err),
        }
    }

    #[cfg(not(windows))]
    {
        std::fs::rename(temp_path, final_path)?;
        sync_parent_directory(final_path)
    }
}

fn sync_file_path(path: &Path) -> Result<(), std::io::Error> {
    std::fs::File::open(path)?.sync_all()
}

#[cfg(not(windows))]
fn sync_parent_directory(path: &Path) -> Result<(), std::io::Error> {
    let Some(parent) = path.parent() else {
        return Ok(());
    };
    std::fs::File::open(parent)?.sync_all()
}

#[cfg(windows)]
fn sync_parent_directory(_path: &Path) -> Result<(), std::io::Error> {
    Ok(())
}

fn unique_atomic_temp_path(path: &Path) -> PathBuf {
    unique_atomic_sidecar_path(path, "tmp", "sources.toml")
}

fn unique_backup_path(path: &Path) -> PathBuf {
    static NEXT_NONCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let nonce = NEXT_NONCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("sources.toml");

    path.with_file_name(format!(
        "{file_name}.backup.{}.{}.{}",
        std::process::id(),
        timestamp,
        nonce
    ))
}

#[cfg(windows)]
fn unique_replace_backup_path(path: &Path) -> PathBuf {
    unique_atomic_sidecar_path(path, "bak", "sources.toml")
}

fn unique_atomic_sidecar_path(path: &Path, suffix: &str, fallback_name: &str) -> PathBuf {
    static NEXT_NONCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let nonce = NEXT_NONCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(fallback_name);

    path.with_file_name(format!(
        ".{file_name}.{suffix}.{}.{}.{}",
        std::process::id(),
        timestamp,
        nonce
    ))
}

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

    #[test]
    fn test_empty_config_default() {
        let config = SourcesConfig::default();
        assert!(config.sources.is_empty());
    }

    #[test]
    fn test_replace_file_from_temp_overwrites_existing_file() {
        let temp = tempfile::tempdir().expect("tempdir");
        let final_path = temp.path().join("sources.toml");
        let first_tmp = temp.path().join("first.tmp");
        let second_tmp = temp.path().join("second.tmp");

        std::fs::write(&first_tmp, "first = true\n").expect("write first temp");
        replace_file_from_temp(&first_tmp, &final_path).expect("initial replace");
        assert_eq!(
            std::fs::read_to_string(&final_path).expect("read first final"),
            "first = true\n"
        );

        std::fs::write(&second_tmp, "second = true\n").expect("write second temp");
        replace_file_from_temp(&second_tmp, &final_path).expect("overwrite replace");
        assert_eq!(
            std::fs::read_to_string(&final_path).expect("read second final"),
            "second = true\n"
        );
    }

    #[test]
    fn test_unique_atomic_temp_path_changes_each_call() {
        let final_path = Path::new("/tmp/sources.toml");
        let first = unique_atomic_temp_path(final_path);
        let second = unique_atomic_temp_path(final_path);

        assert_ne!(first, second);
        assert_eq!(first.parent(), final_path.parent());
        assert_eq!(second.parent(), final_path.parent());
    }

    #[test]
    fn test_unique_backup_path_changes_each_call() {
        let final_path = Path::new("/tmp/sources.toml");
        let first = unique_backup_path(final_path);
        let second = unique_backup_path(final_path);

        assert_ne!(first, second);
        assert_eq!(first.parent(), final_path.parent());
        assert_eq!(second.parent(), final_path.parent());
    }

    #[test]
    fn test_config_path_from_parts_prefers_xdg_config_home() {
        let temp = tempfile::tempdir().expect("tempdir");
        let xdg_config_home = temp.path().join("xdg-config");
        let platform_config_dir = temp.path().join("platform-config");
        let home_dir = temp.path().join("home");

        assert_eq!(
            config_path_from_parts(
                Some(xdg_config_home.clone()),
                Some(platform_config_dir),
                Some(home_dir)
            )
            .expect("path from xdg config home"),
            xdg_config_home.join("cass").join("sources.toml")
        );
    }

    #[test]
    fn test_config_path_from_parts_prefers_existing_platform_path_before_dot_config() {
        let temp = tempfile::tempdir().expect("tempdir");
        let platform_config_dir = temp.path().join("platform-config");
        let platform_path = platform_config_dir.join("cass").join("sources.toml");
        let home_dir = temp.path().join("home");
        let dot_config_path = home_dir.join(".config").join("cass").join("sources.toml");
        std::fs::create_dir_all(platform_path.parent().expect("platform parent")).unwrap();
        std::fs::create_dir_all(dot_config_path.parent().expect("dot-config parent")).unwrap();
        std::fs::write(&platform_path, "").unwrap();
        std::fs::write(&dot_config_path, "").unwrap();

        assert_eq!(
            config_path_from_parts(None, Some(platform_config_dir), Some(home_dir))
                .expect("existing platform path"),
            platform_path
        );
    }

    #[test]
    fn test_config_path_from_parts_uses_existing_dot_config_before_new_platform_path() {
        let temp = tempfile::tempdir().expect("tempdir");
        let platform_config_dir = temp.path().join("platform-config");
        let home_dir = temp.path().join("home");
        let dot_config_path = home_dir.join(".config").join("cass").join("sources.toml");
        std::fs::create_dir_all(dot_config_path.parent().expect("dot-config parent")).unwrap();
        std::fs::write(&dot_config_path, "").unwrap();

        assert_eq!(
            config_path_from_parts(None, Some(platform_config_dir), Some(home_dir))
                .expect("existing dot-config path"),
            dot_config_path
        );
    }

    #[test]
    fn test_source_definition_local() {
        let source = SourceDefinition::local("test");
        assert_eq!(source.name, "test");
        assert_eq!(source.source_type, SourceKind::Local);
        assert!(!source.is_remote());
    }

    #[test]
    fn test_source_definition_ssh() {
        let source = SourceDefinition::ssh("laptop", "user@laptop.local");
        assert_eq!(source.name, "laptop");
        assert_eq!(source.source_type, SourceKind::Ssh);
        assert_eq!(source.host, Some("user@laptop.local".into()));
        assert!(source.is_remote());
    }

    #[test]
    fn test_source_validation_empty_name() {
        let source = SourceDefinition::default();
        assert!(source.validate().is_err());

        let source = SourceDefinition::local("   ");
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_rejects_padded_names() {
        let source = SourceDefinition::local(" laptop");
        assert!(source.validate().is_err());

        let source = SourceDefinition::local("laptop ");
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_dot_names() {
        let source = SourceDefinition::local(".");
        assert!(source.validate().is_err());

        let source = SourceDefinition::local("..");
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_reserved_local_name() {
        let source = SourceDefinition::ssh("local", "user@host");
        assert!(source.validate().is_err());

        let source = SourceDefinition::ssh("LOCAL", "user@host");
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_normalize_generated_remote_source_name_disambiguates_local() {
        assert_eq!(normalize_generated_remote_source_name("local"), "local-ssh");
        assert_eq!(normalize_generated_remote_source_name("LOCAL"), "LOCAL-ssh");
        assert_eq!(
            normalize_generated_remote_source_name(" local "),
            "local-ssh"
        );
        assert_eq!(normalize_generated_remote_source_name("laptop"), "laptop");
        assert_eq!(normalize_generated_remote_source_name(" laptop "), "laptop");
    }

    #[test]
    fn test_source_validation_ssh_without_host() {
        let mut source = SourceDefinition::ssh("test", "host");
        source.host = None;
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_ssh_host_hardening() {
        let source = SourceDefinition::ssh("test", "user-name_1@host-name.example");
        assert!(source.validate().is_ok());

        let source = SourceDefinition::ssh("test", "ssh-config-alias");
        assert!(source.validate().is_ok());

        let source = SourceDefinition::ssh("test", "-oProxyCommand=evil");
        assert!(source.validate().is_err());

        let source = SourceDefinition::ssh("test", "user@host withspace");
        assert!(source.validate().is_err());

        for host in [
            " user@host",
            "user@host ",
            "\tuser@host",
            "user@host;touch /tmp/cass-owned",
            "user@host`hostname`",
            "user@host$(hostname)",
            "user@host/../../secret",
            "user@host:2222",
            "üser@host",
            "@host",
            "user@",
            "user@host@extra",
        ] {
            let source = SourceDefinition::ssh("test", host);
            assert!(
                source.validate().is_err(),
                "host should be rejected: {host:?}"
            );
        }
    }

    #[test]
    fn test_source_validation_rejects_invalid_paths() {
        for path in [
            "",
            "   ",
            " ~/.claude/projects",
            "~/.claude/projects ",
            "~/.claude\nprojects",
        ] {
            let mut source = SourceDefinition::ssh("test", "user@host");
            source.paths = vec![path.to_string()];
            assert!(
                source.validate().is_err(),
                "path should be rejected: {path:?}"
            );
        }

        let mut source = SourceDefinition::ssh("test", "user@host");
        source.paths = vec!["~/Library/Application Support/Cursor/User/globalStorage".to_string()];
        assert!(source.validate().is_ok());
    }

    #[test]
    fn test_load_from_preserves_invalid_paths_for_operation_level_reporting() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("sources.toml");
        std::fs::write(
            &config_path,
            r#"
[[sources]]
name = "laptop"
type = "ssh"
host = "user@host"
paths = [" ~/.claude/projects", "~/.codex/sessions"]
"#,
        )
        .expect("write config");

        let loaded = SourcesConfig::load_from(&config_path).expect("lenient load");
        assert_eq!(loaded.sources.len(), 1);
        assert_eq!(loaded.sources[0].paths[0], " ~/.claude/projects");
        assert_eq!(loaded.sources[0].paths[1], "~/.codex/sessions");
        assert!(
            loaded.validate().is_err(),
            "strict validation should still reject writing the malformed path"
        );
    }

    #[test]
    fn test_load_from_still_rejects_invalid_source_structure() {
        let temp = tempfile::tempdir().expect("tempdir");
        let config_path = temp.path().join("sources.toml");
        std::fs::write(
            &config_path,
            r#"
[[sources]]
name = "laptop"
type = "ssh"
host = "user@host withspace"
paths = ["~/.claude/projects"]
"#,
        )
        .expect("write config");

        assert!(
            SourcesConfig::load_from(&config_path).is_err(),
            "lenient load is only for per-path validation, not unsafe host structure"
        );
    }

    #[test]
    fn test_source_validation_path_mapping_empty_from() {
        let mut source = SourceDefinition::local("test");
        source.path_mappings.push(PathMapping::new("", "/Users/me"));
        assert!(source.validate().is_err());

        source.path_mappings.clear();
        source
            .path_mappings
            .push(PathMapping::new("   ", "/Users/me"));
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_path_mapping_empty_to() {
        let mut source = SourceDefinition::local("test");
        source
            .path_mappings
            .push(PathMapping::new("/home/user", ""));
        assert!(source.validate().is_err());

        source.path_mappings.clear();
        source
            .path_mappings
            .push(PathMapping::new("/home/user", "   "));
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_path_mapping_empty_agent_names() {
        let mut source = SourceDefinition::local("test");
        source.path_mappings.push(PathMapping::with_agents(
            "/home/user",
            "/Users/me",
            vec!["claude-code".into(), "   ".into()],
        ));
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_source_validation_path_mapping_empty_agents_list() {
        let mut source = SourceDefinition::local("test");
        source.path_mappings.push(PathMapping::with_agents(
            "/home/user",
            "/Users/me",
            Vec::new(),
        ));
        assert!(source.validate().is_err());
    }

    #[test]
    fn test_path_mapping_new() {
        let mapping = PathMapping::new("/home/user", "/Users/me");
        assert_eq!(mapping.from, "/home/user");
        assert_eq!(mapping.to, "/Users/me");
        assert!(mapping.agents.is_none());
    }

    #[test]
    fn test_path_mapping_with_agents() {
        let mapping = PathMapping::with_agents(
            "/home/user",
            "/Users/me",
            vec!["claude-code".into(), "cursor".into()],
        );
        assert_eq!(mapping.from, "/home/user");
        assert_eq!(mapping.to, "/Users/me");
        assert_eq!(
            mapping.agents,
            Some(vec!["claude-code".into(), "cursor".into()])
        );
    }

    #[test]
    fn test_path_mapping_apply() {
        let mapping = PathMapping::new("/home/user/projects", "/Users/me/projects");

        // Matching prefix
        assert_eq!(
            mapping.apply("/home/user/projects/myapp"),
            Some("/Users/me/projects/myapp".into())
        );

        // Non-matching prefix
        assert_eq!(mapping.apply("/opt/data"), None);

        // Partial match (not at start)
        assert_eq!(mapping.apply("/data/home/user/projects"), None);
    }

    #[test]
    fn test_path_mapping_applies_to_agent() {
        // This test pins the semantics of the *cass wrapper*
        // (`path_mapping_applies_to_agent`) rather than the upstream
        // `PathMapping::applies_to_agent` method. Cass intentionally uses a
        // permissive wrapper: when the caller doesn't specify an agent, even
        // mappings that are scoped to a specific agent still apply. Upstream
        // (`franken_agent_detection`) uses a stricter default (`(Some, None)
        // => false`) because its scan-time usage wants to skip
        // agent-specific mappings when the agent is unknown. Both semantics
        // are correct in their own context; cass's tests must exercise the
        // cass wrapper to avoid coupling to whichever default franken picks.

        // Mapping with no agent filter — applies in every case.
        let global = PathMapping::new("/home", "/Users");
        assert!(path_mapping_applies_to_agent(&global, None));
        assert!(path_mapping_applies_to_agent(&global, Some("claude-code")));
        assert!(path_mapping_applies_to_agent(&global, Some("any-agent")));

        // Mapping with agent filter.
        let filtered = PathMapping::with_agents("/home", "/Users", vec!["claude-code".into()]);
        // No agent specified → cass wrapper matches (permissive default).
        assert!(path_mapping_applies_to_agent(&filtered, None));
        // An explicitly empty allow-list is invalid config and should not match
        // defensively if one is constructed in code.
        let empty_filter = PathMapping::with_agents("/home", "/Users", Vec::new());
        assert!(!path_mapping_applies_to_agent(&empty_filter, None));
        // Agent matches the allow-list.
        assert!(path_mapping_applies_to_agent(
            &filtered,
            Some("claude-code")
        ));
        // Agent not in the allow-list.
        assert!(!path_mapping_applies_to_agent(&filtered, Some("cursor")));
        // Hyphen/underscore normalization: `claude_code` must match the
        // allow-list entry `claude-code` because cass normalizes agent slugs
        // before comparison.
        assert!(path_mapping_applies_to_agent(
            &filtered,
            Some("claude_code")
        ));
        assert!(path_mapping_applies_to_agent(&filtered, Some("claude")));

        let openclaw_filtered =
            PathMapping::with_agents("/home", "/Users", vec!["openclaw".into()]);
        assert!(path_mapping_applies_to_agent(
            &openclaw_filtered,
            Some("open-claw")
        ));
    }

    #[test]
    fn test_path_rewriting() {
        let mut source = SourceDefinition::local("test");
        source.path_mappings.push(PathMapping::new(
            "/home/user/projects",
            "/Users/me/projects",
        ));
        source
            .path_mappings
            .push(PathMapping::new("/home/user", "/Users/me"));

        // Longest prefix should match
        assert_eq!(
            source.rewrite_path("/home/user/projects/myapp"),
            "/Users/me/projects/myapp"
        );

        // Shorter prefix
        assert_eq!(source.rewrite_path("/home/user/other"), "/Users/me/other");

        // No match
        assert_eq!(source.rewrite_path("/opt/data"), "/opt/data");
    }

    #[test]
    fn test_path_rewriting_with_agent_filter() {
        let mut source = SourceDefinition::local("test");
        // Global mapping
        source
            .path_mappings
            .push(PathMapping::new("/home/user", "/Users/me"));
        // Agent-specific mapping
        source.path_mappings.push(PathMapping::with_agents(
            "/home/user/projects",
            "/Volumes/Work/projects",
            vec!["claude-code".into()],
        ));

        // Without agent filter, both mappings apply (longest match wins)
        assert_eq!(
            source.rewrite_path_for_agent("/home/user/projects/app", None),
            "/Volumes/Work/projects/app"
        );

        // With claude-code agent, use specific mapping
        assert_eq!(
            source.rewrite_path_for_agent("/home/user/projects/app", Some("claude-code")),
            "/Volumes/Work/projects/app"
        );
        assert_eq!(
            source.rewrite_path_for_agent("/home/user/projects/app", Some("claude")),
            "/Volumes/Work/projects/app"
        );

        // With cursor agent, falls back to global mapping
        assert_eq!(
            source.rewrite_path_for_agent("/home/user/projects/app", Some("cursor")),
            "/Users/me/projects/app"
        );

        // Non-matching path
        assert_eq!(
            source.rewrite_path_for_agent("/opt/data", Some("claude-code")),
            "/opt/data"
        );
    }

    #[test]
    fn test_config_duplicate_names() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::local("test"));
        config.sources.push(SourceDefinition::local("test"));

        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_duplicate_names_case_insensitive() {
        let mut config = SourcesConfig::default();
        config
            .sources
            .push(SourceDefinition::ssh("Laptop", "user@laptop"));
        config
            .sources
            .push(SourceDefinition::ssh("laptop", "user@other-host"));

        assert!(config.validate().is_err());
    }

    #[test]
    fn test_source_name_keys_trim_and_ignore_case() {
        assert_eq!(source_name_key(" Laptop "), "laptop");
        assert!(source_names_equal(" Laptop ", "laptop"));
    }

    #[test]
    fn test_config_add_source() {
        let mut config = SourcesConfig::default();
        config.add_source(SourceDefinition::local("test")).unwrap();

        assert_eq!(config.sources.len(), 1);

        // Adding duplicate should fail
        assert!(config.add_source(SourceDefinition::local("test")).is_err());
    }

    #[test]
    fn test_config_add_source_case_insensitive_duplicate() {
        let mut config = SourcesConfig::default();
        config
            .add_source(SourceDefinition::ssh("Laptop", "user@laptop"))
            .unwrap();

        assert!(
            config
                .add_source(SourceDefinition::ssh("laptop", "user@other-host"))
                .is_err()
        );
    }

    #[test]
    fn test_config_remove_source() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::local("test"));

        assert!(config.remove_source("test"));
        assert!(!config.remove_source("nonexistent"));
        assert!(config.sources.is_empty());
    }

    #[test]
    fn test_config_remove_source_case_insensitive() {
        let mut config = SourcesConfig::default();
        config
            .sources
            .push(SourceDefinition::ssh("Laptop", "user@laptop"));

        assert!(config.remove_source("laptop"));
        assert!(config.sources.is_empty());
    }

    #[test]
    fn test_find_source_case_insensitive() {
        let mut config = SourcesConfig::default();
        config
            .sources
            .push(SourceDefinition::ssh("Laptop", "user@laptop"));

        assert!(config.find_source("laptop").is_some());
        assert!(config.find_source("LAPTOP").is_some());
        assert!(config.find_source_mut("laptop").is_some());
    }

    #[test]
    fn test_config_serialization_roundtrip() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition {
            name: "laptop".into(),
            source_type: SourceKind::Ssh,
            host: Some("user@laptop.local".into()),
            paths: vec!["~/.claude/projects".into()],
            sync_schedule: SyncSchedule::Daily,
            path_mappings: vec![PathMapping::new("/home/user", "/Users/me")],
            platform: Some(Platform::Linux),
        });

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: SourcesConfig = toml::from_str(&serialized).unwrap();

        assert_eq!(deserialized.sources.len(), 1);
        assert_eq!(deserialized.sources[0].name, "laptop");
        assert_eq!(deserialized.sources[0].sync_schedule, SyncSchedule::Daily);
        assert_eq!(deserialized.sources[0].path_mappings.len(), 1);
        assert_eq!(deserialized.sources[0].path_mappings[0].from, "/home/user");
        assert_eq!(deserialized.sources[0].path_mappings[0].to, "/Users/me");
    }

    #[test]
    fn test_path_mapping_serialization_with_agents() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition {
            name: "remote".into(),
            source_type: SourceKind::Ssh,
            host: Some("user@server".into()),
            paths: vec![],
            sync_schedule: SyncSchedule::Manual,
            path_mappings: vec![
                PathMapping::new("/home/user", "/Users/me"),
                PathMapping::with_agents("/opt/work", "/Volumes/Work", vec!["claude-code".into()]),
            ],
            platform: None,
        });

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: SourcesConfig = toml::from_str(&serialized).unwrap();

        assert_eq!(deserialized.sources[0].path_mappings.len(), 2);
        // First mapping has no agents filter
        assert!(deserialized.sources[0].path_mappings[0].agents.is_none());
        // Second mapping has agents filter
        assert_eq!(
            deserialized.sources[0].path_mappings[1].agents,
            Some(vec!["claude-code".into()])
        );
    }

    #[test]
    fn test_preset_paths() {
        let macos = get_preset_paths("macos-defaults").unwrap();
        assert!(!macos.is_empty());
        assert!(macos.iter().any(|p| p.contains(".claude")));

        let linux = get_preset_paths("linux-defaults").unwrap();
        assert!(!linux.is_empty());

        assert!(get_preset_paths("unknown").is_err());
    }

    #[test]
    fn test_sync_schedule_display() {
        assert_eq!(SyncSchedule::Manual.to_string(), SYNC_SCHEDULE_MANUAL);
        assert_eq!(SyncSchedule::Hourly.to_string(), SYNC_SCHEDULE_HOURLY);
        assert_eq!(SyncSchedule::Daily.to_string(), SYNC_SCHEDULE_DAILY);
    }

    #[test]
    fn test_discover_ssh_hosts() {
        // Just test that the function doesn't panic
        let hosts = super::discover_ssh_hosts();
        // Could be empty if no ~/.ssh/config exists
        for host in hosts {
            assert!(!host.name.is_empty());
        }
    }

    #[test]
    fn test_parse_ssh_config_splits_multiple_host_aliases() {
        let hosts = super::parse_ssh_config(
            r#"
Host alpha beta *.internal ?wild
  HostName 192.0.2.10
  User ubuntu
  Port 2222
  IdentityFile ~/.ssh/id_ed25519

Host gamma
  User deploy
"#,
        );

        assert_eq!(hosts.len(), 3);
        assert_eq!(hosts[0].name, "alpha");
        assert_eq!(hosts[1].name, "beta");
        assert_eq!(hosts[2].name, "gamma");
        for host in &hosts[..2] {
            assert_eq!(host.hostname.as_deref(), Some("192.0.2.10"));
            assert_eq!(host.user.as_deref(), Some("ubuntu"));
            assert_eq!(host.port, Some(2222));
            assert_eq!(host.identity_file.as_deref(), Some("~/.ssh/id_ed25519"));
        }
        assert_eq!(hosts[2].user.as_deref(), Some("deploy"));
    }

    #[test]
    fn test_parse_ssh_config_skips_negated_host_patterns() {
        let hosts = super::parse_ssh_config(
            r#"
Host * !bastion staging
  User ubuntu

Host production !legacy-prod
  User deploy
"#,
        );

        assert_eq!(hosts.len(), 2);
        assert_eq!(hosts[0].name, "staging");
        assert_eq!(hosts[0].user.as_deref(), Some("ubuntu"));
        assert_eq!(hosts[1].name, "production");
        assert_eq!(hosts[1].user.as_deref(), Some("deploy"));
    }

    #[test]
    fn test_parse_ssh_config() {
        let content = "
            Host example
                HostName example.com
                User testuser

            Host=another
                Port=2222
                IdentityFile = ~/.ssh/id_rsa
        ";
        let hosts = parse_ssh_config(content);
        assert_eq!(hosts.len(), 2);
        assert_eq!(hosts[0].name, "example");
        assert_eq!(hosts[0].hostname.as_deref(), Some("example.com"));
        assert_eq!(hosts[0].user.as_deref(), Some("testuser"));

        assert_eq!(hosts[1].name, "another");
        assert_eq!(hosts[1].port, Some(2222));
        assert_eq!(hosts[1].identity_file.as_deref(), Some("~/.ssh/id_rsa"));
    }

    // ==========================================================================
    // Source Config Generator Tests
    // ==========================================================================

    use super::super::probe::{CassStatus, DetectedAgent, HostProbeResult, SystemInfo};

    fn make_test_probe(
        reachable: bool,
        agents: Vec<DetectedAgent>,
        sys_info: Option<SystemInfo>,
    ) -> HostProbeResult {
        HostProbeResult {
            host_name: "test-host".into(),
            reachable,
            connection_time_ms: 100,
            cass_status: CassStatus::NotFound,
            detected_agents: agents,
            system_info: sys_info,
            resources: None,
            error: if reachable {
                None
            } else {
                Some("connection refused".into())
            },
        }
    }

    fn make_test_agent(agent_type: &str, path: &str) -> DetectedAgent {
        DetectedAgent {
            agent_type: agent_type.into(),
            path: path.into(),
            estimated_sessions: Some(100),
            estimated_size_mb: Some(50),
        }
    }

    fn make_test_sys_info(os: &str, remote_home: &str) -> SystemInfo {
        SystemInfo {
            os: os.into(),
            arch: "x86_64".into(),
            distro: Some("Ubuntu 22.04".into()),
            has_cargo: true,
            has_cargo_binstall: true,
            has_curl: true,
            has_wget: true,
            remote_home: remote_home.into(),
            machine_id: None,
        }
    }

    #[test]
    fn test_source_config_generator_new() {
        let generator = SourceConfigGenerator::new();
        assert!(!generator.local_home.as_os_str().is_empty());
    }

    #[test]
    fn test_generate_source_basic() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/ubuntu")),
        );

        let source = generator.generate_source("my-server", &probe);

        assert_eq!(source.name, "my-server");
        assert_eq!(source.source_type, SourceKind::Ssh);
        assert_eq!(source.host, Some("my-server".into()));
        assert_eq!(source.sync_schedule, SyncSchedule::Manual);
        assert!(!source.paths.is_empty());
        assert!(source.paths.contains(&"~/.claude/projects".to_string()));
    }

    #[test]
    fn test_generate_source_disambiguates_reserved_local_name() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/ubuntu")),
        );

        let source = generator.generate_source("local", &probe);

        assert_eq!(source.name, "local-ssh");
        assert_eq!(source.host, Some("local".into()));
    }

    #[test]
    fn test_generate_source_deduplicates_paths() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![
                make_test_agent("claude", "~/.claude/projects"),
                make_test_agent("claude-2", "~/.claude/projects"), // Duplicate
            ],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let source = generator.generate_source("server", &probe);
        assert_eq!(source.paths.len(), 1);
    }

    #[test]
    fn test_generate_source_path_mappings() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/ubuntu")),
        );

        let source = generator.generate_source("server", &probe);
        assert!(!source.path_mappings.is_empty());
        assert!(
            source
                .path_mappings
                .iter()
                .any(|m| m.from.contains("/home/ubuntu"))
        );
    }

    #[test]
    fn test_generate_source_platform_detection() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![],
            Some(make_test_sys_info("linux", "/home/user")),
        );
        let source = generator.generate_source("server", &probe);
        assert_eq!(source.platform, Some(Platform::Linux));
    }

    #[test]
    fn test_generate_preview_basic() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("server1", &probe)];
        let preview = generator.generate_preview(&probes, &HashSet::new());

        assert_eq!(preview.sources_to_add.len(), 1);
        assert!(preview.sources_skipped.is_empty());
        assert!(preview.has_changes());
    }

    #[test]
    fn test_generate_preview_skips_already_configured() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("server1", &probe)];
        let mut configured = HashSet::new();
        configured.insert("server1".to_string());

        let preview = generator.generate_preview(&probes, &configured);
        assert!(preview.sources_to_add.is_empty());
        assert_eq!(preview.sources_skipped.len(), 1);
    }

    #[test]
    fn test_generate_preview_skips_already_configured_case_insensitive() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("Laptop", &probe)];
        let mut configured = HashSet::new();
        configured.insert(source_name_key("laptop"));

        let preview = generator.generate_preview(&probes, &configured);
        assert!(preview.sources_to_add.is_empty());
        assert_eq!(preview.sources_skipped.len(), 1);
    }

    #[test]
    fn test_generate_preview_skips_already_configured_case_insensitively_with_raw_names() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("laptop", &probe)];
        let mut configured = HashSet::new();
        configured.insert("Laptop".to_string());

        let preview = generator.generate_preview(&probes, &configured);

        assert!(preview.sources_to_add.is_empty());
        assert_eq!(preview.sources_skipped.len(), 1);
        assert!(matches!(
            preview.sources_skipped[0].1,
            SkipReason::AlreadyConfigured
        ));
    }

    #[test]
    fn test_generate_preview_preserves_already_configured_skip_for_invalid_probe_data() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "bad\npath")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("server1", &probe)];
        let mut configured = HashSet::new();
        configured.insert("server1".to_string());

        let preview = generator.generate_preview(&probes, &configured);

        assert!(preview.sources_to_add.is_empty());
        assert_eq!(preview.sources_skipped.len(), 1);
        assert_eq!(preview.sources_skipped[0].0, "server1");
        assert!(matches!(
            preview.sources_skipped[0].1,
            SkipReason::AlreadyConfigured
        ));
    }

    #[test]
    fn test_generate_preview_skips_conflicting_generated_names_case_insensitive() {
        let generator = SourceConfigGenerator::new();
        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![("Laptop", &probe), ("laptop", &probe)];
        let preview = generator.generate_preview(&probes, &HashSet::new());

        assert_eq!(preview.sources_to_add.len(), 1);
        assert_eq!(preview.sources_to_add[0].name, "Laptop");
        assert_eq!(preview.sources_skipped.len(), 1);
        assert_eq!(preview.sources_skipped[0].0, "laptop");
        assert!(matches!(
            &preview.sources_skipped[0].1,
            SkipReason::GeneratedNameConflict(name) if name == "laptop"
        ));
    }

    #[test]
    fn test_generate_preview_invalid_source_does_not_shadow_later_valid_duplicate() {
        let generator = SourceConfigGenerator::new();
        let invalid_probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "bad\npath")],
            Some(make_test_sys_info("linux", "/home/user")),
        );
        let valid_probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> =
            vec![("Laptop", &invalid_probe), ("laptop", &valid_probe)];
        let preview = generator.generate_preview(&probes, &HashSet::new());

        assert_eq!(preview.sources_to_add.len(), 1);
        assert_eq!(preview.sources_to_add[0].name, "laptop");
        assert_eq!(preview.sources_skipped.len(), 1);
        assert_eq!(preview.sources_skipped[0].0, "Laptop");
        assert!(matches!(
            &preview.sources_skipped[0].1,
            SkipReason::InvalidSourceDefinition(message)
                if message.contains("paths[0] cannot contain control characters")
        ));
    }

    #[test]
    fn test_generate_preview_skips_invalid_generated_sources_before_merge() {
        let generator = SourceConfigGenerator::new();
        let invalid_host_probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );
        let invalid_path_probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "bad\npath")],
            Some(make_test_sys_info("linux", "/home/user")),
        );
        let valid_probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(make_test_sys_info("linux", "/home/user")),
        );

        let probes: Vec<(&str, &HostProbeResult)> = vec![
            ("bad host", &invalid_host_probe),
            ("path-host", &invalid_path_probe),
            ("server1", &valid_probe),
        ];
        let preview = generator.generate_preview(&probes, &HashSet::new());

        assert_eq!(preview.sources_to_add.len(), 1);
        assert_eq!(preview.sources_to_add[0].name, "server1");
        assert_eq!(preview.sources_skipped.len(), 2);
        assert_eq!(preview.sources_skipped[0].0, "bad host");
        assert!(matches!(
            &preview.sources_skipped[0].1,
            SkipReason::InvalidSourceDefinition(message)
                if message.contains("SSH host cannot contain whitespace")
        ));
        assert_eq!(preview.sources_skipped[1].0, "path-host");
        assert!(matches!(
            &preview.sources_skipped[1].1,
            SkipReason::InvalidSourceDefinition(message)
                if message.contains("paths[0] cannot contain control characters")
        ));

        let mut config = SourcesConfig::default();
        let (added, skipped) = config.merge_preview(&preview).unwrap();
        assert_eq!(added, 1);
        assert!(skipped.is_empty());
        assert_eq!(config.sources.len(), 1);
        assert_eq!(config.sources[0].name, "server1");
    }

    #[test]
    fn test_merge_source() {
        let mut config = SourcesConfig::default();
        let source = SourceDefinition::ssh("new-server", "user@server");

        let result = config.merge_source(source).unwrap();
        assert!(matches!(result, MergeResult::Added(_)));
        assert_eq!(config.sources.len(), 1);
    }

    #[test]
    fn test_merge_source_already_exists() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::ssh("server", "host"));

        let source = SourceDefinition::ssh("server", "other-host");
        let result = config.merge_source(source).unwrap();
        assert!(matches!(result, MergeResult::AlreadyExists(_)));
        assert_eq!(config.sources.len(), 1);
    }

    #[test]
    fn test_merge_source_already_exists_case_insensitive() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::ssh("Server", "host"));

        let source = SourceDefinition::ssh("server", "other-host");
        let result = config.merge_source(source).unwrap();
        assert!(matches!(result, MergeResult::AlreadyExists(_)));
        assert_eq!(config.sources.len(), 1);
    }

    #[test]
    fn test_configured_names() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::ssh("server1", "h1"));
        config.sources.push(SourceDefinition::ssh("server2", "h2"));

        let names = config.configured_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains("server1"));
        assert!(names.contains("server2"));
    }

    #[test]
    fn test_exclude_and_include_agents_normalize_and_dedup() {
        let mut config = SourcesConfig::default();

        assert!(config.exclude_agent_from_indexing(" OpenClaw ").unwrap());
        assert!(!config.exclude_agent_from_indexing("open-claw").unwrap());
        assert!(config.is_agent_disabled("openclaw"));
        assert_eq!(config.configured_disabled_agents(), vec!["openclaw"]);

        assert!(config.include_agent_in_indexing("open_claw").unwrap());
        assert!(!config.is_agent_disabled("openclaw"));
        assert!(config.configured_disabled_agents().is_empty());
    }

    #[test]
    fn test_exclude_agent_aliases_collapse_to_internal_connector_slug() {
        let mut config = SourcesConfig::default();

        assert!(config.exclude_agent_from_indexing("claude-code").unwrap());
        assert!(config.is_agent_disabled("claude"));
        assert!(config.is_agent_disabled("claude_code"));
        assert_eq!(config.configured_disabled_agents(), vec!["claude"]);
    }

    #[test]
    fn test_validate_rejects_empty_disabled_agent_entry() {
        let mut config = SourcesConfig::default();
        config.disabled_agents.push("   ".into());
        let err = config
            .validate()
            .expect_err("disabled_agents entry should fail");
        assert!(matches!(err, ConfigError::Validation(_)));
    }

    #[test]
    fn test_sources_config_roundtrip_preserves_disabled_agents() {
        let mut config = SourcesConfig::default();
        config.exclude_agent_from_indexing("openclaw").unwrap();
        config.exclude_agent_from_indexing("claude-code").unwrap();

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: SourcesConfig = toml::from_str(&serialized).unwrap();

        assert_eq!(
            deserialized.configured_disabled_agents(),
            vec!["claude", "openclaw"]
        );
    }

    #[test]
    fn test_configured_name_keys_normalize_case() {
        let mut config = SourcesConfig::default();
        config.sources.push(SourceDefinition::ssh("Server1", "h1"));
        config.sources.push(SourceDefinition::ssh("server2", "h2"));

        let names = config.configured_name_keys();
        assert_eq!(names.len(), 2);
        assert!(names.contains("server1"));
        assert!(names.contains("server2"));
    }

    #[test]
    fn test_save_to_rejects_invalid_config() {
        let temp = tempfile::tempdir().expect("tempdir");
        let path = temp.path().join("sources.toml");

        let mut config = SourcesConfig::default();
        config
            .sources
            .push(SourceDefinition::ssh("local", "user@host"));

        let err = config
            .save_to(&path)
            .expect_err("save_to should reject invalid config");
        assert!(matches!(err, ConfigError::Validation(_)));
        assert!(!path.exists(), "invalid config should not be written");
    }

    #[test]
    fn test_empty_remote_home_no_mappings() {
        let generator = SourceConfigGenerator::new();
        let mut sys_info = make_test_sys_info("linux", "");
        sys_info.remote_home = "".into();

        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(sys_info),
        );

        let source = generator.generate_source("server", &probe);
        assert!(source.path_mappings.is_empty());
    }

    #[test]
    fn test_trailing_slash_remote_home_normalized() {
        let generator = SourceConfigGenerator::new();
        // Remote home with trailing slash should be normalized
        let mut sys_info = make_test_sys_info("linux", "/home/user/");
        sys_info.remote_home = "/home/user/".into(); // Explicitly set with trailing slash

        let probe = make_test_probe(
            true,
            vec![make_test_agent("claude", "~/.claude/projects")],
            Some(sys_info),
        );

        let source = generator.generate_source("server", &probe);

        // Should have mappings without double slashes
        assert!(!source.path_mappings.is_empty());
        // The projects mapping should NOT have double slashes
        let projects_mapping = source
            .path_mappings
            .iter()
            .find(|m| m.from.contains("projects"));
        assert!(projects_mapping.is_some());
        // Check no double slashes
        assert!(
            !projects_mapping.unwrap().from.contains("//"),
            "Path mapping should not contain double slashes: {}",
            projects_mapping.unwrap().from
        );
    }
}