crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
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
mod manifest;
mod merge;
mod python;
mod signing;
mod walkthrough;

use anyhow::{Context, Result};
use crossterm::style::Stylize;
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::Path;

use crate::db::Database;
use merge::{write_mcp_json_merged, write_root_gitignore, write_settings_json_merged};
pub use python::detect_python_prefix;
use python::{install_cpitd, CpitdResult};
use signing::setup_driver_signing;
use walkthrough::{apply_tui_choices, run_tui_walkthrough, setup_shell_alias};

// Section markers re-exported from merge module (used by tests)

/// The placeholder used in the settings.json template for the Python invocation prefix.
const PYTHON_PREFIX_PLACEHOLDER: &str = "__PYTHON_PREFIX__";

// Embed hook files at compile time from resources/ (packaged with the crate)
const SETTINGS_JSON: &str = include_str!("../../../resources/claude/settings.json");
pub(crate) const PROMPT_GUARD_PY: &str =
    include_str!("../../../resources/claude/hooks/prompt-guard.py");
pub(crate) const POST_EDIT_CHECK_PY: &str =
    include_str!("../../../resources/claude/hooks/post-edit-check.py");
pub(crate) const SESSION_START_PY: &str =
    include_str!("../../../resources/claude/hooks/session-start.py");
pub(crate) const PRE_WEB_CHECK_PY: &str =
    include_str!("../../../resources/claude/hooks/pre-web-check.py");
pub(crate) const WORK_CHECK_PY: &str =
    include_str!("../../../resources/claude/hooks/work-check.py");
pub(crate) const CROSSLINK_CONFIG_PY: &str =
    include_str!("../../../resources/claude/hooks/crosslink_config.py");
pub(crate) const HEARTBEAT_PY: &str = include_str!("../../../resources/claude/hooks/heartbeat.py");

// Embed MCP servers
const SAFE_FETCH_SERVER_PY: &str =
    include_str!("../../../resources/claude/mcp/safe-fetch-server.py");
const KNOWLEDGE_SERVER_PY: &str = include_str!("../../../resources/claude/mcp/knowledge-server.py");
const AGENT_PROMPT_SERVER_PY: &str =
    include_str!("../../../resources/claude/mcp/agent-prompt-server.py");
const MCP_JSON: &str = include_str!("../../../resources/mcp.json");

// Embed slash commands — auto-generated by build.rs from resources/claude/commands/
include!(concat!(env!("OUT_DIR"), "/commands_gen.rs"));

// Hook configuration constant — imported from shared registry module
pub(crate) use crate::commands::config_registry::HOOK_CONFIG_JSON;

// Embed rule files — auto-generated by build.rs from resources/crosslink/rules/
// Generates RULE_* consts and RULE_FILES array for all .md and .txt files.
include!(concat!(env!("OUT_DIR"), "/rules_gen.rs"));

/// The managed gitignore section content.
///
/// This block is placed between `GITIGNORE_SECTION_START` and `GITIGNORE_SECTION_END`
/// markers in the project root `.gitignore`. The markers make `crosslink init --force`
/// idempotent — re-running replaces the section in-place instead of appending duplicates.
use crate::commands::config_registry::{ConfigType, REGISTRY};
use std::collections::HashMap;

/// TUI walkthrough choices for `crosslink init` — registry-driven.
struct TuiChoices {
    values: HashMap<String, serde_json::Value>,
    install_alias: bool,
}

impl Default for TuiChoices {
    fn default() -> Self {
        let mut values = HashMap::new();
        // Default values from the embedded config
        let defaults: serde_json::Value =
            serde_json::from_str(HOOK_CONFIG_JSON).unwrap_or_default();
        for entry in REGISTRY {
            if matches!(
                entry.config_type,
                ConfigType::StringArray | ConfigType::Map | ConfigType::Integer
            ) {
                continue;
            }
            if let Some(v) = defaults.get(entry.key) {
                values.insert(entry.key.to_string(), v.clone());
            }
        }
        Self {
            values,
            install_alias: false,
        }
    }
}

// ── Styled inline output helper ──────────────────────────────────────────────

struct InitUI {
    is_tty: bool,
}

impl InitUI {
    fn new() -> Self {
        Self {
            is_tty: io::stdout().is_terminal(),
        }
    }

    fn banner(&self) {
        if self.is_tty {
            println!();
            println!("  {} {}", "crosslink".bold().cyan(), "init".dark_grey());
            println!("  {}", "".repeat(40).dark_grey());
            println!();
        }
    }

    fn step_start(&self, label: &str) {
        if self.is_tty {
            print!("  {} {}... ", "".cyan(), label);
            io::stdout().flush().ok();
        } else {
            print!("{label}... ");
        }
    }

    fn step_ok(&self, detail: Option<&str>) {
        if self.is_tty {
            match detail {
                Some(d) => println!("{} {}", "".green(), d.dark_grey()),
                None => println!("{}", "".green()),
            }
        } else {
            match detail {
                Some(d) => println!("done ({d})"),
                None => println!("done"),
            }
        }
    }

    fn step_created(&self, what: &str) {
        if self.is_tty {
            println!(
                "  {} {} {}",
                "".green(),
                "created".green(),
                what.dark_grey()
            );
        } else {
            println!("Created {what}");
        }
    }

    fn step_skip(&self, msg: &str) {
        if self.is_tty {
            println!("  {} {}", "".dark_grey(), msg.dark_grey());
        } else {
            println!("{msg}");
        }
    }

    fn warn(&self, msg: &str) {
        if self.is_tty {
            println!("  {} {}", "".yellow(), msg.yellow());
        } else {
            println!("Warning: {msg}");
        }
    }

    fn detail(&self, msg: &str) {
        if self.is_tty {
            println!("    {}", msg.dark_grey());
        } else {
            println!("  {msg}");
        }
    }

    fn success(&self) {
        if self.is_tty {
            println!();
            println!(
                "  {} {}",
                "".green().bold(),
                "Crosslink initialized successfully!".bold()
            );
            println!();
            println!(
                "  {} {} {}",
                "next".dark_grey(),
                "".cyan(),
                "crosslink session start".white()
            );
            println!(
                "       {} {}",
                "".cyan(),
                "crosslink create \"Task\"".white()
            );
            println!();
        } else {
            println!("Crosslink initialized successfully!");
            println!();
            println!("Crosslink tracks issues, comments, and sessions in .crosslink/issues.db.");
            println!("AI agents use it to coordinate work across sessions and worktrees.");
            println!();
            println!("Quick start:");
            println!("  crosslink create \"Task\"     # Create an issue");
            println!("  crosslink list              # See all issues");
            println!("  crosslink session start     # Start a work session");
            println!();
            println!("Multi-agent features (agents, signing, locks, containers) are optional");
            println!("and only needed when multiple AI agents collaborate on the same repo.");
        }
    }
}

/// Options for `crosslink init`.
pub struct InitOpts<'a> {
    pub force: bool,
    pub update: bool,
    pub dry_run: bool,
    pub no_prompt: bool,
    pub python_prefix: Option<&'a str>,
    pub skip_cpitd: bool,
    pub skip_signing: bool,
    pub signing_key: Option<&'a str>,
    pub reconfigure: bool,
    pub defaults: bool,
}

/// Ensure `repo_compact_id` exists in `.crosslink/repo-id`.
///
/// Generates a 4-char base62 identifier on first init and preserves it
/// on subsequent inits. Stored in a separate file (not hook-config.json)
/// to avoid triggering policy drift detection.
fn ensure_repo_compact_id(crosslink_dir: &Path) -> Result<()> {
    let id_path = crosslink_dir.join("repo-id");
    if id_path.exists() {
        return Ok(());
    }
    let id = crate::utils::generate_compact_id();
    fs::write(&id_path, &id).context("Failed to write repo-id")?;
    Ok(())
}

/// Read `repo_compact_id` from `.crosslink/repo-id`, or return a fallback.
pub fn read_repo_compact_id(crosslink_dir: &Path) -> String {
    let id_path = crosslink_dir.join("repo-id");
    if let Ok(id) = fs::read_to_string(&id_path) {
        let trimmed = id.trim();
        if !trimmed.is_empty() {
            return trimmed.to_string();
        }
    }
    // Fallback: generate from directory hash for consistent identity
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    crosslink_dir.hash(&mut hasher);
    crate::utils::base62_encode_4(hasher.finish())
}

/// Lightweight agent identity setup for `crosslink init`.
///
/// Creates the agent config and generates an SSH key, but does NOT
/// publish keys to the hub or configure signing on the cache worktree.
/// Those heavier operations happen lazily on first `crosslink sync` or
/// `crosslink agent init`.
///
/// # Errors
///
/// Returns an error if agent config creation or SSH key generation fails.
fn init_agent_identity(crosslink_dir: &Path, agent_id: &str) -> Result<()> {
    let mut config = crate::identity::AgentConfig::init(crosslink_dir, agent_id, None)?;

    let keys_dir = crosslink_dir.join("keys");
    match crate::signing::generate_agent_key(&keys_dir, agent_id, &config.machine_id) {
        Ok(keypair) => {
            config.ssh_key_path = Some(format!("keys/{agent_id}_ed25519"));
            config.ssh_fingerprint = Some(keypair.fingerprint);
            config.ssh_public_key = Some(keypair.public_key);

            let path = crosslink_dir.join("agent.json");
            let json = serde_json::to_string_pretty(&config)?;
            fs::write(&path, json)?;
        }
        Err(e) => {
            tracing::warn!("Could not generate agent SSH key: {e}");
        }
    }

    Ok(())
}

/// Detect project lint/test commands and populate `agent_overrides` in
/// hook-config.json so kickoff agents can self-validate their work (#495).
///
/// Only populates empty arrays — preserves any manually configured commands.
fn populate_agent_tool_commands(config_path: &Path, project_root: &Path) -> Result<()> {
    if !config_path.exists() {
        return Ok(());
    }

    let raw = fs::read_to_string(config_path)?;
    let mut config: serde_json::Value = serde_json::from_str(&raw)?;

    let Some(serde_json::Value::Object(overrides)) = config.get_mut("agent_overrides") else {
        return Ok(());
    };

    // Only populate if arrays are empty (don't overwrite manual config)
    let lint_empty = overrides
        .get("agent_lint_commands")
        .and_then(|v| v.as_array())
        .is_none_or(Vec::is_empty);
    let test_empty = overrides
        .get("agent_test_commands")
        .and_then(|v| v.as_array())
        .is_none_or(Vec::is_empty);

    if !lint_empty && !test_empty {
        return Ok(()); // Both already configured
    }

    let conv = super::kickoff::detect_conventions(project_root);

    let changed = if lint_empty && !conv.lint_commands.is_empty() {
        overrides.insert(
            "agent_lint_commands".to_string(),
            serde_json::json!(conv.lint_commands),
        );
        true
    } else {
        false
    };

    let changed = if test_empty {
        conv.test_command.as_ref().map_or(changed, |test_cmd| {
            overrides.insert(
                "agent_test_commands".to_string(),
                serde_json::json!([test_cmd]),
            );
            true
        })
    } else {
        changed
    };

    if changed {
        let output = serde_json::to_string_pretty(&config)?;
        fs::write(config_path, format!("{output}\n"))?;
    }

    Ok(())
}

/// Collect all managed files as `(relative_path, template_content)` pairs.
///
/// For `settings.json` the content is the template *after* `__PYTHON_PREFIX__`
/// substitution but *before* the `allowedTools` merge — this ensures user
/// tool additions don't produce false "user-modified" signals in the manifest.
fn managed_files(python_prefix: &str) -> Vec<(String, String)> {
    let mut files: Vec<(String, String)> = vec![
        (
            ".claude/hooks/prompt-guard.py".into(),
            PROMPT_GUARD_PY.into(),
        ),
        (
            ".claude/hooks/post-edit-check.py".into(),
            POST_EDIT_CHECK_PY.into(),
        ),
        (
            ".claude/hooks/session-start.py".into(),
            SESSION_START_PY.into(),
        ),
        (
            ".claude/hooks/pre-web-check.py".into(),
            PRE_WEB_CHECK_PY.into(),
        ),
        (".claude/hooks/work-check.py".into(), WORK_CHECK_PY.into()),
        (
            ".claude/hooks/crosslink_config.py".into(),
            CROSSLINK_CONFIG_PY.into(),
        ),
        (".claude/hooks/heartbeat.py".into(), HEARTBEAT_PY.into()),
        (
            ".claude/mcp/safe-fetch-server.py".into(),
            SAFE_FETCH_SERVER_PY.into(),
        ),
        (
            ".claude/mcp/knowledge-server.py".into(),
            KNOWLEDGE_SERVER_PY.into(),
        ),
        (
            ".claude/mcp/agent-prompt-server.py".into(),
            AGENT_PROMPT_SERVER_PY.into(),
        ),
    ];

    // Command files (auto-discovered by build.rs)
    for (filename, content) in COMMAND_FILES {
        files.push((format!(".claude/commands/{filename}"), content.to_string()));
    }

    // Rule files (auto-discovered by build.rs)
    for (filename, content) in RULE_FILES {
        files.push((format!(".crosslink/rules/{filename}"), content.to_string()));
    }

    // Settings.json — template after prefix substitution, before merge
    let settings_template = SETTINGS_JSON.replace(PYTHON_PREFIX_PLACEHOLDER, python_prefix);
    files.push((".claude/settings.json".into(), settings_template));

    files
}

/// Run the `--update` flow: manifest-tracked safe upgrade of managed files.
fn run_update(path: &Path, opts: &InitOpts<'_>) -> Result<()> {
    use manifest::{
        build_manifest, classify_update, read_manifest, sha256_file, sha256_hex, write_manifest,
        UpdateAction,
    };

    let crosslink_dir = path.join(".crosslink");
    let ui = InitUI::new();

    if !crosslink_dir.exists() || !path.join(".claude").exists() {
        anyhow::bail!(
            "Project not initialized. Run `crosslink init` first, then use `--update` for upgrades."
        );
    }

    // Detect Python prefix (needed for settings.json template)
    let prefix = opts.python_prefix.map_or_else(
        || detect_python_prefix(path),
        std::string::ToString::to_string,
    );

    let template_files = managed_files(&prefix);
    let old_manifest = read_manifest(&crosslink_dir);

    let manifest_missing = old_manifest.is_none();
    if manifest_missing {
        ui.warn(
            "No init-manifest.json found — treating all managed files as potentially modified.",
        );
        ui.detail("This is expected on first upgrade from a pre-manifest crosslink version.");
        ui.detail("Use `crosslink init --force` instead to overwrite all managed files.");
        println!();
    }

    ui.banner();

    // Build a lookup from the old manifest
    let old_files = old_manifest
        .as_ref()
        .map(|m| &m.files)
        .cloned()
        .unwrap_or_default();

    let mut auto_updated: Vec<String> = Vec::new();
    let mut up_to_date: Vec<String> = Vec::new();
    let mut template_unchanged: Vec<String> = Vec::new();
    let mut conflicts: Vec<String> = Vec::new();
    let mut deleted: Vec<String> = Vec::new();
    let mut new_files: Vec<String> = Vec::new();

    // Classify each managed file
    for (rel_path, template_content) in &template_files {
        let abs_path = path.join(rel_path);
        let new_template_hash = sha256_hex(template_content);

        match old_files.get(rel_path) {
            Some(entry) => {
                let current_hash = sha256_file(&abs_path)?;
                let action =
                    classify_update(&entry.sha256, current_hash.as_deref(), &new_template_hash);

                match action {
                    UpdateAction::UpToDate => up_to_date.push(rel_path.clone()),
                    UpdateAction::AutoUpdate => auto_updated.push(rel_path.clone()),
                    UpdateAction::TemplateUnchanged => {
                        template_unchanged.push(rel_path.clone());
                    }
                    UpdateAction::Conflict => conflicts.push(rel_path.clone()),
                    UpdateAction::Deleted => deleted.push(rel_path.clone()),
                    UpdateAction::NewFile => unreachable!(),
                }
            }
            None => {
                // File not in old manifest — it's a newly added template file
                new_files.push(rel_path.clone());
            }
        }
    }

    // ── Report ──────────────────────────────────────────────────────────
    let total_changes = auto_updated.len() + new_files.len();
    let has_issues = !conflicts.is_empty() || !deleted.is_empty();

    if total_changes == 0 && !has_issues {
        ui.step_skip("All managed files are up to date.");
        return Ok(());
    }

    if !auto_updated.is_empty() {
        ui.step_start(&format!(
            "{} file{} to auto-update",
            auto_updated.len(),
            if auto_updated.len() == 1 { "" } else { "s" }
        ));
        println!();
        for f in &auto_updated {
            ui.detail(f);
        }
    }

    if !new_files.is_empty() {
        ui.step_start(&format!(
            "{} new file{} to create",
            new_files.len(),
            if new_files.len() == 1 { "" } else { "s" }
        ));
        println!();
        for f in &new_files {
            ui.detail(f);
        }
    }

    if !conflicts.is_empty() {
        ui.warn(&format!(
            "{} file{} modified by both user and template — {}",
            conflicts.len(),
            if conflicts.len() == 1 { "" } else { "s" },
            if opts.no_prompt {
                "skipping (--no-prompt)"
            } else {
                "will prompt"
            }
        ));
        for f in &conflicts {
            ui.detail(f);
        }
    }

    for f in &deleted {
        ui.detail(&format!(
            "{f} — deleted by user, skipping (will not recreate)"
        ));
    }

    if !template_unchanged.is_empty() || !up_to_date.is_empty() {
        let skip_count = template_unchanged.len() + up_to_date.len();
        ui.step_skip(&format!(
            "{skip_count} file{} already up to date",
            if skip_count == 1 { "" } else { "s" }
        ));
    }

    // ── Dry run: stop here ──────────────────────────────────────────────
    if opts.dry_run {
        println!();
        ui.detail("Dry run — no files were modified.");
        return Ok(());
    }

    // ── Apply changes ───────────────────────────────────────────────────
    let template_map: std::collections::HashMap<&str, &str> = template_files
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();

    // Auto-update files (user never touched them)
    for rel_path in &auto_updated {
        let abs_path = path.join(rel_path);
        let content = template_map[rel_path.as_str()];

        if rel_path == ".claude/settings.json" {
            // settings.json: re-run the merge to preserve user allowedTools
            write_settings_json_merged(&abs_path, &prefix)?;
        } else {
            // Ensure parent directory exists
            if let Some(parent) = abs_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&abs_path, content).with_context(|| format!("Failed to write {rel_path}"))?;
        }
    }

    // Create new files (added in newer template set)
    for rel_path in &new_files {
        let abs_path = path.join(rel_path);
        let content = template_map[rel_path.as_str()];

        if rel_path == ".claude/settings.json" {
            write_settings_json_merged(&abs_path, &prefix)?;
        } else {
            if let Some(parent) = abs_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&abs_path, content).with_context(|| format!("Failed to write {rel_path}"))?;
        }
    }

    // Handle conflicts (prompt or skip)
    let mut conflict_accepted: Vec<String> = Vec::new();
    if !opts.no_prompt {
        let is_tty = io::stdin().is_terminal();
        for rel_path in &conflicts {
            if !is_tty {
                // Non-interactive: skip like --no-prompt
                ui.detail(&format!("Skipping {rel_path} (non-interactive terminal)"));
                continue;
            }

            print!("  Overwrite {rel_path} with new template? (user changes will be lost) [y/N] ");
            io::stdout().flush().ok();

            let mut answer = String::new();
            io::stdin().read_line(&mut answer).ok();

            if answer.trim().eq_ignore_ascii_case("y") {
                let abs_path = path.join(rel_path);
                let content = template_map[rel_path.as_str()];
                if rel_path == ".claude/settings.json" {
                    write_settings_json_merged(&abs_path, &prefix)?;
                } else {
                    fs::write(&abs_path, content)
                        .with_context(|| format!("Failed to write {rel_path}"))?;
                }
                conflict_accepted.push(rel_path.clone());
            } else {
                ui.detail(&format!("Keeping user version of {rel_path}"));
            }
        }
    }

    // ── Write updated manifest ──────────────────────────────────────────
    // Build new manifest. For files we wrote, use the new template hash.
    // For files we skipped (user-modified, deleted), keep the old manifest entry
    // so future updates can still detect changes correctly.
    let new_full_manifest = build_manifest(&template_files);
    let mut final_manifest = new_full_manifest;

    // For files where the user kept their version (conflict not accepted),
    // preserve the old manifest hash so the conflict surfaces again next time.
    for rel_path in &conflicts {
        if !conflict_accepted.contains(rel_path) {
            if let Some(old_entry) = old_files.get(rel_path) {
                final_manifest
                    .files
                    .insert(rel_path.clone(), old_entry.clone());
            }
        }
    }

    // For deleted files, remove from manifest entirely
    for rel_path in &deleted {
        final_manifest.files.remove(rel_path);
    }

    // For template-unchanged user-modified files, preserve old manifest entry
    for rel_path in &template_unchanged {
        if let Some(old_entry) = old_files.get(rel_path) {
            final_manifest
                .files
                .insert(rel_path.clone(), old_entry.clone());
        }
    }

    write_manifest(&crosslink_dir, &final_manifest)?;

    // ── Summary ─────────────────────────────────────────────────────────
    let total_written = auto_updated.len() + new_files.len() + conflict_accepted.len();
    if total_written > 0 {
        ui.step_ok(Some(&format!(
            "{total_written} file{} updated",
            if total_written == 1 { "" } else { "s" }
        )));
    }

    Ok(())
}

pub fn run(path: &Path, opts: &InitOpts<'_>) -> Result<()> {
    // Dispatch to update flow if --update is set
    if opts.update {
        return run_update(path, opts);
    }

    let force = opts.force;
    let python_prefix = opts.python_prefix;
    let skip_cpitd = opts.skip_cpitd;
    let skip_signing = opts.skip_signing;
    let signing_key = opts.signing_key;
    let reconfigure = opts.reconfigure;
    let defaults = opts.defaults;
    let crosslink_dir = path.join(".crosslink");
    let claude_dir = path.join(".claude");
    let hooks_dir = claude_dir.join("hooks");

    let ui = InitUI::new();

    // Pre-flight: verify git repo exists and has at least one commit (#401).
    // Crosslink uses git worktrees for hub/knowledge branches, which require
    // a functioning repo with commit history.
    let git_dir = path.join(".git");
    if !git_dir.exists() {
        anyhow::bail!(
            "No git repository found at {}.\n\
             Run `git init` and create an initial commit before running `crosslink init`.",
            path.display()
        );
    }
    let has_commits = std::process::Command::new("git")
        .current_dir(path)
        .args(["rev-parse", "HEAD"])
        .output()
        .is_ok_and(|o| o.status.success());
    if !has_commits {
        anyhow::bail!(
            "Git repository has no commits.\n\
             Create an initial commit before running `crosslink init`:\n\
             \n  git add .\n  git commit -m \"Initial commit\""
        );
    }

    // Check if already initialized
    let crosslink_exists = crosslink_dir.exists();
    let claude_exists = claude_dir.exists();

    if crosslink_exists && claude_exists && !force && !reconfigure {
        ui.step_skip("Already initialized");
        ui.detail("Use --force to update hooks to latest version.");
        ui.detail("Use --reconfigure to re-run the setup walkthrough.");
        return Ok(());
    }

    // ── TUI walkthrough FIRST — before any filesystem changes ────────────
    // If the user presses Esc, we bail before creating anything.
    let config_path = crosslink_dir.join("hook-config.json");
    let config_exists = config_path.exists();
    let should_run_tui = !defaults && (!config_exists || force || reconfigure);

    let tui_result = if should_run_tui {
        let base_config: serde_json::Value = if config_exists && reconfigure {
            let raw = fs::read_to_string(&config_path)
                .context("Failed to read existing hook-config.json")?;
            serde_json::from_str(&raw).context("hook-config.json contains invalid JSON")?
        } else {
            serde_json::from_str(HOOK_CONFIG_JSON)
                .context("Embedded hook-config.json is invalid")?
        };

        let existing_ref = if config_exists {
            Some(&base_config as &serde_json::Value)
        } else {
            None
        };
        let choices = run_tui_walkthrough(existing_ref)?;
        Some((base_config, choices))
    } else {
        None
    };

    // ── All filesystem changes happen below this point ───────────────────

    // Dry-run guard: preview what --force would write, then exit without
    // touching the filesystem (mirrors the --update --dry-run behaviour).
    if opts.dry_run {
        let ui = InitUI::new();
        ui.banner();

        let prefix = python_prefix.map_or_else(
            || detect_python_prefix(path),
            std::string::ToString::to_string,
        );
        let files = managed_files(&prefix);

        let mut would_write: Vec<&str> = Vec::new();
        let mut would_create: Vec<&str> = Vec::new();
        for (rel_path, _) in &files {
            if path.join(rel_path).exists() {
                would_write.push(rel_path);
            } else {
                would_create.push(rel_path);
            }
        }

        // Always includes non-managed files written by init
        let extra = [".mcp.json", ".crosslink/hook-config.json", ".gitignore"];
        for f in &extra {
            if path.join(f).exists() {
                would_write.push(f);
            } else {
                would_create.push(f);
            }
        }

        if !would_write.is_empty() {
            ui.step_start(&format!(
                "{} file{} to overwrite",
                would_write.len(),
                if would_write.len() == 1 { "" } else { "s" }
            ));
            println!();
            for f in &would_write {
                ui.detail(f);
            }
        }
        if !would_create.is_empty() {
            ui.step_start(&format!(
                "{} new file{} to create",
                would_create.len(),
                if would_create.len() == 1 { "" } else { "s" }
            ));
            println!();
            for f in &would_create {
                ui.detail(f);
            }
        }

        println!();
        ui.detail("Dry run — no files were modified.");
        return Ok(());
    }

    ui.banner();

    let rules_dir = crosslink_dir.join("rules");

    // Create .crosslink directory and database
    if !crosslink_exists {
        ui.step_start("Initializing database");
        fs::create_dir_all(&crosslink_dir).context("Failed to create .crosslink directory")?;
        let db_path = crosslink_dir.join("issues.db");
        Database::open(&db_path)?;
        ui.step_ok(None);
    }

    // Write hook config
    let tui_choices = match tui_result {
        Some((mut config, choices)) => {
            apply_tui_choices(&mut config, &choices)?;
            let output = serde_json::to_string_pretty(&config)
                .context("Failed to serialize hook-config.json")?;
            fs::write(&config_path, format!("{output}\n"))
                .context("Failed to write hook-config.json")?;
            ui.step_created("hook-config.json");
            Some(choices)
        }
        None if !config_exists || force => {
            fs::write(&config_path, HOOK_CONFIG_JSON)
                .context("Failed to write hook-config.json")?;
            ui.step_created("hook-config.json");
            None
        }
        None => None,
    };

    // Ensure repo_compact_id exists in hook-config.json (idempotent)
    ensure_repo_compact_id(&crosslink_dir)?;

    // Auto-detect lint/test commands for agent overrides (#495)
    populate_agent_tool_commands(&config_path, path)?;

    // Write .crosslink/.gitignore for multi-agent files
    let crosslink_gitignore = crosslink_dir.join(".gitignore");
    if !crosslink_gitignore.exists() || force {
        fs::write(
            &crosslink_gitignore,
            "# Multi-agent collaboration (machine-local)\n\
             agent.json\n\
             repo-id\n\
             .hub-cache/\n\
             .knowledge-cache/\n\
             keys/\n\
             integrations/\n\
             \n\
             # Machine-local overrides\n\
             hook-config.local.json\n\
             rules.local/\n",
        )
        .context("Failed to write .crosslink/.gitignore")?;
    }

    // Write/update managed section in root .gitignore
    ui.step_start("Configuring .gitignore");
    write_root_gitignore(path).context("Failed to update root .gitignore")?;
    ui.step_ok(None);

    // Create or update rules directory
    let rules_exist = rules_dir.exists();
    if !rules_exist || force {
        ui.step_start("Deploying rules");
        fs::create_dir_all(&rules_dir).context("Failed to create .crosslink/rules directory")?;

        for (filename, content) in RULE_FILES {
            fs::write(rules_dir.join(filename), content)
                .with_context(|| format!("Failed to write {filename}"))?;
        }

        if force && rules_exist {
            ui.step_ok(Some("updated"));
        } else {
            ui.step_ok(Some(&format!("{} files", RULE_FILES.len())));
        }
    }

    // Create rules.local directory for machine-local rule overrides
    let rules_local_dir = crosslink_dir.join("rules.local");
    if !rules_local_dir.exists() {
        fs::create_dir_all(&rules_local_dir)
            .context("Failed to create .crosslink/rules.local directory")?;
    }

    // Detect or use provided Python prefix (needed for settings.json and cpitd install)
    let prefix = python_prefix.map_or_else(
        || detect_python_prefix(path),
        std::string::ToString::to_string,
    );

    // Create .claude directory and hooks (or update if force)
    if !claude_exists || force {
        ui.step_start("Setting up Claude Code hooks");
        fs::create_dir_all(&hooks_dir).context("Failed to create .claude/hooks directory")?;

        write_settings_json_merged(&claude_dir.join("settings.json"), &prefix)
            .context("Failed to write settings.json")?;

        fs::write(hooks_dir.join("prompt-guard.py"), PROMPT_GUARD_PY)
            .context("Failed to write prompt-guard.py")?;
        fs::write(hooks_dir.join("post-edit-check.py"), POST_EDIT_CHECK_PY)
            .context("Failed to write post-edit-check.py")?;
        fs::write(hooks_dir.join("session-start.py"), SESSION_START_PY)
            .context("Failed to write session-start.py")?;
        fs::write(hooks_dir.join("pre-web-check.py"), PRE_WEB_CHECK_PY)
            .context("Failed to write pre-web-check.py")?;
        fs::write(hooks_dir.join("work-check.py"), WORK_CHECK_PY)
            .context("Failed to write work-check.py")?;
        fs::write(hooks_dir.join("crosslink_config.py"), CROSSLINK_CONFIG_PY)
            .context("Failed to write crosslink_config.py")?;
        fs::write(hooks_dir.join("heartbeat.py"), HEARTBEAT_PY)
            .context("Failed to write heartbeat.py")?;

        let mcp_dir = claude_dir.join("mcp");
        fs::create_dir_all(&mcp_dir).context("Failed to create .claude/mcp directory")?;
        fs::write(mcp_dir.join("safe-fetch-server.py"), SAFE_FETCH_SERVER_PY)
            .context("Failed to write safe-fetch-server.py")?;
        fs::write(mcp_dir.join("knowledge-server.py"), KNOWLEDGE_SERVER_PY)
            .context("Failed to write knowledge-server.py")?;
        fs::write(
            mcp_dir.join("agent-prompt-server.py"),
            AGENT_PROMPT_SERVER_PY,
        )
        .context("Failed to write agent-prompt-server.py")?;

        let commands_dir = claude_dir.join("commands");
        fs::create_dir_all(&commands_dir).context("Failed to create .claude/commands directory")?;
        for (filename, content) in COMMAND_FILES {
            fs::write(commands_dir.join(filename), content)
                .with_context(|| format!("Failed to write {filename}"))?;
        }

        let warnings =
            write_mcp_json_merged(&path.join(".mcp.json")).context("Failed to write .mcp.json")?;
        for warning in &warnings {
            ui.warn(warning);
        }

        if force && claude_exists {
            ui.step_ok(Some("updated"));
        } else {
            ui.step_ok(None);
        }
    }

    // Write init manifest after all managed file writes succeed.
    // This enables future `--update` runs to perform three-way merges.
    {
        let manifest_files = managed_files(&prefix);
        let m = manifest::build_manifest(&manifest_files);
        manifest::write_manifest(&crosslink_dir, &m)
            .context("Failed to write init-manifest.json")?;
    }

    // Auto-install cpitd unless skipped
    if !skip_cpitd {
        ui.step_start("Checking cpitd");
        match install_cpitd(&prefix) {
            Ok(CpitdResult::InstalledFromPypi) => ui.step_ok(Some("installed")),
            Ok(CpitdResult::InstalledFromSource) => ui.step_ok(Some("installed from source")),
            Ok(CpitdResult::AlreadyInstalled) => ui.step_ok(Some("already installed")),
            Err(e) => {
                // Finish the step_start line, then show warning below
                println!();
                ui.warn(&format!("Could not auto-install cpitd: {e}"));
                ui.detail("You can install it manually: pip install cpitd");
            }
        }
    }

    // Driver SSH key detection and setup
    if !skip_signing {
        setup_driver_signing(path, signing_key, &ui)?;
    }

    // Auto-initialise agent identity so hub-cache commits are always
    // signing-aware. Creates agent ID + SSH key only — hub publishing and
    // signing configuration happen lazily on first sync. Errors are
    // non-fatal; the agent can still work unsigned.
    if crate::identity::AgentConfig::load(&crosslink_dir)?.is_none() {
        let agent_id = crate::utils::generate_compact_id();
        ui.step_start("Initializing agent identity");
        match init_agent_identity(&crosslink_dir, &agent_id) {
            Ok(()) => ui.step_ok(Some(&agent_id)),
            Err(e) => {
                println!();
                ui.warn(&format!("Could not auto-initialize agent: {e}"));
                ui.detail("Run `crosslink agent init <id>` manually to enable signing.");
            }
        }
    }

    // Shell alias setup (REQ-10)
    if let Some(ref choices) = tui_choices {
        setup_shell_alias(&ui, choices);
    }

    ui.success();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use merge::{GITIGNORE_SECTION_END, GITIGNORE_SECTION_START};
    use tempfile::tempdir;

    /// Create a temp directory with a git repo and initial commit.
    /// Required because init now checks for .git and HEAD (#401).
    fn test_dir() -> tempfile::TempDir {
        let dir = tempdir().unwrap();
        let init = std::process::Command::new("git")
            .current_dir(dir.path())
            .args(["init"])
            .output()
            .expect("git init failed");
        assert!(init.status.success(), "git init failed");
        // Use -c flags so identity works even when env vars or global config are absent
        let commit = std::process::Command::new("git")
            .current_dir(dir.path())
            .args([
                "-c",
                "user.name=test",
                "-c",
                "user.email=test@test",
                "commit",
                "--allow-empty",
                "-m",
                "init",
            ])
            .output()
            .expect("git commit failed");
        assert!(commit.status.success(), "git commit --allow-empty failed");
        dir
    }

    /// Build default test opts (skips cpitd/signing, uses --defaults to skip TUI).
    fn test_opts(force: bool) -> InitOpts<'static> {
        InitOpts {
            force,
            update: false,
            dry_run: false,
            no_prompt: false,
            python_prefix: None,
            skip_cpitd: true,
            skip_signing: true,
            signing_key: None,
            reconfigure: false,
            defaults: true,
        }
    }

    #[test]
    fn test_run_fresh_init() {
        let dir = test_dir();
        let result = run(dir.path(), &test_opts(false));
        assert!(result.is_ok());

        // Verify directories created
        assert!(dir.path().join(".crosslink").exists());
        assert!(dir.path().join(".crosslink/rules").exists());
        assert!(dir.path().join(".crosslink/issues.db").exists());
        assert!(dir.path().join(".claude").exists());
        assert!(dir.path().join(".claude/hooks").exists());
        assert!(dir.path().join(".claude/mcp").exists());
        assert!(dir.path().join(".crosslink/hook-config.json").exists());
    }

    #[test]
    fn test_run_creates_hook_files() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Verify hook files
        assert!(dir.path().join(".claude/settings.json").exists());
        assert!(dir.path().join(".claude/hooks/prompt-guard.py").exists());
        assert!(dir.path().join(".claude/hooks/post-edit-check.py").exists());
        assert!(dir.path().join(".claude/hooks/session-start.py").exists());
        assert!(dir.path().join(".claude/hooks/pre-web-check.py").exists());
        assert!(dir.path().join(".claude/hooks/work-check.py").exists());
        assert!(dir
            .path()
            .join(".claude/hooks/crosslink_config.py")
            .exists());
        assert!(dir.path().join(".claude/mcp/safe-fetch-server.py").exists());
        assert!(dir.path().join(".claude/mcp/knowledge-server.py").exists());
        assert!(dir
            .path()
            .join(".claude/mcp/agent-prompt-server.py")
            .exists());
        assert!(dir.path().join(".mcp.json").exists());
    }

    #[test]
    fn test_run_creates_rule_files() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let rules_dir = dir.path().join(".crosslink/rules");
        assert!(rules_dir.join("global.md").exists());
        assert!(rules_dir.join("project.md").exists());
        assert!(rules_dir.join("rust.md").exists());
        assert!(rules_dir.join("python.md").exists());
        assert!(rules_dir.join("javascript.md").exists());
        assert!(rules_dir.join("typescript.md").exists());
        assert!(rules_dir.join("tracking-strict.md").exists());
        assert!(rules_dir.join("tracking-normal.md").exists());
        assert!(rules_dir.join("tracking-relaxed.md").exists());
    }

    #[test]
    fn test_run_already_initialized_no_force() {
        let dir = test_dir();

        // First init
        run(dir.path(), &test_opts(false)).unwrap();

        // Second init without force - should succeed but not recreate
        let result = run(dir.path(), &test_opts(false));
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_force_update() {
        let dir = test_dir();

        // First init
        run(dir.path(), &test_opts(false)).unwrap();

        // Modify a hook file
        let hook_path = dir.path().join(".claude/hooks/prompt-guard.py");
        fs::write(&hook_path, "# modified").unwrap();

        // Force update
        run(dir.path(), &test_opts(true)).unwrap();

        // Verify file was restored
        let content = fs::read_to_string(&hook_path).unwrap();
        assert_ne!(content, "# modified");
        assert!(content.contains("python") || content.contains("def") || content.len() > 20);
    }

    /// Keys that the embedded `MCP_JSON` is expected to manage.
    fn embedded_mcp_keys() -> Vec<String> {
        let embedded: serde_json::Value = serde_json::from_str(MCP_JSON).unwrap();
        embedded["mcpServers"]
            .as_object()
            .unwrap()
            .keys()
            .cloned()
            .collect()
    }

    #[test]
    fn test_force_init_preserves_existing_mcp_servers() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Add a custom MCP server entry alongside the embedded ones
        let mcp_path = dir.path().join(".mcp.json");
        let mut content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&mcp_path).unwrap()).unwrap();
        content["mcpServers"]["my-custom-server"] = serde_json::json!({
            "command": "node",
            "args": ["my-server.js"]
        });
        fs::write(&mcp_path, serde_json::to_string_pretty(&content).unwrap()).unwrap();

        // Force update
        run(dir.path(), &test_opts(true)).unwrap();

        // Verify all embedded keys and the custom key are present
        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&mcp_path).unwrap()).unwrap();
        let servers = result["mcpServers"].as_object().unwrap();

        for key in embedded_mcp_keys() {
            assert!(
                servers.contains_key(&key),
                "embedded key \"{key}\" should exist"
            );
        }
        assert!(
            servers.contains_key("my-custom-server"),
            "custom server should be preserved"
        );
        assert_eq!(
            servers["my-custom-server"]["command"].as_str().unwrap(),
            "node"
        );
    }

    #[test]
    fn test_force_init_returns_warnings_for_overwritten_keys() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // The first init created .mcp.json with the embedded keys.
        // A second force init should warn about overwriting each one.
        let mcp_path = dir.path().join(".mcp.json");
        let warnings = write_mcp_json_merged(&mcp_path).unwrap();

        let expected_keys = embedded_mcp_keys();
        assert_eq!(
            warnings.len(),
            expected_keys.len(),
            "should warn once per embedded key"
        );
        for key in &expected_keys {
            assert!(
                warnings.iter().any(|w| w.contains(key)),
                "should warn about overwriting \"{key}\""
            );
        }
    }

    #[test]
    fn test_write_mcp_json_merged_creates_fresh_file() {
        let dir = test_dir();
        let mcp_path = dir.path().join(".mcp.json");

        // No pre-existing file
        assert!(!mcp_path.exists());

        let warnings = write_mcp_json_merged(&mcp_path).unwrap();
        assert!(
            warnings.is_empty(),
            "fresh creation should produce no warnings"
        );

        let content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&mcp_path).unwrap()).unwrap();
        let servers = content["mcpServers"].as_object().unwrap();

        // Should contain exactly the embedded keys
        let expected_keys = embedded_mcp_keys();
        assert_eq!(servers.len(), expected_keys.len());
        for key in &expected_keys {
            assert!(
                servers.contains_key(key),
                "fresh file should contain \"{key}\""
            );
        }
    }

    #[test]
    fn test_force_init_fails_on_malformed_mcp_json() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write invalid JSON to .mcp.json
        let mcp_path = dir.path().join(".mcp.json");
        fs::write(&mcp_path, "not json {{{").unwrap();

        // Force init should fail, not silently overwrite
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("invalid JSON"),
            "Error should mention invalid JSON, got: {err}"
        );

        // Original (broken) content should be untouched
        let content = fs::read_to_string(&mcp_path).unwrap();
        assert_eq!(content, "not json {{{");
    }

    #[test]
    fn test_force_init_fails_on_non_object_mcp_json() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write a JSON array to .mcp.json
        let mcp_path = dir.path().join(".mcp.json");
        fs::write(&mcp_path, "[1, 2, 3]").unwrap();

        // Force init should fail, not silently overwrite
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("not a JSON object"),
            "Error should mention not a JSON object, got: {err}"
        );

        // Original content should be untouched
        let content = fs::read_to_string(&mcp_path).unwrap();
        assert_eq!(content, "[1, 2, 3]");
    }

    #[test]
    fn test_force_init_handles_empty_mcp_json_file() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write empty file
        let mcp_path = dir.path().join(".mcp.json");
        fs::write(&mcp_path, "").unwrap();

        // Should fail — empty file is not valid JSON
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("invalid JSON"),
            "Error should mention invalid JSON, got: {err}"
        );
    }

    #[test]
    fn test_force_init_fails_on_non_object_mcp_servers_value() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write valid JSON where mcpServers is a string instead of object
        let mcp_path = dir.path().join(".mcp.json");
        fs::write(&mcp_path, r#"{"mcpServers": "banana"}"#).unwrap();

        // Should fail, not silently replace
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("non-object mcpServers"),
            "Error should mention non-object mcpServers, got: {err}"
        );

        // Original content should be untouched
        let content = fs::read_to_string(&mcp_path).unwrap();
        assert_eq!(content, r#"{"mcpServers": "banana"}"#);
    }

    #[test]
    fn test_init_merges_into_mcp_json_without_mcp_servers_key() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write a valid object with no mcpServers key
        let mcp_path = dir.path().join(".mcp.json");
        fs::write(&mcp_path, r#"{"someOtherKey": true}"#).unwrap();

        // Force init should add mcpServers, preserving the other key
        run(dir.path(), &test_opts(true)).unwrap();

        let content = fs::read_to_string(&mcp_path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["someOtherKey"], true);
        assert!(parsed["mcpServers"]["crosslink-safe-fetch"].is_object());
        assert!(parsed["mcpServers"]["crosslink-knowledge"].is_object());
    }

    #[test]
    fn test_run_partial_init_crosslink_only() {
        let dir = test_dir();

        // Create only .crosslink directory
        fs::create_dir_all(dir.path().join(".crosslink")).unwrap();

        let result = run(dir.path(), &test_opts(false));
        assert!(result.is_ok());

        // .claude should now exist
        assert!(dir.path().join(".claude").exists());
    }

    #[test]
    fn test_run_partial_init_claude_only() {
        let dir = test_dir();

        // Create only .claude directory
        fs::create_dir_all(dir.path().join(".claude")).unwrap();

        let result = run(dir.path(), &test_opts(false));
        assert!(result.is_ok());

        // .crosslink should now exist
        assert!(dir.path().join(".crosslink").exists());
    }

    #[test]
    fn test_run_database_usable() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Open the created database and verify it works
        let db_path = dir.path().join(".crosslink/issues.db");
        let db = Database::open(&db_path).unwrap();

        // Should be able to create an issue
        let id = db.create_issue("Test issue", None, "medium").unwrap();
        assert!(id > 0);
    }

    #[test]
    fn test_run_rule_files_not_empty() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let rules_dir = dir.path().join(".crosslink/rules");

        // Verify rule files have content
        let global = fs::read_to_string(rules_dir.join("global.md")).unwrap();
        assert!(!global.is_empty());

        let rust = fs::read_to_string(rules_dir.join("rust.md")).unwrap();
        assert!(!rust.is_empty());
    }

    #[test]
    fn test_run_force_updates_rules() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Modify a rule file
        let rule_path = dir.path().join(".crosslink/rules/global.md");
        fs::write(&rule_path, "# modified rule").unwrap();

        // Force update
        run(dir.path(), &test_opts(true)).unwrap();

        // Verify file was restored
        let content = fs::read_to_string(&rule_path).unwrap();
        assert_ne!(content, "# modified rule");
    }

    #[test]
    fn test_run_idempotent_with_force() {
        let dir = test_dir();

        // Multiple force runs should all succeed
        for _ in 0..3 {
            let result = run(dir.path(), &test_opts(true));
            assert!(result.is_ok());
        }

        // All files should still exist
        assert!(dir.path().join(".crosslink/issues.db").exists());
        assert!(dir.path().join(".claude/settings.json").exists());
    }

    #[test]
    #[allow(clippy::const_is_empty)]
    fn test_embedded_constants_not_empty() {
        // Verify all embedded constants have content
        assert!(!SETTINGS_JSON.is_empty());
        assert!(!PROMPT_GUARD_PY.is_empty());
        assert!(!POST_EDIT_CHECK_PY.is_empty());
        assert!(!SESSION_START_PY.is_empty());
        assert!(!PRE_WEB_CHECK_PY.is_empty());
        assert!(!WORK_CHECK_PY.is_empty());
        assert!(!CROSSLINK_CONFIG_PY.is_empty());
        assert!(!HEARTBEAT_PY.is_empty());
        assert!(!SAFE_FETCH_SERVER_PY.is_empty());
        assert!(!KNOWLEDGE_SERVER_PY.is_empty());
        assert!(!AGENT_PROMPT_SERVER_PY.is_empty());
        assert!(!MCP_JSON.is_empty());
        // All auto-discovered command files should be non-empty
        assert!(
            COMMAND_FILES.len() >= 11,
            "Expected at least 11 command files, found {}",
            COMMAND_FILES.len()
        );
        for (filename, content) in COMMAND_FILES {
            assert!(!content.is_empty(), "Command file {filename} is empty");
        }
        assert!(!RULE_SANITIZE_PATTERNS.is_empty());
        assert!(!HOOK_CONFIG_JSON.is_empty());
        assert!(!RULE_TRACKING_STRICT.is_empty());
        assert!(!RULE_TRACKING_NORMAL.is_empty());
        assert!(!RULE_TRACKING_RELAXED.is_empty());
        assert!(!RULE_GLOBAL.is_empty());
        assert!(!RULE_RUST.is_empty());
    }

    #[test]
    fn test_rule_files_count() {
        // Verify we have the expected number of rule files
        assert!(RULE_FILES.len() >= 20);

        // All should have content
        for (name, content) in RULE_FILES {
            assert!(!name.is_empty(), "Rule file name should not be empty");
            assert!(!content.is_empty(), "Rule file {name} should not be empty");
        }
    }

    #[test]
    fn test_gitignore_includes_local_config() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".crosslink/.gitignore")).unwrap();
        assert!(content.contains("agent.json"));
        assert!(content.contains(".hub-cache/"));
        assert!(content.contains("hook-config.local.json"));
    }

    // --- Python toolchain detection tests ---

    #[test]
    fn test_detect_python_prefix_default() {
        let dir = test_dir();
        assert_eq!(detect_python_prefix(dir.path()), "python3");
    }

    #[test]
    fn test_detect_python_prefix_uv_lock() {
        let dir = test_dir();
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "uv run python3");
    }

    #[test]
    fn test_detect_python_prefix_uv_pyproject() {
        let dir = test_dir();
        fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"foo\"\n\n[tool.uv]\ndev-dependencies = []\n",
        )
        .unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "uv run python3");
    }

    #[test]
    fn test_detect_python_prefix_poetry_lock() {
        let dir = test_dir();
        fs::write(dir.path().join("poetry.lock"), "").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "poetry run python3");
    }

    #[test]
    fn test_detect_python_prefix_poetry_pyproject() {
        let dir = test_dir();
        fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"foo\"\n\n[tool.poetry]\nname = \"foo\"\n",
        )
        .unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "poetry run python3");
    }

    #[test]
    fn test_detect_python_prefix_venv() {
        let dir = test_dir();
        fs::create_dir(dir.path().join(".venv")).unwrap();
        assert_eq!(detect_python_prefix(dir.path()), ".venv/bin/python3");
    }

    #[test]
    fn test_detect_python_prefix_pipenv() {
        let dir = test_dir();
        fs::write(dir.path().join("Pipfile"), "").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "pipenv run python3");
    }

    #[test]
    fn test_detect_python_prefix_pipenv_lock() {
        let dir = test_dir();
        fs::write(dir.path().join("Pipfile.lock"), "{}").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "pipenv run python3");
    }

    #[test]
    fn test_detect_python_prefix_uv_beats_poetry() {
        let dir = test_dir();
        // Both uv.lock and poetry.lock present — uv wins
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        fs::write(dir.path().join("poetry.lock"), "").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "uv run python3");
    }

    #[test]
    fn test_detect_python_prefix_poetry_beats_venv() {
        let dir = test_dir();
        fs::write(dir.path().join("poetry.lock"), "").unwrap();
        fs::create_dir(dir.path().join(".venv")).unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "poetry run python3");
    }

    #[test]
    fn test_detect_python_prefix_venv_beats_pipenv() {
        let dir = test_dir();
        fs::create_dir(dir.path().join(".venv")).unwrap();
        fs::write(dir.path().join("Pipfile"), "").unwrap();
        assert_eq!(detect_python_prefix(dir.path()), ".venv/bin/python3");
    }

    #[test]
    fn test_detect_python_prefix_pyproject_without_tools_is_default() {
        let dir = test_dir();
        // Plain pyproject.toml with no tool sections
        fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"foo\"\nversion = \"1.0\"\n",
        )
        .unwrap();
        assert_eq!(detect_python_prefix(dir.path()), "python3");
    }

    // --- Settings.json templating tests ---

    #[test]
    fn test_settings_json_default_uses_python3() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        assert!(
            content.contains("python3"),
            "Default init should use python3 in settings.json"
        );
        assert!(
            !content.contains(PYTHON_PREFIX_PLACEHOLDER),
            "Placeholder should be replaced"
        );
    }

    #[test]
    fn test_settings_json_uv_project() {
        let dir = test_dir();
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        assert!(
            content.contains("uv run python3"),
            "uv project should use 'uv run python3' in settings.json"
        );
    }

    #[test]
    fn test_settings_json_cli_override() {
        let dir = test_dir();
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        // CLI override should beat auto-detection
        run(
            dir.path(),
            &InitOpts {
                python_prefix: Some("custom-python"),
                ..test_opts(false)
            },
        )
        .unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        assert!(
            content.contains("custom-python"),
            "CLI override should be used in settings.json"
        );
        assert!(
            !content.contains("uv run python3"),
            "Auto-detected prefix should not appear when overridden"
        );
    }

    #[test]
    fn test_settings_json_produces_valid_json() {
        let dir = test_dir();
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&content);
        assert!(
            parsed.is_ok(),
            "Settings JSON should be valid after templating"
        );
    }

    #[test]
    fn test_force_re_detects_toolchain() {
        let dir = test_dir();
        // First init: no markers → python3
        run(dir.path(), &test_opts(false)).unwrap();
        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        assert!(content.contains("python3 \\\"$HOOK\\\""));

        // Add uv.lock, force re-init → should now use uv
        fs::write(dir.path().join("uv.lock"), "").unwrap();
        run(dir.path(), &test_opts(true)).unwrap();
        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        assert!(
            content.contains("uv run python3"),
            "Force re-init should re-detect toolchain"
        );
    }

    // --- Settings.json allowedTools merge tests ---

    /// The default allowedTools entries that the embedded template provides.
    fn embedded_allowed_tools() -> Vec<String> {
        let template: serde_json::Value = serde_json::from_str(SETTINGS_JSON).unwrap();
        template
            .get("allowedTools")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn test_settings_json_includes_allowed_tools() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let tools = parsed["allowedTools"]
            .as_array()
            .expect("allowedTools should be an array");

        for expected in embedded_allowed_tools() {
            assert!(
                tools.iter().any(|v| v.as_str() == Some(&expected)),
                "allowedTools should contain \"{expected}\""
            );
        }
    }

    #[test]
    fn test_settings_json_includes_tmux_and_worktree_permissions() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let tools: Vec<&str> = parsed["allowedTools"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();

        assert!(
            tools.contains(&"Bash(tmux *)"),
            "allowedTools should include tmux permission"
        );
        assert!(
            tools.contains(&"Bash(git worktree *)"),
            "allowedTools should include git worktree permission"
        );
    }

    #[test]
    fn test_force_init_preserves_user_allowed_tools() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Add a custom allowedTools entry
        let settings_path = dir.path().join(".claude/settings.json");
        let mut content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        content["allowedTools"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::Value::String("Bash(my-custom-tool *)".into()));
        fs::write(
            &settings_path,
            serde_json::to_string_pretty(&content).unwrap(),
        )
        .unwrap();

        // Force re-init
        run(dir.path(), &test_opts(true)).unwrap();

        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        let tools: Vec<&str> = result["allowedTools"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();

        // Should have embedded tools AND the custom one
        for expected in embedded_allowed_tools() {
            assert!(
                tools.contains(&expected.as_str()),
                "embedded tool \"{expected}\" should be preserved after force re-init"
            );
        }
        assert!(
            tools.contains(&"Bash(my-custom-tool *)"),
            "custom allowedTools entry should be preserved after force re-init"
        );
    }

    #[test]
    fn test_force_init_no_duplicate_allowed_tools() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Force re-init multiple times
        run(dir.path(), &test_opts(true)).unwrap();
        run(dir.path(), &test_opts(true)).unwrap();

        let settings_path = dir.path().join(".claude/settings.json");
        let content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        let tools: Vec<&str> = content["allowedTools"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();

        // Each embedded tool should appear exactly once (no duplicates)
        for expected in embedded_allowed_tools() {
            let count = tools.iter().filter(|&&t| t == expected.as_str()).count();
            assert_eq!(
                count, 1,
                "\"{expected}\" should appear exactly once, found {count}"
            );
        }
    }

    #[test]
    fn test_settings_json_merge_fails_on_malformed_json() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write invalid JSON to settings.json
        let settings_path = dir.path().join(".claude/settings.json");
        fs::write(&settings_path, "not json {{{").unwrap();

        // Force init should fail, not silently overwrite
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("invalid JSON"),
            "Error should mention invalid JSON, got: {err}"
        );

        // Original (broken) content should be untouched
        let content = fs::read_to_string(&settings_path).unwrap();
        assert_eq!(content, "not json {{{");
    }

    #[test]
    fn test_settings_json_merge_fails_on_non_object() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Write a JSON array to settings.json
        let settings_path = dir.path().join(".claude/settings.json");
        fs::write(&settings_path, "[1, 2, 3]").unwrap();

        // Force init should fail, not silently overwrite
        let result = run(dir.path(), &test_opts(true));
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("not a JSON object"),
            "Error should mention not a JSON object, got: {err}"
        );
    }

    #[test]
    fn test_settings_json_merge_creates_fresh_file() {
        let dir = test_dir();
        let settings_path = dir.path().join(".claude/settings.json");
        fs::create_dir_all(dir.path().join(".claude")).unwrap();

        // No pre-existing file
        assert!(!settings_path.exists());

        write_settings_json_merged(&settings_path, "python3").unwrap();

        let content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        let tools: Vec<&str> = content["allowedTools"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();

        for expected in embedded_allowed_tools() {
            assert!(
                tools.contains(&expected.as_str()),
                "fresh file should contain \"{expected}\""
            );
        }
    }

    // --- Root .gitignore tests ---

    #[test]
    fn test_init_creates_root_gitignore() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(content.contains(GITIGNORE_SECTION_START));
        assert!(content.contains(GITIGNORE_SECTION_END));
        assert!(content.contains(".crosslink/issues.db"));
        assert!(content.contains(".crosslink/agent.json"));
        assert!(content.contains(".crosslink/session.json"));
        assert!(content.contains(".crosslink/daemon.pid"));
        assert!(content.contains(".crosslink/keys/"));
        assert!(content.contains(".crosslink/.hub-cache/"));
        assert!(content.contains(".crosslink/hook-config.local.json"));
        assert!(content.contains(".claude/hooks/"));
        assert!(content.contains(".claude/commands/"));
        assert!(content.contains(".claude/mcp/"));
    }

    #[test]
    fn test_root_gitignore_idempotent() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let first = fs::read_to_string(dir.path().join(".gitignore")).unwrap();

        // Force re-init should produce identical content
        run(dir.path(), &test_opts(true)).unwrap();
        let second = fs::read_to_string(dir.path().join(".gitignore")).unwrap();

        assert_eq!(
            first, second,
            "Re-init should not duplicate gitignore entries"
        );
    }

    #[test]
    fn test_root_gitignore_preserves_user_entries() {
        let dir = test_dir();

        // Write a pre-existing .gitignore with user content
        fs::write(dir.path().join(".gitignore"), "/target/\n*.log\n").unwrap();

        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(
            content.contains("/target/"),
            "User entries before managed section should be preserved"
        );
        assert!(
            content.contains("*.log"),
            "User entries before managed section should be preserved"
        );
        assert!(content.contains(GITIGNORE_SECTION_START));
        assert!(content.contains(".crosslink/issues.db"));
    }

    #[test]
    fn test_root_gitignore_preserves_entries_around_managed_section() {
        let dir = test_dir();

        // First init
        run(dir.path(), &test_opts(false)).unwrap();

        // Add user content before and after the managed section
        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        let new_content =
            format!("# My custom rules\n/build/\n\n{content}\n# Trailing rules\n*.tmp\n");
        fs::write(dir.path().join(".gitignore"), new_content).unwrap();

        // Force re-init
        run(dir.path(), &test_opts(true)).unwrap();

        let result = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(
            result.contains("/build/"),
            "Pre-section user entries preserved"
        );
        assert!(
            result.contains("*.tmp"),
            "Post-section user entries preserved"
        );
        assert!(
            result.contains(".crosslink/issues.db"),
            "Managed entries present"
        );

        // Should have exactly one managed section
        assert_eq!(
            result.matches(GITIGNORE_SECTION_START).count(),
            1,
            "Should have exactly one managed section start marker"
        );
        assert_eq!(
            result.matches(GITIGNORE_SECTION_END).count(),
            1,
            "Should have exactly one managed section end marker"
        );
    }

    #[test]
    fn test_root_gitignore_has_do_track_comments() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(
            content.contains("DO track"),
            "Should include DO track comments for documentation"
        );
        assert!(
            content.contains("hook-config.json"),
            "Should mention hook-config.json as tracked"
        );
    }

    #[test]
    fn test_write_root_gitignore_fresh() {
        let dir = test_dir();
        write_root_gitignore(dir.path()).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(content.starts_with(GITIGNORE_SECTION_START));
        assert!(content.contains(GITIGNORE_SECTION_END));
        assert!(content.contains(".crosslink/issues.db"));
    }

    #[test]
    fn test_write_root_gitignore_replaces_section() {
        let dir = test_dir();

        // Write twice
        write_root_gitignore(dir.path()).unwrap();
        write_root_gitignore(dir.path()).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert_eq!(
            content.matches(GITIGNORE_SECTION_START).count(),
            1,
            "Should have exactly one start marker after double write"
        );
    }

    #[test]
    fn test_crosslink_inner_gitignore_includes_integrations() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".crosslink/.gitignore")).unwrap();
        assert!(content.contains("integrations/"));
    }

    // --- Tier 1/2 smoke tests (GH issue #242) ---

    #[test]
    fn test_init_deploys_skill_files() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let commands_dir = dir.path().join(".claude/commands");
        assert!(
            commands_dir.join("maintain.md").exists(),
            "maintain.md skill not deployed"
        );
        assert!(
            commands_dir.join("design.md").exists(),
            "design.md skill not deployed"
        );

        // Verify non-empty content
        let maintain = fs::read_to_string(commands_dir.join("maintain.md")).unwrap();
        assert!(!maintain.is_empty(), "maintain.md is empty");
        let design = fs::read_to_string(commands_dir.join("design.md")).unwrap();
        assert!(!design.is_empty(), "design.md is empty");
    }

    #[test]
    fn test_init_deploys_mcp_servers() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // All three server scripts must be deployed. Previously only
        // safe-fetch and knowledge were checked, which masked #554 — init
        // registered crosslink-agent-prompt in .mcp.json but never wrote
        // the script to disk, so every Claude Code session logged a
        // server-launch failure.
        let mcp_dir = dir.path().join(".claude/mcp");
        assert!(
            mcp_dir.join("safe-fetch-server.py").exists(),
            "safe-fetch-server.py not deployed"
        );
        assert!(
            mcp_dir.join("knowledge-server.py").exists(),
            "knowledge-server.py not deployed"
        );
        assert!(
            mcp_dir.join("agent-prompt-server.py").exists(),
            "agent-prompt-server.py not deployed"
        );

        // .mcp.json must reference all three MCP servers. If a server is
        // registered here without the matching script being deployed,
        // Claude Code will fail to launch it on startup (#554).
        let mcp_content = fs::read_to_string(dir.path().join(".mcp.json")).unwrap();
        let mcp: serde_json::Value = serde_json::from_str(&mcp_content).unwrap();
        let servers = mcp["mcpServers"].as_object().unwrap();
        assert!(
            servers.contains_key("crosslink-safe-fetch"),
            ".mcp.json missing crosslink-safe-fetch"
        );
        assert!(
            servers.contains_key("crosslink-knowledge"),
            ".mcp.json missing crosslink-knowledge"
        );
        assert!(
            servers.contains_key("crosslink-agent-prompt"),
            ".mcp.json missing crosslink-agent-prompt"
        );
    }

    #[test]
    fn test_force_init_deploys_skill_files() {
        let dir = test_dir();
        // First init
        run(dir.path(), &test_opts(false)).unwrap();

        // Delete skill files to simulate upgrade scenario
        let commands_dir = dir.path().join(".claude/commands");
        fs::remove_file(commands_dir.join("maintain.md")).unwrap();
        fs::remove_file(commands_dir.join("design.md")).unwrap();
        assert!(!commands_dir.join("maintain.md").exists());
        assert!(!commands_dir.join("design.md").exists());

        // Force init should re-deploy them
        run(dir.path(), &test_opts(true)).unwrap();
        assert!(commands_dir.join("maintain.md").exists());
        assert!(commands_dir.join("design.md").exists());
    }

    // --- Init manifest and --update tests ---

    fn update_opts() -> InitOpts<'static> {
        InitOpts {
            force: false,
            update: true,
            dry_run: false,
            no_prompt: true, // Tests are non-interactive
            python_prefix: None,
            skip_cpitd: true,
            skip_signing: true,
            signing_key: None,
            reconfigure: false,
            defaults: true,
        }
    }

    fn dry_run_opts() -> InitOpts<'static> {
        InitOpts {
            dry_run: true,
            ..update_opts()
        }
    }

    #[test]
    fn test_init_writes_manifest() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let manifest_path = dir.path().join(".crosslink/init-manifest.json");
        assert!(manifest_path.exists(), "Manifest should be created on init");

        let content = fs::read_to_string(&manifest_path).unwrap();
        let manifest: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(manifest.get("crosslink_version").is_some());
        assert!(manifest.get("initialized_at").is_some());
        assert!(manifest.get("files").is_some());

        let files = manifest["files"].as_object().unwrap();
        assert!(
            files.contains_key(".claude/hooks/prompt-guard.py"),
            "Manifest should track hook files"
        );
        assert!(
            files.contains_key(".claude/settings.json"),
            "Manifest should track settings.json"
        );
        assert!(
            files.contains_key(".claude/mcp/safe-fetch-server.py"),
            "Manifest should track MCP servers"
        );
        assert!(
            files.contains_key(".claude/mcp/knowledge-server.py"),
            "Manifest should track knowledge MCP server"
        );
        assert!(
            files.contains_key(".claude/mcp/agent-prompt-server.py"),
            "Manifest should track agent-prompt MCP server"
        );
    }

    #[test]
    fn test_force_init_updates_manifest() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let manifest_path = dir.path().join(".crosslink/init-manifest.json");
        let first = fs::read_to_string(&manifest_path).unwrap();

        // Force re-init
        run(dir.path(), &test_opts(true)).unwrap();

        let second = fs::read_to_string(&manifest_path).unwrap();
        // Hashes should be the same (same templates), but timestamp may differ
        let m1: serde_json::Value = serde_json::from_str(&first).unwrap();
        let m2: serde_json::Value = serde_json::from_str(&second).unwrap();
        assert_eq!(
            m1["files"], m2["files"],
            "File hashes should be identical across force re-inits"
        );
    }

    #[test]
    fn test_update_no_changes_needed() {
        let dir = test_dir();
        // Fresh init creates manifest
        run(dir.path(), &test_opts(false)).unwrap();

        // Immediately update — nothing should change
        let result = run(dir.path(), &update_opts());
        assert!(result.is_ok());

        // Verify hook file wasn't modified (content same as template)
        let content = fs::read_to_string(dir.path().join(".claude/hooks/prompt-guard.py")).unwrap();
        assert!(content.contains("python") || content.contains("def") || content.len() > 20);
    }

    #[test]
    fn test_update_fails_without_init() {
        let dir = test_dir();
        // No init — update should fail
        let result = run(dir.path(), &update_opts());
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(
            err.contains("not initialized"),
            "Should mention not initialized, got: {err}"
        );
    }

    #[test]
    fn test_update_preserves_user_modified_hook() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // User modifies a hook file
        let hook_path = dir.path().join(".claude/hooks/prompt-guard.py");
        fs::write(&hook_path, "# user customization\nprint('hello')").unwrap();

        // Update with --no-prompt — user-modified file should be kept
        run(dir.path(), &update_opts()).unwrap();

        let content = fs::read_to_string(&hook_path).unwrap();
        assert_eq!(
            content, "# user customization\nprint('hello')",
            "User-modified hook should not be overwritten"
        );
    }

    #[test]
    fn test_update_skips_deleted_files() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // User deletes a hook file
        let hook_path = dir.path().join(".claude/hooks/heartbeat.py");
        fs::remove_file(&hook_path).unwrap();

        // Update should NOT recreate deleted files
        run(dir.path(), &update_opts()).unwrap();

        assert!(
            !hook_path.exists(),
            "Deleted file should not be recreated by --update"
        );
    }

    #[test]
    fn test_update_dry_run_makes_no_changes() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Modify a hook file
        let hook_path = dir.path().join(".claude/hooks/prompt-guard.py");
        let original = fs::read_to_string(&hook_path).unwrap();
        fs::write(&hook_path, "# modified").unwrap();

        // Read manifest before dry run
        let manifest_before =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();

        // Dry run
        run(dir.path(), &dry_run_opts()).unwrap();

        // File should still be modified
        let content = fs::read_to_string(&hook_path).unwrap();
        assert_eq!(content, "# modified", "Dry run should not modify files");

        // Manifest should be unchanged
        let manifest_after =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();
        assert_eq!(
            manifest_before, manifest_after,
            "Dry run should not update manifest"
        );

        // Restore for other tests
        fs::write(&hook_path, original).unwrap();
    }

    #[test]
    fn test_force_dry_run_makes_no_changes() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Modify a hook file so we can detect overwrites
        let hook_path = dir.path().join(".claude/hooks/prompt-guard.py");
        fs::write(&hook_path, "# user-modified").unwrap();

        // Snapshot manifest
        let manifest_before =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();

        // Force + dry-run
        let dry_force = InitOpts {
            force: true,
            dry_run: true,
            ..test_opts(true)
        };
        run(dir.path(), &dry_force).unwrap();

        // File should still have the user modification
        let content = fs::read_to_string(&hook_path).unwrap();
        assert_eq!(
            content, "# user-modified",
            "Force dry-run should not overwrite files"
        );

        // Manifest should be unchanged
        let manifest_after =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();
        assert_eq!(
            manifest_before, manifest_after,
            "Force dry-run should not update manifest"
        );
    }

    #[test]
    fn test_update_preserves_user_allowed_tools() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Add a custom allowedTools entry
        let settings_path = dir.path().join(".claude/settings.json");
        let mut content: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        content["allowedTools"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::Value::String("Bash(my-tool *)".into()));
        fs::write(
            &settings_path,
            serde_json::to_string_pretty(&content).unwrap(),
        )
        .unwrap();

        // Run update
        run(dir.path(), &update_opts()).unwrap();

        // Custom tool should still be present
        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        let has_custom_tool = result["allowedTools"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .any(|t| t == "Bash(my-tool *)");
        assert!(
            has_custom_tool,
            "Custom allowedTools entry should survive --update"
        );
    }

    #[test]
    fn test_update_without_manifest_warns() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        // Remove manifest to simulate old install
        fs::remove_file(dir.path().join(".crosslink/init-manifest.json")).unwrap();

        // Update should still work (treats everything as potentially modified)
        let result = run(dir.path(), &update_opts());
        assert!(result.is_ok());
    }

    #[test]
    fn test_gitignore_includes_manifest() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let content = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(
            content.contains("init-manifest.json"),
            "Gitignore should include init-manifest.json"
        );
    }

    #[test]
    fn test_manifest_tracks_all_managed_files() {
        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let manifest_content =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();
        let manifest: serde_json::Value = serde_json::from_str(&manifest_content).unwrap();
        let files = manifest["files"].as_object().unwrap();

        // Should track all hook files
        let hook_files = [
            "prompt-guard.py",
            "post-edit-check.py",
            "session-start.py",
            "pre-web-check.py",
            "work-check.py",
            "crosslink_config.py",
            "heartbeat.py",
        ];
        for hook in &hook_files {
            let key = format!(".claude/hooks/{hook}");
            assert!(files.contains_key(&key), "Manifest should track {key}");
        }

        // Should track MCP servers
        assert!(files.contains_key(".claude/mcp/safe-fetch-server.py"));
        assert!(files.contains_key(".claude/mcp/knowledge-server.py"));
        assert!(files.contains_key(".claude/mcp/agent-prompt-server.py"));

        // Should track settings.json
        assert!(files.contains_key(".claude/settings.json"));

        // Should track rule files
        assert!(files.contains_key(".crosslink/rules/global.md"));
        assert!(files.contains_key(".crosslink/rules/rust.md"));
    }

    #[test]
    fn test_manifest_hashes_match_file_content() {
        use manifest::sha256_hex;

        let dir = test_dir();
        run(dir.path(), &test_opts(false)).unwrap();

        let manifest_content =
            fs::read_to_string(dir.path().join(".crosslink/init-manifest.json")).unwrap();
        let manifest: manifest::InitManifest = serde_json::from_str(&manifest_content).unwrap();

        // Hook files should have hash matching on-disk content
        let hook_path = dir.path().join(".claude/hooks/prompt-guard.py");
        let on_disk = fs::read_to_string(&hook_path).unwrap();
        let expected_hash = sha256_hex(&on_disk);

        assert_eq!(
            manifest.files[".claude/hooks/prompt-guard.py"].sha256, expected_hash,
            "Manifest hash should match on-disk file for non-merged files"
        );
    }
}