mind-cli 0.28.0

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

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use crate::catalog::CatalogItem;
use crate::error::BadRefReason::NoMatch;
use crate::error::{ItemKind, MindError, Result};
use crate::manifest::InstalledItem;
use crate::namespace;
use crate::paths::{Paths, mkdir_p};

/// Install (or upgrade in place) one catalog item, returning its manifest record.
///
/// `commit` is the source's current commit; `siblings` is every catalog item in
/// the same source (including `item` itself), used to validate `{{ns:}}` name
/// tokens and to resolve the `{{self}}` / `{{tools:}}` / `{{path:}}` path tokens
/// to store paths. The recorded hash is of the *source* content so drift
/// detection compares like with like. `dangerously_skip_build` runs a build hook
/// non-interactively without prompting (HOOK-74); without it a non-TTY context
/// skips the build hook (HOOK-72).
pub fn install(
    paths: &Paths,
    item: &CatalogItem,
    commit: &str,
    siblings: &[CatalogItem],
    force: bool,
    dangerously_skip_build: bool,
) -> Result<InstalledItem> {
    let kind = item.kind;
    let name = item.effective_name();

    // Defense-in-depth: verify the effective name is safe before using it to
    // build any filesystem paths (NS-28 / UnsafeName). The prefix validator
    // (`validate_prefix`) and catalog name check (`is_safe_item_name`) already
    // guard the inputs individually, but this belt-and-suspenders check ensures
    // that even an unexpected combination cannot yield a traversal name.
    {
        use std::path::Component;
        let effective_safe = !name.is_empty()
            && !name.contains('\0')
            && std::path::Path::new(&name).components().all(|c| {
                !matches!(
                    c,
                    Component::RootDir | Component::ParentDir | Component::Prefix(..)
                )
            });
        if !effective_safe {
            return Err(MindError::UnsafeName { name: name.clone() });
        }
    }

    let store = paths.store_item(kind, &name);
    let staging = paths.staging_path(kind, &name);
    let backup = paths.backup_path(kind, &name);

    // 0. Resolve where this item will link, and refuse up front to overwrite any
    //    target that is not mind's own symlink (a user's file/dir/foreign link).
    //    This runs before staging, so a clobber aborts touching nothing. With
    //    `force`, the guard is skipped and step 3 overwrites the conflicting
    //    target (LIFE-41).
    // A tool with no explicit `link` is store-only: no link target, so no agent
    // home symlink (the harness does not discover it; items reach it by token).
    //
    // spec: NS-40 -- an agent's default link uses the bare harness name (the
    // frontmatter `name:` field, which is what the Claude harness resolves), NOT
    // the effective (possibly prefixed) name. The store path and manifest `name`
    // still use the effective name. An explicit `link_rel` from mind.toml wins.
    let link_name = if kind == ItemKind::Agent {
        item.agent_harness_name()
            .unwrap_or_else(|| item.name.clone())
    } else {
        name.clone()
    };
    let link_rel = item
        .link_rel
        .clone()
        .or_else(|| paths.default_link_rel(kind, &link_name));
    let store_root = paths.store_dir();
    // Only link into lobes whose `kinds` admit this item's kind (HARN-2/HARN-3)
    // and whose parent directory exists (STO-56: the reachability gate). A lobe
    // that excludes the kind or whose parent is absent contributes no link and is
    // not an error, so the recorded manifest `links` reflect exactly the lobes
    // that were active at install time. A skipped unreachable lobe prints a
    // one-time note (HARN-16) naming both remedies, deduplicated per process so a
    // multi-item `learn`/`meld` does not repeat it for every item.
    // spec: STO-56
    // spec: HARN-16
    let planned_links: Vec<std::path::PathBuf> = match &link_rel {
        Some(rel) => {
            let mut planned = Vec::new();
            for home in paths.agent_homes()?.iter().filter(|home| home.admits(kind)) {
                if home.reachable() {
                    planned.push(home.path.join(rel));
                } else {
                    note_unreachable_lobe_once(&home.path);
                }
            }
            planned
        }
        None => Vec::new(),
    };
    if !force {
        for link in &planned_links {
            ensure_unoccupied(&store_root, link)?;
        }
    }

    // 1. Stage and validate the new copy. Live install is untouched until step 2.
    remove_path(&staging)?;
    if let Some(parent) = staging.parent() {
        mkdir_p(parent)?;
    }
    // spec: IGN-10 -- the copy and the hash below take the SAME ignore set, so
    // the store holds exactly what the recorded hash measures. Computed once
    // and shared rather than derived twice, so the two cannot fall out of step.
    let ignore = item.ignore_set()?;
    copy_recursive_ignoring(&item.path, &staging, &ignore)?;
    // Record the source hash now, while the tree just copied is still what is
    // on disk and any failure still aborts before the step-2 swap. Hashing it
    // after step 4 (as the InstalledItem literal used to) left a window where a
    // source read error surfaced with the backup already dropped: the new copy
    // swapped in and linked but never recorded in the manifest.
    let hash = crate::hash::hash_path_ignoring(&item.path, &ignore)?;
    if let Err(e) = expand_references(&staging, item, siblings, &store_root) {
        let _ = remove_path(&staging);
        return Err(e);
    }

    // 1b. Per-item build hook: build the item's tooling inside staging, before
    //     the swap, so a failed build is rolled back with staging and never
    //     touches the live install (HOOK-70..74). It is arbitrary code, so it is
    //     disclosed and prompted on a TTY; a non-TTY context skips it (the item
    //     installs unbuilt, HOOK-72); `dangerously_skip_build` runs it unattended
    //     (HOOK-74).
    if let Some(build) = &item.build
        && let Err(e) = run_build_hook(item, build, &staging, commit, dangerously_skip_build)
    {
        let _ = remove_path(&staging);
        return Err(e);
    }

    // 2. Swap staging into the store, holding any prior copy in backup.
    if let Some(parent) = store.parent() {
        mkdir_p(parent)?;
    }
    let had_backup = store.exists();
    if had_backup {
        remove_path(&backup)?;
        if let Some(parent) = backup.parent() {
            mkdir_p(parent)?;
        }
        rename(&store, &backup)?;
    }
    if let Err(e) = rename(&staging, &store) {
        if had_backup {
            let _ = rename(&backup, &store); // restore previous version
        }
        return Err(e);
    }

    // 3. Link the store copy into every agent home (targets were checked free in
    //    step 0, or force was given). Under force, any pre-existing foreign target
    //    is stashed before ensure_link removes it so rollback can restore it
    //    (LIFE-43). On any failure, undo the links made so far (restoring their
    //    stashes) and roll the store back.
    let mut links: Vec<std::path::PathBuf> = Vec::new();
    let mut stashes: Vec<Option<std::path::PathBuf>> = Vec::new();
    for (i, link) in planned_links.into_iter().enumerate() {
        // Under force, move any pre-existing foreign target to a stash so it
        // can be restored on rollback. A missing target or mind's own symlink
        // needs no stash. (LIFE-43)
        let stash = if force {
            let sp = paths.tmp_dir().join("foreign-stash").join(i.to_string());
            match maybe_stash_foreign(&store_root, &link, &sp) {
                Ok(true) => Some(sp),
                Ok(false) => None,
                Err(e) => {
                    // Stashing failed: roll back links and store made so far.
                    for (made, s) in links.iter().zip(stashes.iter()) {
                        let _ = remove_path(made);
                        if let Some(s) = s {
                            let _ = rename(s, made);
                        }
                    }
                    let _ = remove_path(&store);
                    if had_backup {
                        let _ = rename(&backup, &store);
                    }
                    return Err(e);
                }
            }
        } else {
            None
        };

        if let Err(e) = ensure_link(&store, &link) {
            // Rollback: remove symlinks made so far, restore their stashes, then
            // restore the store. Also restore the current link's stash if any.
            for (made, s) in links.iter().zip(stashes.iter()) {
                let _ = remove_path(made);
                if let Some(s) = s {
                    let _ = rename(s, made);
                }
            }
            if let Some(s) = &stash {
                let _ = rename(s, &link);
            }
            let _ = remove_path(&store);
            if had_backup {
                let _ = rename(&backup, &store);
            }
            return Err(e);
        }
        links.push(link);
        stashes.push(stash);
    }

    // 4. Success: drop the backup and any foreign-target stashes (the new
    //    symlinks have taken their place; LIFE-43).
    if had_backup {
        let _ = remove_path(&backup);
    }
    for s in stashes.iter().flatten() {
        let _ = remove_path(s);
    }

    Ok(InstalledItem {
        kind,
        name,
        bare_name: item.name.clone(),
        source: item.source.clone(),
        commit: commit.to_string(),
        hash,
        store: paths.store_rel(kind, &item.effective_name()),
        links: links
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect(),
        description: item.description.clone(),
        // spec: HOOK-110 -- filled in by the caller (`install_item` in
        // commands.rs) once the item's install hooks have actually run; this
        // function runs no hooks itself.
        install_hooks: Vec::new(),
        // spec: LNK-19 -- likewise filled in by the caller, which is where the
        // LNK-18 reconciliation decided what to drop; this function only ever
        // sees the already-reconciled item.
        dropped_requires: Vec::new(),
    })
}

/// Remove an installed item using its recorded file registry (absolute link
/// paths across every agent home, then the store copy).
///
/// Before removing any path, each one is verified to be lexically under the
/// expected root (store root for the store copy; a configured lobe for links).
/// Paths that contain `..` components or fail the `starts_with` check are
/// skipped with a warning rather than removed (LIFE-44).
pub fn uninstall(paths: &Paths, item: &InstalledItem) -> Result<()> {
    let store_root = paths.store_dir();
    let agent_homes = paths.agent_homes()?;

    // Precompute canonicalized lobe roots once (LIFE-44). Lobe paths may be
    // stored as relative paths resolved against the cwd at config-load time,
    // but the manifest records absolute link paths (resolved at install time).
    // Canonicalization aligns both sides so a legitimate install-from-other-cwd
    // is not rejected as out-of-bounds.
    let canonical_roots: Vec<PathBuf> = agent_homes
        .iter()
        .map(|h| h.path.canonicalize().unwrap_or_else(|_| h.path.clone()))
        .collect();
    let root_refs: Vec<&Path> = canonical_roots.iter().map(|p| p.as_path()).collect();

    for link in &item.links {
        let p = Path::new(link);
        let canon_p = canonicalize_link_parent(p);
        if !is_confined_under_any(&canon_p, &root_refs) {
            // Secondary check: if the stored link IS absolute and contains no
            // `..` components, allow deletion (the manifest was written by mind
            // itself and the path is structurally safe even if not under a
            // currently-configured lobe). This handles the case where a lobe
            // was removed from config after install.
            if !p.is_absolute() || p.components().any(|c| c == std::path::Component::ParentDir) {
                // spec: DSC-95 -- `p` is built from the manifest-recorded link
                // path, which for an item installed by a pre-DSC-96 binary can
                // carry an unsanitized name; route it through `display_path`
                // like every other source-derived path print site.
                eprintln!(
                    "mind: warning: skipping removal of '{}' -- path is outside all configured agent homes",
                    crate::sanitize::display_path(p)
                );
                continue;
            }
        }
        remove_path(p)?;
    }
    let store_path = paths.mind_home.join(&item.store);
    if !is_confined_under(&store_path, &store_root) {
        // spec: DSC-95
        eprintln!(
            "mind: warning: skipping removal of '{}' -- path is outside the mind store root",
            crate::sanitize::display_path(&store_path)
        );
        return Ok(());
    }
    remove_path(&store_path)?;
    Ok(())
}

/// Canonicalize `link`'s PARENT directory and rejoin the file name, rather
/// than canonicalizing `link` itself, for the LIFE-44 confinement check.
///
/// `link` names a symlink into the store; canonicalizing straight through it
/// (a plain `link.canonicalize()`) follows the symlink to its target (the
/// store), which is never under an agent home, so `is_confined_under_any`
/// would be permanently unreachable for any link that still existed on disk.
/// Canonicalizing the parent resolves any indirection in the directory prefix
/// (e.g. a lobe path recorded relative to another cwd) while leaving the
/// final, possibly-symlinked component untouched, so the comparison lands on
/// the lobe location instead of the store target. If the link no longer
/// exists (or has no parent/file-name component), falls back to the raw path
/// unchanged.
fn canonicalize_link_parent(link: &Path) -> PathBuf {
    link.parent()
        .zip(link.file_name())
        .map(|(parent, name)| {
            parent
                .canonicalize()
                .unwrap_or_else(|_| parent.to_path_buf())
                .join(name)
        })
        .unwrap_or_else(|| link.to_path_buf())
}

/// True when `path` is lexically under `root`: `Path::starts_with(root)` is
/// true AND the path contains no `..` components (which could defeat the
/// component-by-component check on some edge cases where canonicalization has
/// not been performed). (LIFE-44)
pub(crate) fn is_confined_under(path: &Path, root: &Path) -> bool {
    use std::path::Component;
    if path.components().any(|c| c == Component::ParentDir) {
        return false;
    }
    path.starts_with(root)
}

/// True when `path` is confined under at least one of `roots`. (LIFE-44)
fn is_confined_under_any(path: &Path, roots: &[&Path]) -> bool {
    roots.iter().any(|root| is_confined_under(path, root))
}

/// Recreate any missing links for an installed item, pointing at its existing
/// store copy. Returns the number of links repaired. Used by `introspect --fix`.
/// If the store copy itself is gone there is nothing to link to, so it repairs
/// nothing (that is drift for `upgrade`/`learn` to resolve, not a re-link).
///
/// Links belonging to an unreachable lobe (STO-56: the lobe's parent directory
/// no longer exists) are skipped: a vanished project should not be recreated.
pub fn relink(paths: &Paths, item: &InstalledItem) -> Result<usize> {
    let store = paths.mind_home.join(&item.store);
    if !store.exists() {
        return Ok(0);
    }
    // spec: STO-56 -- skip links whose lobe parent is gone.
    let agent_homes = paths.agent_homes()?;
    let mut fixed = 0;
    for link_str in &item.links {
        let link = Path::new(link_str);
        // Determine if this link belongs to a reachable lobe. If it is not under
        // any configured lobe path, assume reachable (fallback preserves behavior).
        let reachable = agent_homes
            .iter()
            .find(|lobe| link.starts_with(&lobe.path))
            .is_none_or(|lobe| lobe.reachable());
        if !reachable {
            continue;
        }
        if std::fs::symlink_metadata(link).is_err() {
            ensure_link(&store, link)?;
            fixed += 1;
        }
    }
    Ok(fixed)
}

/// Link an already-installed item into one or more new lobes (HARN-7/HARN-8).
/// Recovers `link_rel` from the item's existing links by stripping known lobe
/// prefixes; falls back to `paths.default_link_rel`. Returns the paths
/// successfully created and (path, error) pairs for failures.
/// Does NOT update the manifest — the caller records created paths into item.links.
///
/// spec: HARN-17 -- unless `force` is set, each target is guarded by the same
/// `ensure_unoccupied` check the install path uses (LIFE-41): a pre-existing
/// foreign file or directory is never clobbered. A blocked target is reported
/// via the ordinary `LinkOccupied` failure (naming the `--force` remedy) in the
/// returned `failed` list, exactly like any other link failure.
pub fn link_into_new_lobes(
    paths: &Paths,
    item: &InstalledItem,
    new_lobes: &[crate::paths::Lobe],
    force: bool,
) -> (
    Vec<std::path::PathBuf>,
    Vec<(std::path::PathBuf, MindError)>,
) {
    let mut created = Vec::new();
    let mut failed = Vec::new();

    let agent_homes = paths.agent_homes().unwrap_or_default();
    let link_rel = item.links.iter().find_map(|link_str| {
        let link = Path::new(link_str);
        agent_homes
            .iter()
            .find_map(|lobe| link.strip_prefix(&lobe.path).ok())
            .map(|rel| rel.to_string_lossy().into_owned())
    });
    let link_rel = match link_rel.or_else(|| paths.default_link_rel(item.kind, &item.name)) {
        Some(rel) => rel,
        None => return (created, failed),
    };

    let store = paths.mind_home.join(&item.store);
    let store_root = paths.store_dir();
    for lobe in new_lobes {
        if !lobe.admits(item.kind) {
            continue;
        }
        let expected = lobe.path.join(&link_rel);
        let expected_str = expected.to_string_lossy().into_owned();
        if item.links.iter().any(|l| l == &expected_str) {
            continue;
        }
        if !force && let Err(e) = ensure_unoccupied(&store_root, &expected) {
            failed.push((expected, e));
            continue;
        }
        match ensure_link(&store, &expected) {
            Ok(()) => created.push(expected),
            Err(e) => failed.push((expected, e)),
        }
    }
    (created, failed)
}

/// Under a forced install, move a pre-existing foreign target at `link` to
/// `stash` so it can be restored on rollback (LIFE-43). Returns `true` when
/// the target was moved (a stash was created). Returns `false` when the link
/// is absent or is already mind's own symlink into the store (no stash needed).
///
/// Uses the same "is mind's own" predicate as `ensure_unoccupied`: a symlink
/// pointing into `store_root` is ours; everything else (regular file, directory,
/// symlink to another location) is foreign.
///
/// Called only when `force` is true. The non-force path uses `ensure_unoccupied`
/// which refuses to touch foreign targets at all.
fn maybe_stash_foreign(store_root: &Path, link: &Path, stash: &Path) -> Result<bool> {
    let meta = match std::fs::symlink_metadata(link) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(MindError::io(link, e)),
        Ok(m) => m,
    };
    // Mind's own symlink: no stash needed.
    if meta.file_type().is_symlink()
        && std::fs::read_link(link).is_ok_and(|t| t.starts_with(store_root))
    {
        return Ok(false);
    }
    // Foreign target: move it to the stash so rollback can rename it back.
    if let Some(parent) = stash.parent() {
        mkdir_p(parent)?;
    }
    rename(link, stash)?;
    Ok(true)
}

/// Lobe paths already reported unreachable this process (HARN-16), so the note
/// is printed once per lobe rather than once per skipped item.
static WARNED_UNREACHABLE_LOBES: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();

/// Print a one-time (per-process) note when a configured lobe is skipped at
/// install time because its parent directory does not exist (STO-56/HARN-16).
/// Names both remedies: create the missing directory (making the lobe
/// reachable), or drop the lobe from config with `mind config lobes remove
/// <path>`. Deduplicated by lobe path so a multi-item `learn`/`meld` prints it
/// once, not once per affected item.
fn note_unreachable_lobe_once(path: &Path) {
    let seen = WARNED_UNREACHABLE_LOBES.get_or_init(|| Mutex::new(HashSet::new()));
    let mut seen = seen
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if seen.insert(path.to_path_buf()) {
        // spec: CLI-217 -- this runs on the ordinary `learn`/`meld` install path,
        // ahead of the verb's `print_json`, so it must not be a bare `println!`.
        // spec: CLI-225 -- the lobe path comes from user config (`~/.mind/config.toml`),
        // not restricted against shell metacharacters, and lands in a pasteable
        // `mind config lobes remove <path>` remedy, so it is shell-quoted first.
        let quoted_path = crate::error::shell_quote(&path.display().to_string());
        crate::render::note(format!(
            "note: lobe '{}' is unreachable (its parent directory does not exist); \
             create the missing directory, or run `mind config lobes remove {quoted_path}` to drop it",
            path.display()
        ));
    }
}

/// Refuse to install over a link target that mind does not own. A target is
/// "ours" only if it is a symlink pointing into the store root; a regular file,
/// a directory, or a symlink elsewhere is the user's and is left untouched
/// (`LinkOccupied`). A missing target is free.
fn ensure_unoccupied(store_root: &Path, link: &Path) -> Result<()> {
    match std::fs::symlink_metadata(link) {
        Ok(meta) => {
            let ours = meta.file_type().is_symlink()
                && std::fs::read_link(link).is_ok_and(|t| t.starts_with(store_root));
            if ours {
                Ok(())
            } else {
                Err(MindError::LinkOccupied {
                    path: link.display().to_string(),
                })
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(MindError::io(link, e)),
    }
}

/// Create (or refresh) a symlink at `link` pointing to `store`.
pub(crate) fn ensure_link(store: &Path, link: &Path) -> Result<()> {
    if let Some(parent) = link.parent() {
        mkdir_p(parent)?;
    }
    remove_path(link)?;
    symlink(store, link)
}

/// Rewrite reference tokens in every markdown file under the staged copy (the
/// extension test `namespace::is_markdown`, NS-53; a token in a non-markdown
/// file is left literal): the `{{ns:name}}` name tokens, then the `{{self}}` /
/// `{{tools:name}}` / `{{path:ref}}` path tokens. Both resolve against
/// `siblings` (every item in the same source) and a bad reference in either
/// pass aborts the staged install.
/// A non-markdown file the item lists in `expand:` is expanded too (NS-57), with
/// path tokens rendered absolute rather than the TOOL-16 `~` form (TOOL-20).
/// Also validates the `requires` frontmatter entries (DEP-6): each must resolve
/// to exactly one sibling (not source-qualified, not ambiguous, not missing);
/// and each `expand:` entry must be a safe relative path naming a shipped file.
fn expand_references(
    root: &Path,
    item: &CatalogItem,
    siblings: &[CatalogItem],
    store_root: &Path,
) -> Result<()> {
    let names: std::collections::HashSet<String> =
        siblings.iter().map(|s| s.name.clone()).collect();
    // spec: NS-42 -- agent referents expand bare even under a prefix. Compute the
    // set of agent bare names that are NOT also a non-agent sibling name (the
    // cross-kind shadow rule: if a name is both an agent and a skill/rule/tool, it
    // is NOT bare -- it keeps the prefix).
    let agent_names: std::collections::HashSet<String> = siblings
        .iter()
        .filter(|s| s.kind == crate::error::ItemKind::Agent)
        .map(|s| s.name.clone())
        .collect();
    let non_agent_names: std::collections::HashSet<String> = siblings
        .iter()
        .filter(|s| s.kind != crate::error::ItemKind::Agent)
        .map(|s| s.name.clone())
        .collect();
    let bare_names: std::collections::HashSet<String> =
        agent_names.difference(&non_agent_names).cloned().collect();
    let path_siblings: Vec<namespace::PathSibling> =
        siblings.iter().map(CatalogItem::as_path_sibling).collect();
    // TOOL-16: render store paths with a leading `~` when the store is under
    // home, so a token expands to a value a Claude permission glob can match.
    let home = dirs::home_dir();
    let ctx = namespace::PathCtx {
        store_root,
        home: home.as_deref(),
        prefix: &item.prefix,
        self_kind: item.kind,
        self_name: &item.name,
        siblings: &path_siblings,
    };
    // NS-57/TOOL-20: an `expand:`-listed non-markdown file renders path tokens
    // as an absolute store path (home = None), since it is program input read by
    // something that does not expand a leading `~` the way TOOL-16's markdown
    // form assumes.
    let ctx_abs = namespace::PathCtx { home: None, ..ctx };

    // DEP-6: validate every `requires` entry before touching any file. A bad
    // entry here aborts the staged install (the live copy is still untouched).
    // spec: DSC-95 -- `MindError::BadReference`'s `#[error(...)]` Display
    // interpolates `item`, `referent`, and `in_source` verbatim, with no
    // sanitizing step of its own, so every field handed to it here is
    // sanitized at construction. `item.key()` was already validated by
    // `is_safe_item_name` (DSC-96), so `.display()` there is defense-in-depth
    // only; `referent` and `in_source` are NOT pre-validated (an `{{ns:}}`
    // token's inner text, or a `requires`/`expand` entry, or a source name
    // read from an arbitrary directory), so each is run through
    // `sanitize::strip_ansi` at its call site, BEFORE it is composed into a
    // larger wrapper string (sanitize.rs's doc: compose-then-sanitize lets one
    // field's dangling escape eat its neighbors).
    let bad_ref = |referent: String, reason: crate::error::BadRefReason| MindError::BadReference {
        item: item.key().display(),
        referent,
        reason,
        in_source: crate::sanitize::strip_ansi(&item.source),
    };
    // A `requires` entry that fails to resolve names the specific cause (DEP-7),
    // mirroring what `review` reports, so the install-time error is not the blunt
    // "does not match any item" for a ref that in fact crosses sources, is
    // malformed, or is merely ambiguous.
    let bad_requires = |entry: &str, reason| {
        // spec: DSC-95 -- sanitize the raw mind.toml `requires` entry before
        // composing it into the `"requires: {entry}"` wrapper.
        let entry = crate::sanitize::strip_ansi(entry);
        bad_ref(format!("requires: {entry}"), reason)
    };
    for entry in &item.requires {
        // spec: DEP-6 DEP-7
        use crate::error::BadRefReason::{AmbiguousKind, CrossSource, InvalidRef};
        let r =
            crate::resolve::parse_item_ref(entry).map_err(|_| bad_requires(entry, InvalidRef))?;
        // Source-qualified entries cross sources, which is forbidden (DEP-5).
        if r.source.is_some() {
            return Err(bad_requires(entry, CrossSource));
        }
        // Resolve against siblings by bare name, narrowing by kind (DEP-5).
        let matches: Vec<&CatalogItem> = siblings
            .iter()
            .filter(|s| s.name == r.name && r.kind.is_none_or(|k| s.kind == k))
            .collect();
        if matches.is_empty() {
            // A genuine typo/unknown item (DEP-6).
            return Err(bad_requires(entry, NoMatch));
        }
        if matches.len() > 1 && r.kind.is_none() {
            // A bare name matching several kinds without a qualifier (DEP-6).
            return Err(bad_requires(entry, AmbiguousKind));
        }
    }

    // NS-57: validate every `expand:` entry before staging touches a file. Each
    // must be a safe relative path (no absolute, no `..`) naming a file the item
    // ships; a bad entry aborts the staged install as a BadReference, the same
    // transactional pre-swap failure a bad `requires` or `{{ns:}}` raises, so a
    // typo is caught loudly rather than left as an un-expanded literal.
    // spec: DSC-95 -- sanitize the raw mind.toml `expand` entry before
    // composing it into the `"expand: {entry}"` wrapper (same rationale as
    // `bad_requires` above).
    let bad_expand = |entry: &str, reason| {
        let entry = crate::sanitize::strip_ansi(entry);
        bad_ref(format!("expand: {entry}"), reason)
    };
    let mut expand_set: std::collections::HashSet<std::path::PathBuf> =
        std::collections::HashSet::new();
    for entry in &item.expand {
        // spec: NS-57
        use crate::error::BadRefReason::InvalidRef;
        let rel = Path::new(entry);
        let unsafe_path = rel.components().any(|c| {
            matches!(
                c,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        });
        if unsafe_path {
            return Err(bad_expand(entry, InvalidRef));
        }
        // Must name a real file within the staged item. A single-file item
        // (agent/rule) has no bundled files, so any entry is a miss.
        if !(root.is_dir() && root.join(rel).is_file()) {
            return Err(bad_expand(entry, NoMatch));
        }
        expand_set.insert(rel.to_path_buf());
    }

    let mut files = Vec::new();
    if root.is_dir() {
        collect_files(root, &mut files)?;
    } else {
        files.push(root.to_path_buf());
    }
    for file in files {
        // NS-53: all four token families expand only in a markdown file. A
        // token in any other file (a script, data) is left exactly as written
        // -- including one that would not resolve, which retires the
        // BadReference this loop used to raise for it (NS-11/NS-12 are scoped
        // to markdown accordingly).
        //
        // A directory item (skill/tool) stages every file under its original
        // name, so `file` itself carries the right extension to check. A
        // single-file item (agent/rule) stages as a bare name with no
        // extension at all (matching its store form), so its markdown-ness is
        // read from the source path instead.
        let source_like: &Path = if root.is_dir() { &file } else { &item.path };
        let is_md = namespace::is_markdown(source_like);
        // NS-57: a file listed in `expand:` is expanded like markdown even
        // though its extension is not, so a bundled script can reference a
        // sibling tool. Its relative path (under the staged dir) is what the
        // validated `expand_set` holds.
        let is_listed = root.is_dir()
            && file
                .strip_prefix(root)
                .map(|rel| expand_set.contains(rel))
                .unwrap_or(false);
        if !is_md && !is_listed {
            continue;
        }
        // Skip anything that is not valid UTF-8 text.
        let Ok(content) = std::fs::read_to_string(&file) else {
            continue;
        };
        if !content.contains("{{") {
            continue;
        }
        // TOOL-20: a listed non-markdown file renders path tokens absolute; a
        // markdown file keeps the TOOL-16 `~` form.
        let path_ctx = if is_listed && !is_md { &ctx_abs } else { &ctx };
        let expanded =
            namespace::expand(&content, &item.prefix, &names, &bare_names).map_err(|name| {
                // spec: DSC-95 -- `name` is the raw `{{ns:name}}` inner text
                // (`namespace::expand` enforces no character class on it), so
                // sanitize it BEFORE composing the `{{ns:...}}` wrapper below.
                let name = crate::sanitize::strip_ansi(&name);
                bad_ref(format!("{{{{ns:{name}}}}}"), NoMatch)
            })?;
        let expanded =
            namespace::expand_paths(&expanded, path_ctx).map_err(|(referent, reason)| {
                // spec: DSC-95 -- `referent` arrives already composed by
                // `namespace::expand_paths`; sanitize the whole (single, final)
                // value here since nothing further is appended to it afterward.
                bad_ref(crate::sanitize::strip_ansi(&referent), reason)
            })?;
        std::fs::write(&file, expanded).map_err(|e| MindError::io(&file, e))?;
    }
    Ok(())
}

/// Run an item's build hook in its staging directory. Disclosed and prompted on
/// a TTY (two-way: run, or skip and install unbuilt); a non-TTY context skips it
/// (HOOK-72); `dangerously_skip` runs it unattended (HOOK-74). A non-zero exit
/// is a hard stop (HOOK-71) the caller rolls back.
fn run_build_hook(
    item: &CatalogItem,
    build: &str,
    staging: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    // spec: HOOK-72 HOOK-74
    let run = if dangerously_skip {
        true
    } else if !crate::hook::is_tty() {
        // spec: CLI-217
        crate::render::note(format!(
            "note: skipped build hook for {} in a non-interactive context; its tooling is not built",
            item.display_key()
        ));
        false
    } else {
        let disclosure = crate::hook::disclosure_text(
            &item.source,
            "(per-item build)",
            commit,
            &staging.to_string_lossy(),
            build,
            None,
            None, // no browse URL for per-item build hooks (HOOK-24: local path only)
        );
        matches!(
            crate::hook::prompt_choice_optional(&disclosure)?,
            crate::hook::OptionalChoice::Run
        )
    };
    if run {
        // A progress line, not an aside: it belongs on stdout in text mode, and
        // under `--json` the whole run's fd 1 already points at stderr
        // (main.rs's `json_stdout`), so it cannot reach the result document.
        // spec: CLI-217
        println!("running build hook for {}", item.display_key());
        crate::hook::run_hook(build, staging, &item.source, "build", "build")?;
    } else if crate::hook::is_tty() && !dangerously_skip {
        // spec: CLI-217
        crate::render::note(format!(
            "note: skipped build hook for {}; its tooling is not built",
            item.display_key()
        ));
    }
    Ok(())
}

/// The working directory for an item lifecycle hook: the item's store path when
/// it is a directory (a skill or tool), else its parent (an agent/rule store is a
/// single file, so the kind directory is the working dir).
fn hook_cwd(store: &Path) -> std::path::PathBuf {
    if store.is_dir() {
        store.to_path_buf()
    } else {
        store
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| store.to_path_buf())
    }
}

/// Run a per-item lifecycle hook (`event` is "install", HOOK-81, "update",
/// HOOK-120/125, or "uninstall", HOOK-82) in the item's store directory: the
/// final step of an install/update, or the step before a removal. Disclosed and
/// prompted two-way (run / skip) on a TTY; a non-TTY context skips it;
/// `dangerously_skip` runs it unattended (HOOK-83). A non-zero exit is a
/// `HookFailed` hard stop the caller acts on (install/update rolls back;
/// uninstall leaves the item installed).
///
/// Returns whether the hook actually RAN (`true`) or was skipped (`false`),
/// so an install-hook caller can record the outcome (HOOK-110).
///
/// `display_key` is display-only (DSC-95): it lands straight in a
/// `println!`/[`crate::render::note`] below, never in an identity comparison
/// or a filesystem path, so a caller MUST pass an already-sanitized value
/// (e.g. [`CatalogItem::display_key`]/[`InstalledItem::display_key`]), never a
/// raw item key.
///
/// `label` and `optional` are the hook's own [`crate::mindfile::ResolvedHook`]
/// fields (its declared `name`/`run`, HOOK-51, and its `optional` flag), routed
/// through `hook::hook_disclosure_text` so the disclosure names the hook and
/// its lifecycle event on dedicated `Hook:`/`Event:` lines (HOOK-51, HOOK-120)
/// instead of smuggling the event into the `Pin:` field.
#[allow(clippy::too_many_arguments)]
fn run_item_hook(
    event: &'static str,
    label: &str,
    optional: bool,
    display_key: &str,
    source: &str,
    cmd: &str,
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<bool> {
    // The noun for the side effect the hook applies, per event: install and
    // update both apply a side effect; uninstall runs cleanup.
    let effect = match event {
        "install" | "update" => "its side effect is not applied",
        _ => "its cleanup is not run",
    };
    let cwd = hook_cwd(store);
    let run = if dangerously_skip {
        true
    } else if !crate::hook::is_tty() {
        // spec: CLI-217
        crate::render::note(format!(
            "note: skipped {event} hook for {display_key} in a non-interactive context; {effect}"
        ));
        false
    } else {
        // spec: HOOK-120, HOOK-51 -- name the hook and its own lifecycle event
        // on dedicated lines, mirroring the source-hook disclosure, rather than
        // folding the event into the `Pin:` field (which is documented as the
        // resolved branch/tag/ref, HOOK-20) or dropping the hook's `name`.
        let disclosure = crate::hook::hook_disclosure_text(
            label,
            event,
            optional,
            source,
            "(per-item)",
            commit,
            &cwd.to_string_lossy(),
            cmd,
            None,
            None, // no browse URL for per-item lifecycle hooks (HOOK-24: local path only)
        );
        matches!(
            crate::hook::prompt_choice_optional(&disclosure)?,
            crate::hook::OptionalChoice::Run
        )
    };
    if run {
        // Same as the build-hook line above: a progress line on stdout in text
        // mode, unreachable from `--json` stdout by the process-wide redirect.
        // spec: CLI-217
        println!("running {event} hook for {display_key}");
        crate::hook::run_hook(cmd, &cwd, source, event, event)?;
    } else if crate::hook::is_tty() && !dangerously_skip {
        // spec: CLI-217
        crate::render::note(format!(
            "note: skipped {event} hook for {display_key}; {effect}"
        ));
    }
    Ok(run)
}

/// Run one batch of an item's lifecycle hooks (HOOK-81, HOOK-86) as the final
/// step of installing it, in declaration order. Despite the name, `hooks` need
/// not all be install-event hooks: the callers in `commands.rs`
/// (`install_item`) and `hooks_cmd.rs` (`hooks run`) also pass an item's
/// update-event batch here on `upgrade` (HOOK-120/125), since an update batch
/// is disclosed, prompted, and recorded exactly like an install one, just
/// under its own `Event:` line (HOOK-51, HOOK-120). Each entry is disclosed,
/// prompted, and fails exactly as the scalar shorthand does (HOOK-86): a
/// non-zero exit aborts the loop and the caller rolls the install back. An
/// empty list is a no-op.
///
/// Returns one [`crate::source::RecordedHook`] per hook offered, in the same
/// order, so the caller can persist the outcome on the item's manifest record
/// (HOOK-110): `ran_at = Some(commit)` for a hook that ran, `ran_at = None` for
/// one that was offered but skipped (mirrors the source-level mechanism,
/// HOOK-55). A hook whose failure aborts the loop is not represented in the
/// returned vec (its error propagates instead and the caller rolls the whole
/// install back, so there is nothing to record).
///
/// This is the entry point used by the `learn`/`upgrade` install path
/// (`commands::install_item`), where a hook failure rolls the whole
/// just-installed item back (HOOK-86): there is no manifest entry left to
/// attach a partial record to, so discarding the partial vec on error is
/// correct here. A caller that instead runs hooks against an item that stays
/// installed regardless of the outcome (`hooks run`, HOOK-102) needs the
/// hooks recorded before the failure too; see
/// [`run_item_install_hooks_partial`] for that shape.
pub fn run_item_install_hooks(
    item: &CatalogItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<Vec<crate::source::RecordedHook>> {
    let mut recorded = Vec::with_capacity(hooks.len());
    run_item_install_hooks_recording(item, hooks, store, commit, dangerously_skip, &mut recorded)?;
    Ok(recorded)
}

/// Same hook batch as [`run_item_install_hooks`] (install- or update-event,
/// per that function's doc), but for a caller whose item is already installed
/// and stays installed regardless of the batch's outcome (`hooks run`,
/// HOOK-102). Returns the hooks recorded before an abort
/// alongside the error, mirroring `run_source_hooks`'s "save whatever was
/// recorded so far before propagating the error" (HOOK-53): the caller can
/// persist the partial vec to the manifest before returning the error, so a
/// hook that already ran its side effect is not offered again on retry
/// (HOOK-110).
pub fn run_item_install_hooks_partial(
    item: &CatalogItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> (Vec<crate::source::RecordedHook>, Result<()>) {
    let mut recorded = Vec::with_capacity(hooks.len());
    let result = run_item_install_hooks_recording(
        item,
        hooks,
        store,
        commit,
        dangerously_skip,
        &mut recorded,
    );
    (recorded, result)
}

/// Shared loop backing [`run_item_install_hooks`] and
/// [`run_item_install_hooks_partial`] (install- or update-event batch, per
/// their docs): runs each hook in order, pushing its outcome onto `recorded`
/// as it goes (not only on overall success), so a caller holding a `&mut`
/// into `recorded` sees every hook that ran or was offered before an abort
/// even though this function returns early via `?`.
fn run_item_install_hooks_recording(
    item: &CatalogItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
    recorded: &mut Vec<crate::source::RecordedHook>,
) -> Result<()> {
    for hook in hooks {
        // spec: HOOK-120, HOOK-51 -- the disclosure and every note name the
        // hook's own event and label, so an update hook is never announced as
        // an install one, and a named hook is never shown anonymously.
        let ran = run_item_hook(
            hook.event.as_str(),
            hook.label(),
            hook.optional,
            &item.display_key(),
            &item.source,
            &hook.run,
            store,
            commit,
            dangerously_skip,
        )?;
        recorded.push(crate::source::RecordedHook {
            command: hook.run.clone(),
            ran_at: if ran { Some(commit.to_string()) } else { None },
        });
    }
    Ok(())
}

/// Run an item's uninstall hooks (HOOK-82, HOOK-86) before its store copy and
/// links go, in declaration order. A non-zero exit aborts the loop and the caller
/// leaves the item installed. An empty list is a no-op.
pub fn run_item_uninstall_hooks(
    item: &InstalledItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    for hook in hooks {
        run_item_hook(
            "uninstall",
            hook.label(),
            hook.optional,
            &item.display_key(),
            &item.source,
            &hook.run,
            store,
            commit,
            dangerously_skip,
        )?;
    }
    Ok(())
}

/// Maximum directory nesting inside a single item tree (LIFE-52), far above
/// any real layout. Converts a pathological or crafted deeply-nested source
/// into a structured error instead of a stack overflow. Shared with the
/// `hash_path` walk in `hash.rs`.
pub(crate) const MAX_ITEM_TREE_DEPTH: usize = 128;

/// The LIFE-52 depth-cap error, naming the path where the cap was hit.
pub(crate) fn depth_exceeded(path: &Path) -> MindError {
    MindError::io(
        path,
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("item tree exceeds {MAX_ITEM_TREE_DEPTH} nested directories"),
        ),
    )
}

/// Every file under `dir`, recursively, depth-capped (LIFE-52).
///
/// `pub(crate)` so the LNK-18 pre-install reference scan in `commands.rs` walks
/// an item tree exactly the way the install path does: one capped walker that
/// surfaces a structured error, rather than a second, uncapped one whose
/// failures are silent.
pub(crate) fn collect_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) -> Result<()> {
    collect_files_at(dir, out, 0)
}

// spec: LIFE-52
fn collect_files_at(dir: &Path, out: &mut Vec<std::path::PathBuf>, depth: usize) -> Result<()> {
    if depth > MAX_ITEM_TREE_DEPTH {
        return Err(depth_exceeded(dir));
    }
    let rd = std::fs::read_dir(dir).map_err(|e| MindError::io(dir, e))?;
    for entry in rd {
        let entry = entry.map_err(|e| MindError::io(dir, e))?;
        let path = entry.path();
        if path.is_dir() {
            collect_files_at(&path, out, depth + 1)?;
        } else {
            out.push(path);
        }
    }
    Ok(())
}

fn rename(from: &Path, to: &Path) -> Result<()> {
    std::fs::rename(from, to).map_err(|e| MindError::io(to, e))
}

/// Best-effort removal of a file, dir, or symlink; "not found" is success.
pub(crate) fn remove_path(path: &Path) -> Result<()> {
    let meta = match std::fs::symlink_metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(MindError::io(path, e)),
    };
    let res = if meta.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        std::fs::remove_file(path)
    };
    res.map_err(|e| MindError::io(path, e))
}

/// Copy a source item tree into `dst`, refusing any symlink entry (LIFE-42).
///
/// Uses `symlink_metadata` (no-follow) to determine whether each entry is a
/// directory, a regular file, or a symlink. A symlink anywhere in the tree is
/// rejected with an `Io` error carrying the offending path, so a crafted source
/// cannot exfiltrate secrets or cause unbounded recursion via a directory cycle.
///
/// Exported as `pub(crate)` so the surface shard's `--snapshot` frozen-copy can
/// reuse this implementation without duplicating the symlink-rejection logic.
pub(crate) fn copy_recursive(src: &Path, dst: &Path) -> Result<()> {
    copy_recursive_at(src, dst, 0, src, &crate::ignore::IgnoreSet::default())
}

/// Copy an item tree, skipping what its ignore set excludes (IGN-10).
///
/// `root` stays the item root across the recursion so a pattern is matched
/// against the ITEM-relative path, which is how they are written in
/// `mind.toml`. An ignored directory is not descended into, so its subtree
/// costs nothing to skip and cannot contribute a file by another route.
pub(crate) fn copy_recursive_ignoring(
    src: &Path,
    dst: &Path,
    ignore: &crate::ignore::IgnoreSet,
) -> Result<()> {
    copy_recursive_at(src, dst, 0, src, ignore)
}

// spec: LIFE-52 -- depth-capped; LIFE-42's symlink rejection already blocks
// cycle-driven recursion, the cap covers plain deep nesting.
fn copy_recursive_at(
    src: &Path,
    dst: &Path,
    depth: usize,
    root: &Path,
    ignore: &crate::ignore::IgnoreSet,
) -> Result<()> {
    if depth > MAX_ITEM_TREE_DEPTH {
        return Err(depth_exceeded(src));
    }
    let meta = std::fs::symlink_metadata(src).map_err(|e| MindError::io(src, e))?;
    if meta.file_type().is_symlink() {
        return Err(MindError::io(
            src,
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "source item trees must not contain symlinks",
            ),
        ));
    }
    if meta.is_dir() {
        mkdir_p(dst)?;
        let rd = std::fs::read_dir(src).map_err(|e| MindError::io(src, e))?;
        for entry in rd {
            let entry = entry.map_err(|e| MindError::io(src, e))?;
            let from = entry.path();
            // spec: IGN-10 -- excluded here, and by the identical test in the
            // hash walk, so what is not installed is not hashed. Classified with
            // `symlink_metadata` (no-follow), same as the hash walk, so a
            // symlink pointing at a directory is never a directory to either: a
            // directory-only rule (all four built-ins, and any `name/` entry)
            // does not match it, so it hard-fails LIFE-42's symlink rejection
            // instead of being silently skipped; a no-slash rule matches it in
            // both walks and it is skipped by both.
            let rel = from.strip_prefix(root).unwrap_or(&from);
            let from_meta =
                std::fs::symlink_metadata(&from).map_err(|e| MindError::io(&from, e))?;
            let is_dir = from_meta.is_dir();
            if ignore.is_ignored(rel, is_dir) {
                continue;
            }
            let to = dst.join(entry.file_name());
            copy_recursive_at(&from, &to, depth + 1, root, ignore)?;
        }
    } else {
        if let Some(parent) = dst.parent() {
            mkdir_p(parent)?;
        }
        std::fs::copy(src, dst).map_err(|e| MindError::io(dst, e))?;
    }
    Ok(())
}

#[cfg(unix)]
fn symlink(target: &Path, link: &Path) -> Result<()> {
    std::os::unix::fs::symlink(target, link).map_err(|e| MindError::io(link, e))
}

#[cfg(not(unix))]
fn symlink(target: &Path, link: &Path) -> Result<()> {
    // On non-unix, fall back to a copy so the layout still works. Known
    // limitation: a copied link is not recognized as mind's own by the clobber
    // guard (`ensure_unoccupied` keys on "symlink into the store"), so reinstall
    // / upgrade over it reports `LinkOccupied`. mind is unix-first; see the
    // platform-limitation note in spec/lifecycle.md.
    copy_recursive(target, link)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use crate::hash::hash_path_ignoring;
    use crate::ignore::IgnoreSet;
    use crate::paths::Lobe;
    use std::sync::atomic::{AtomicU32, Ordering};

    static N: AtomicU32 = AtomicU32::new(0);

    // ---- STO-56: reachability gate -------------------------------------------

    /// `Lobe::reachable()` returns true when the parent dir exists, false when it
    /// does not. This is the primitive the install-time filter and relink use.
    ///
    /// `link_into_new_lobes` (backfill on explicit lobe-add) intentionally does
    /// NOT apply the reachability gate: it is an explicit user action, and
    /// `ensure_link` creates intermediate dirs. The gate applies at install-time
    /// (`planned_links`) and at `relink` (introspect --fix must not recreate links
    /// in vanished projects).
    #[test]
    fn lobe_reachable_gate_covers_planned_links_and_relink() {
        // spec: STO-56
        let n = N.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-reach-gate-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let existing_parent = base.join("existing-project");
        std::fs::create_dir_all(&existing_parent).unwrap();
        let reachable_lobe = Lobe {
            path: existing_parent.join(".windsurf"),
            kinds: Some(vec![ItemKind::Skill]),
        };
        assert!(
            reachable_lobe.reachable(),
            "lobe is reachable when parent exists"
        );

        let gone_parent = base.join("vanished-project");
        // Deliberately do NOT create gone_parent.
        let unreachable_lobe = Lobe {
            path: gone_parent.join(".windsurf"),
            kinds: Some(vec![ItemKind::Skill]),
        };
        assert!(
            !unreachable_lobe.reachable(),
            "lobe is unreachable when parent is missing (STO-56)"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    /// `relink` must skip a link that belongs to a configured but unreachable lobe
    /// (its parent directory has been deleted). The link stays unrepaired and no
    /// error is returned. The reachable lobe's link IS repaired.
    #[cfg(unix)]
    #[test]
    fn relink_skips_link_in_unreachable_lobe() {
        // spec: STO-56
        let n = N.fetch_add(1, Ordering::SeqCst);
        let base =
            std::env::temp_dir().join(format!("mind-reach-relink-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        // Write a store directory for the item.
        let store_rel = "store/skill/myskill";
        let store_path = mind_home.join(store_rel);
        std::fs::create_dir_all(&store_path).unwrap();
        std::fs::write(store_path.join("SKILL.md"), b"# My Skill\n").unwrap();

        // A project lobe whose parent does NOT exist (vanished project).
        let vanished_project = base.join("vanished");
        let project_lobe = vanished_project.join(".windsurf");
        let project_link = project_lobe.join("skills").join("myskill");

        // Write a config that includes the project lobe (unreachable: its parent
        // vanished_project does not exist).
        let cfg = format!(
            "lobes = [\"{claude}\", \"{project}\"]\n",
            claude = claude_home.display(),
            project = project_lobe.display(),
        );
        std::fs::write(mind_home.join("config.toml"), cfg.as_bytes()).unwrap();

        let paths = crate::paths::Paths {
            mind_home: mind_home.clone(),
            claude_home: claude_home.clone(),
        };

        // The installed item has recorded links under both lobes; neither link
        // currently exists (they were broken). relink should repair the one under
        // claude_home (reachable) but skip the one under the project lobe (gone).
        let claude_link = claude_home.join("skills").join("myskill");

        let item = InstalledItem {
            kind: ItemKind::Skill,
            name: "myskill".to_string(),
            bare_name: "myskill".to_string(),
            source: "local/test".to_string(),
            commit: "abc".to_string(),
            hash: "deadbeef".to_string(),
            store: store_rel.to_string(),
            links: vec![
                claude_link.to_string_lossy().into_owned(),
                project_link.to_string_lossy().into_owned(),
            ],
            description: None,
            install_hooks: Vec::new(),
            dropped_requires: Vec::new(),
        };

        let fixed = relink(&paths, &item).unwrap();
        // Only the claude_home link should have been repaired; the project link is
        // skipped because the project lobe is unreachable (STO-56).
        assert_eq!(
            fixed, 1,
            "relink must repair exactly 1 link (claude_home); project lobe must be skipped (STO-56)"
        );
        assert!(
            claude_link.exists() || std::fs::symlink_metadata(&claude_link).is_ok(),
            "claude_home link must have been created by relink"
        );
        assert!(
            !project_link.exists(),
            "project lobe link must not be created for an unreachable lobe (STO-56)"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    fn tool_item(build: &str, path: std::path::PathBuf) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Tool,
            name: "t".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: Some(build.to_string()),
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        }
    }

    #[test]
    fn build_hook_is_skipped_without_a_tty() {
        // spec: HOOK-72
        // The test harness has no TTY, so the build hook must be skipped (the item
        // installs unbuilt): the command must not run, and the call still succeeds.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-build-skip-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        let marker = staging.join("built");
        let item = tool_item(
            &format!("touch {}", marker.display()),
            std::path::PathBuf::from("/src/tools/t"),
        );

        run_build_hook(
            &item,
            item.build.as_deref().unwrap(),
            &staging,
            "abc123",
            false,
        )
        .unwrap();
        assert!(
            !marker.exists(),
            "a non-TTY context must skip the build hook (HOOK-72)"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    // ---- DEP-6: `requires` validation in expand_references -----------------

    /// Build a minimal skill CatalogItem pointing at the given staging dir.
    fn skill_item_at(name: &str, path: std::path::PathBuf, requires: Vec<String>) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Skill,
            name: name.to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires,
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        }
    }

    fn agent_item_at(name: &str, path: std::path::PathBuf) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Agent,
            name: name.to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        }
    }

    #[test]
    fn requires_valid_entry_passes_validation() {
        // spec: DEP-6
        // A `requires: agent:test` entry that resolves to an existing sibling
        // must pass validation and allow expand_references to proceed.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging = std::env::temp_dir().join(format!("mind-req-ok-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        // A text file without any {{ so expand_references reaches the requires check
        // but skips file expansion.
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:test".to_string()],
        );
        let test_agent = agent_item_at("test", std::path::PathBuf::from("/src/agents/test.md"));
        let siblings = vec![item.clone(), test_agent];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "valid requires entry must not error: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_typo_entry_is_bad_reference() {
        // spec: DEP-6
        // A `requires` entry naming a non-existent sibling is a BadReference.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-typo-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:nonexistent".to_string()],
        );
        let siblings = vec![item.clone()]; // no "nonexistent" sibling

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { ref referent, .. }
                if referent.contains("agent:nonexistent")),
            "typo requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_source_qualified_entry_is_bad_reference() {
        // spec: DEP-6
        // A source-qualified `owner/repo#name` entry in `requires` is rejected as
        // a BadReference because `requires` is intra-source only (DEP-5).
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-cross-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["owner/repo#agent:test".to_string()],
        );
        let test_agent = agent_item_at("test", std::path::PathBuf::from("/src/agents/test.md"));
        let siblings = vec![item.clone(), test_agent];

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { .. }),
            "source-qualified requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_ambiguous_bare_name_is_bad_reference() {
        // spec: DEP-6
        // A bare `name` that matches siblings of two different kinds and no kind
        // qualifier is supplied is ambiguous and must be a BadReference.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-ambig-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["shared".to_string()], // bare name matches agent:shared AND rule:shared
        );
        let agent = CatalogItem {
            kind: ItemKind::Agent,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/agents/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };
        let rule = CatalogItem {
            kind: ItemKind::Rule,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/rules/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };
        let siblings = vec![item.clone(), agent, rule];

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { ref referent, .. }
                if referent.contains("shared")),
            "ambiguous bare-name requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_kind_qualified_among_two_same_name_siblings_is_accepted() {
        // spec: DEP-5 DEP-6
        // The other side of the ambiguity boundary: when two siblings share a
        // bare name across kinds, a `kind:name` qualifier resolves to exactly one
        // and MUST pass validation (it is not falsely flagged ambiguous). This
        // pins that the `matches.len() > 1 && r.kind.is_none()` guard does NOT
        // fire once the kind narrows the candidate set to one.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-kindok-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        // `agent:shared` uniquely picks the agent, even though a rule:shared also
        // exists; the bare name alone would be ambiguous.
        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:shared".to_string()],
        );
        let agent = CatalogItem {
            kind: ItemKind::Agent,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/agents/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };
        let rule = CatalogItem {
            kind: ItemKind::Rule,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/rules/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };
        let siblings = vec![item.clone(), agent, rule];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "a kind-qualified ref that uniquely matches one of two same-name \
             siblings must pass validation, not be flagged ambiguous: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_self_reference_resolves_and_is_accepted() {
        // spec: DEP-6
        // An item whose `requires` names its own bare name resolves to itself (it
        // is a sibling of itself in the passed list) and must NOT error: the
        // validation only rejects zero matches or an ambiguous bare name, and a
        // self-reference is a single, unambiguous match. (The pure resolver in
        // deps.rs separately drops the trivial self-edge.)
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-self-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "solo",
            std::path::PathBuf::from("/src/skills/solo"),
            vec!["skill:solo".to_string()],
        );
        let siblings = vec![item.clone()];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "a self-requires must resolve to the item itself and not error: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    // ---- NS-57 / TOOL-20: `expand:` opt-in token expansion -----------------

    /// A skill item at `path` (a fake source path) that opts `expand` files into
    /// token expansion.
    fn skill_item_expand(name: &str, path: std::path::PathBuf, expand: Vec<String>) -> CatalogItem {
        let mut item = skill_item_at(name, path, Vec::new());
        item.expand = expand;
        item
    }

    #[test]
    fn expand_listed_non_markdown_file_expands_with_absolute_path() {
        // spec: NS-57 TOOL-20
        // A file named in `expand:` is expanded like markdown even though it is
        // not markdown, and its path tokens render as an ABSOLUTE store path,
        // while a markdown sibling keeps the TOOL-16 `~` form. Uses a store root
        // under home so the two renderings are distinguishable.
        let home = dirs::home_dir().expect("home dir for the tilde-vs-absolute check");
        let store_root = home.join("mind-expand-store");
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-abs-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(staging.join("resources")).unwrap();
        std::fs::write(staging.join("SKILL.md"), "see {{self}}/x\n").unwrap();
        std::fs::write(staging.join("resources/pr.py"), "p = \"{{self}}/x\"\n").unwrap();

        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["resources/pr.py".to_string()],
        );
        let siblings = vec![item.clone()];
        expand_references(&staging, &item, &siblings, &store_root).unwrap();

        let md = std::fs::read_to_string(staging.join("SKILL.md")).unwrap();
        let py = std::fs::read_to_string(staging.join("resources/pr.py")).unwrap();
        assert!(
            md.contains("~/mind-expand-store/skill/review/x"),
            "a markdown file keeps the ~ form (TOOL-16): {md:?}"
        );
        let abs = store_root.join("skill/review/x");
        assert!(
            py.contains(&abs.to_string_lossy().into_owned()),
            "an expand-listed file renders the absolute store path (TOOL-20): {py:?}"
        );
        assert!(
            !py.contains("~/mind-expand-store"),
            "an expand-listed file must not carry the ~ form: {py:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn unlisted_non_markdown_file_is_left_literal() {
        // spec: NS-57 NS-53
        // Without an `expand:` entry, a token in a non-markdown file is left
        // exactly as written (the NS-53 default).
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-literal-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(staging.join("resources")).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hi\n").unwrap();
        std::fs::write(staging.join("resources/other.py"), "p = \"{{self}}/x\"\n").unwrap();

        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            Vec::new(),
        );
        let siblings = vec![item.clone()];
        expand_references(&staging, &item, &siblings, std::path::Path::new("/store")).unwrap();

        let py = std::fs::read_to_string(staging.join("resources/other.py")).unwrap();
        assert_eq!(
            py, "p = \"{{self}}/x\"\n",
            "an unlisted non-markdown file must be left literal (NS-53)"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn expand_entry_naming_a_missing_file_is_bad_reference() {
        // spec: NS-57
        // An `expand:` entry that names no shipped file aborts the staged install
        // as a BadReference, so a typo is caught loudly.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-miss-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hi\n").unwrap();

        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["resources/nope.py".to_string()],
        );
        let siblings = vec![item.clone()];
        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { .. }),
            "a missing expand target must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn expand_entry_escaping_the_item_is_bad_reference() {
        // spec: NS-57
        // A `..`-bearing (or absolute) `expand:` entry is refused before any file
        // is touched.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-esc-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hi\n").unwrap();

        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["../escape.py".to_string()],
        );
        let siblings = vec![item.clone()];
        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { .. }),
            "an escaping expand entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn unresolved_token_in_listed_file_is_a_hard_failure() {
        // spec: NS-57
        // A token that does not resolve is inert (left literal) in an unlisted
        // non-markdown file, but a HARD install failure once the file is listed,
        // exactly as in markdown (NS-12).
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-bad-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(staging.join("resources")).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hi\n").unwrap();
        std::fs::write(staging.join("resources/pr.py"), "p = \"{{tools:nope}}\"\n").unwrap();

        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["resources/pr.py".to_string()],
        );
        let siblings = vec![item.clone()];
        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { .. }),
            "an unresolved token in a listed file must be a hard BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    // ---- DSC-95: BadReference field sanitization -----------------------------
    //
    // `MindError::BadReference`'s Display interpolates `item`, `referent`, and
    // `in_source` verbatim (error.rs owns that -- it does no sanitizing of its
    // own by design). `item` is always safe (it comes from `CatalogItem::key()`,
    // already validated by `is_safe_item_name`, DSC-96), but `referent` and
    // `in_source` are NOT pre-validated: `referent` is built from a `{{ns:}}`
    // token's raw inner text or a raw `requires`/`expand` mind.toml entry, and
    // `in_source` is the raw source name. These tests pin that `install.rs`
    // sanitizes each at its construction site, before composing a wrapper
    // string, so a hostile source cannot smuggle an ANSI/OSC payload into the
    // error text `main.rs` prints with a bare `eprintln!`.

    /// A `{{ns:name}}` token whose inner text carries an OSC-52 (clipboard
    /// write) payload, naming a sibling that does not exist. The unresolved
    /// name comes straight from `namespace::expand`'s raw `after[..end].trim()`
    /// (namespace.rs enforces no character class on it), so this is the exact
    /// vector M3 describes: an ordinary `mind learn` of a hostile repo could
    /// otherwise write the terminal's clipboard or repaint the screen through
    /// the resulting error message.
    #[test]
    fn hostile_ns_token_referent_is_sanitized_in_bad_reference() {
        // spec: DSC-95
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-ns-hostile-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        // OSC 52 clipboard-write sequence (ESC ] 52 ; c ; <base64> BEL), naming a
        // sibling ("evil") that does not exist in this source.
        let payload = "\x1b]52;c;UEFZTE9BRA==\x07evil";
        std::fs::write(
            staging.join("SKILL.md"),
            format!("# hello\n{{{{ns:{payload}}}}}\n"),
        )
        .unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            Vec::new(),
        );
        let siblings = vec![item.clone()]; // no "evil..." sibling

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        let crate::error::MindError::BadReference { referent, .. } = &err else {
            panic!("expected a BadReference, got {err:?}");
        };
        assert!(
            !referent.contains('\x1b') && !referent.contains('\u{07}'),
            "the referent must not carry the raw ESC/BEL bytes of the OSC \
             payload: {referent:?}"
        );
        // Still actionable: the sibling name that failed to resolve survives
        // sanitizing (it sits in a run of plain letters).
        assert!(
            referent.contains("evil"),
            "the referent must still name enough of the token to be \
             actionable: {referent:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    /// A `requires:` entry carrying a raw ANSI escape (not merely a typo'd
    /// name) must not reach `BadReference.referent` unsanitized either -- the
    /// same construction-site discipline as the `{{ns:}}` case above, but for
    /// the `bad_requires` closure.
    #[test]
    fn hostile_requires_entry_referent_is_sanitized_in_bad_reference() {
        // spec: DSC-95
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-requires-hostile-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let hostile_entry = "agent:nonexistent\x1b[31mRED\x1b[0m";
        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec![hostile_entry.to_string()],
        );
        let siblings = vec![item.clone()]; // no matching sibling

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        let crate::error::MindError::BadReference { referent, .. } = &err else {
            panic!("expected a BadReference, got {err:?}");
        };
        assert!(
            !referent.contains('\x1b'),
            "a hostile requires entry must not leak a raw ESC byte into the \
             referent: {referent:?}"
        );
        assert!(
            referent.contains("agent:nonexistent") && referent.contains("RED"),
            "the referent must still name the entry: {referent:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    /// Same discipline for `expand:` entries (the `bad_expand` closure), on
    /// both the unsafe-path and the missing-file branches.
    #[test]
    fn hostile_expand_entry_referent_is_sanitized_in_bad_reference() {
        // spec: DSC-95
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-expand-hostile-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hi\n").unwrap();

        let hostile_entry = "resources/missing\x1b[31mRED\x1b[0m.py";
        let item = skill_item_expand(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec![hostile_entry.to_string()],
        );
        let siblings = vec![item.clone()];
        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        let crate::error::MindError::BadReference { referent, .. } = &err else {
            panic!("expected a BadReference, got {err:?}");
        };
        assert!(
            !referent.contains('\x1b'),
            "a hostile expand entry must not leak a raw ESC byte into the \
             referent: {referent:?}"
        );
        assert!(
            referent.contains("resources/missing") && referent.contains("RED"),
            "the referent must still name the entry: {referent:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    /// `in_source` is the raw source name (for a local-path meld, a directory
    /// name), which is just as unvalidated as `referent`. This pins it is
    /// sanitized at the same `bad_ref` construction site.
    #[test]
    fn hostile_source_name_is_sanitized_as_in_source_in_bad_reference() {
        // spec: DSC-95
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-in-source-hostile-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let mut item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:nonexistent".to_string()],
        );
        item.source = "local\x1b[31m/test/repo\x1b[0m".to_string();
        let siblings = vec![item.clone()];

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        let crate::error::MindError::BadReference { in_source, .. } = &err else {
            panic!("expected a BadReference, got {err:?}");
        };
        assert!(
            !in_source.contains('\x1b'),
            "in_source must not leak a raw ESC byte from the source name: \
             {in_source:?}"
        );
        assert!(
            in_source.contains("local") && in_source.contains("test/repo"),
            "in_source must still name the source: {in_source:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    // ---- LIFE-43: forced-install transactional stash/restore ---------------

    /// `maybe_stash_foreign` moves a foreign regular file to the stash (returning
    /// true) and leaves an absent path or a mind-owned symlink untouched (false).
    /// Renaming the stash back to the original path recovers the file intact.
    #[cfg(unix)]
    #[test]
    fn maybe_stash_foreign_moves_foreign_file_and_restores_correctly() {
        // spec: LIFE-43
        let n = N.fetch_add(1, Ordering::SeqCst);
        let base =
            std::env::temp_dir().join(format!("mind-stash-helper-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let store_root = base.join("store");
        let link = base.join("link-target.md");
        let stash0 = base.join("stash").join("0");

        // Case 1: absent path -> no stash, returns false.
        let got = maybe_stash_foreign(&store_root, &link, &stash0).unwrap();
        assert!(!got, "absent link must not be stashed (LIFE-43)");
        assert!(
            !stash0.exists(),
            "no stash must be created for an absent link"
        );

        // Case 2: foreign regular file -> stashed, returns true.
        let foreign_content = b"original foreign content";
        std::fs::write(&link, foreign_content).unwrap();
        let got = maybe_stash_foreign(&store_root, &link, &stash0).unwrap();
        assert!(got, "foreign file must be stashed (LIFE-43)");
        assert!(!link.exists(), "original path must be vacated after stash");
        assert!(stash0.exists(), "stash file must exist");
        assert_eq!(
            std::fs::read(&stash0).unwrap(),
            foreign_content,
            "stash must preserve original content"
        );

        // Simulate rollback: rename stash back to original location.
        rename(&stash0, &link).unwrap();
        assert!(link.exists(), "restored path must exist");
        assert_eq!(
            std::fs::read(&link).unwrap(),
            foreign_content,
            "restored file must have original content (LIFE-43)"
        );

        // Case 3: mind's own symlink -> not stashed, returns false.
        std::fs::create_dir_all(&store_root).unwrap();
        let store_file = store_root.join("agent").join("myagent");
        std::fs::create_dir_all(store_file.parent().unwrap()).unwrap();
        std::fs::write(&store_file, b"mind managed").unwrap();
        std::fs::remove_file(&link).unwrap();
        std::os::unix::fs::symlink(&store_file, &link).unwrap();

        let stash1 = base.join("stash").join("1");
        let got = maybe_stash_foreign(&store_root, &link, &stash1).unwrap();
        assert!(!got, "mind's own symlink must not be stashed (LIFE-43)");
        assert!(!stash1.exists(), "no stash for mind's own symlink");
        // Symlink is untouched.
        assert!(std::fs::symlink_metadata(&link).is_ok());

        let _ = std::fs::remove_dir_all(&base);
    }

    /// A forced install that clobbers a foreign file at the first link target
    /// but fails on a later link must leave the original foreign file restored
    /// and the store copy rolled back (LIFE-43, LIFE-4).
    ///
    /// Two lobes are wired via config.toml: the first is a valid directory
    /// containing a pre-existing foreign file; the second has a regular file as
    /// its parent component, so `mkdir_p` inside `ensure_link` fails with ENOTDIR.
    #[cfg(unix)]
    #[test]
    fn force_install_rollback_restores_stashed_foreign_target() {
        // spec: LIFE-43
        let n = N.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-life43-e2e-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let mind_home = base.join("mind");
        let lobe1 = base.join("lobe1");
        // A regular file: using a subdirectory of it as a lobe causes ENOTDIR.
        let blocker = base.join("not-a-dir");

        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&lobe1).unwrap();
        std::fs::write(&blocker, b"i-am-a-regular-file").unwrap();

        let lobe2 = blocker.join("lobe2");

        // Config with two lobes; no env var mutation needed.
        let cfg = format!(
            "lobes = [\"{}\", \"{}\"]\n",
            lobe1.to_str().unwrap(),
            lobe2.to_str().unwrap(),
        );
        std::fs::write(mind_home.join("config.toml"), cfg.as_bytes()).unwrap();

        let paths = Paths {
            mind_home: mind_home.clone(),
            claude_home: lobe1.clone(),
        };

        // Place a foreign regular file at lobe1's agent link location.
        let agents_dir = lobe1.join("agents");
        std::fs::create_dir_all(&agents_dir).unwrap();
        let foreign_path = agents_dir.join("myagent.md");
        let foreign_content = b"foreign content - must survive the rollback";
        std::fs::write(&foreign_path, foreign_content).unwrap();

        // Source file for the catalog item.
        let src_file = base.join("myagent.md");
        std::fs::write(&src_file, b"# My Agent\n").unwrap();

        let item = CatalogItem {
            kind: ItemKind::Agent,
            name: "myagent".to_string(),
            source: "local/test".to_string(),
            prefix: None,
            path: src_file,
            description: None,
            link_rel: None, // defaults to agents/myagent.md under each lobe
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };

        // force=true: lobe1's link is stashed then overwritten with a symlink;
        // lobe2's link fails (mkdir_p into a regular file is ENOTDIR); rollback
        // must restore the stash to lobe1's link path.
        let result = install(
            &paths,
            &item,
            "abc",
            std::slice::from_ref(&item),
            true,
            false,
        );

        assert!(
            result.is_err(),
            "install must fail when a later link cannot be created: {result:?}"
        );

        // Foreign file must be restored at its original path (LIFE-43).
        let meta = std::fs::symlink_metadata(&foreign_path)
            .expect("foreign file must exist at original path after rollback (LIFE-43)");
        assert!(
            !meta.file_type().is_symlink(),
            "restored path must be a regular file, not a symlink (LIFE-43)"
        );
        assert_eq!(
            std::fs::read(&foreign_path).unwrap(),
            foreign_content,
            "restored file must have original content (LIFE-43)"
        );

        // Store copy must be absent (LIFE-4 rollback).
        let store_path = mind_home.join("store").join("agent").join("myagent");
        assert!(
            !store_path.exists(),
            "store copy must be absent after rollback: {store_path:?}"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    // ---- LIFE-44: uninstall path confinement checks --------------------------

    /// The bug this fix closes: canonicalizing a recorded link straight
    /// through the symlink it names resolves to the store target, which is
    /// never under an agent home, making `is_confined_under_any` permanently
    /// false for any link that still exists on disk. Canonicalizing only the
    /// link's PARENT directory (this crate's `canonicalize_link_parent`) keeps
    /// the comparison anchored at the lobe location instead.
    #[cfg(unix)]
    #[test]
    fn canonicalize_link_parent_resolves_the_parent_not_the_symlink_target() {
        // spec: LIFE-44
        let n = N.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-life44-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let lobe = base.join("lobe");
        let store = base.join("mind/store/skill/x");
        std::fs::create_dir_all(&lobe).unwrap();
        std::fs::create_dir_all(&store).unwrap();
        std::fs::write(store.join("SKILL.md"), b"x").unwrap();

        let link = lobe.join("x");
        std::os::unix::fs::symlink(&store, &link).unwrap();

        let canon_lobe = lobe.canonicalize().unwrap();

        // The FIX: canonicalizing the link's parent keeps the result under
        // the lobe, with the link's own file name preserved as the last
        // component.
        let canon = canonicalize_link_parent(&link);
        assert!(
            canon.starts_with(&canon_lobe),
            "canonicalize_link_parent must stay under the lobe (the link's \
             parent), not follow the symlink into the store: {canon:?}"
        );
        assert_eq!(canon.file_name(), Some(std::ffi::OsStr::new("x")));

        // Sanity/contrast: the OLD, buggy approach -- canonicalizing the link
        // itself -- resolves through the symlink into the store instead, so it
        // is NOT under the lobe. This pins that the bug this test guards
        // against is real, not a strawman.
        let old_buggy_approach = link.canonicalize().unwrap();
        assert!(
            !old_buggy_approach.starts_with(&canon_lobe),
            "sanity: canonicalizing straight through the symlink must NOT stay \
             under the lobe -- this is the LIFE-44 bug the fix avoids: {old_buggy_approach:?}"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn is_confined_under_accepts_child_paths() {
        // spec: LIFE-44
        let root = std::path::Path::new("/home/user/.mind/store");
        assert!(
            is_confined_under(
                std::path::Path::new("/home/user/.mind/store/skill/review"),
                root
            ),
            "a child of the root must be confined"
        );
        assert!(
            is_confined_under(root, root),
            "the root itself must be accepted"
        );
    }

    #[test]
    fn is_confined_under_rejects_parent_dir_components() {
        // spec: LIFE-44 -- a `..` component in the recorded path is a violation
        // regardless of where the path appears to start with the root.
        let root = std::path::Path::new("/home/user/.mind/store");
        // Lexically starts with root but contains `..` -> must be rejected.
        assert!(
            !is_confined_under(
                std::path::Path::new("/home/user/.mind/store/skill/../../../etc/passwd"),
                root
            ),
            "path with .. must be rejected even if it starts with the root"
        );
        // A plain `..` relative path must be rejected too.
        assert!(
            !is_confined_under(std::path::Path::new("../outside"), root),
            "relative path with leading .. must be rejected"
        );
    }

    #[test]
    fn is_confined_under_rejects_sibling_paths() {
        // spec: LIFE-44
        let root = std::path::Path::new("/home/user/.mind/store");
        assert!(
            !is_confined_under(std::path::Path::new("/home/user/.claude/skills/x"), root),
            "a path outside the root must be rejected"
        );
        // A path that is a proper prefix of the root in string terms but not a
        // child in path-component terms must also be rejected.
        assert!(
            !is_confined_under(std::path::Path::new("/home/user/.mind"), root),
            "a parent of the root must be rejected"
        );
    }

    /// A source tree containing a symlink (e.g. pointing to a secret outside
    /// the tree) must be rejected by `copy_recursive` with a clear error that
    /// names the offending path (LIFE-42). The caller (`install`) discards the
    /// staging directory on any error, so the partial copy is cleaned up there.
    #[cfg(unix)]
    #[test]
    fn copy_recursive_rejects_symlink_in_source_tree() {
        // spec: LIFE-42
        let n = N.fetch_add(1, Ordering::SeqCst);
        let src = std::env::temp_dir().join(format!("mind-cplink-src-{}-{n}", std::process::id()));
        let dst = std::env::temp_dir().join(format!("mind-cplink-dst-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("ok.txt"), b"normal").unwrap();
        // A symlink to /etc/passwd simulates a crafted source attempting to
        // exfiltrate a secret file outside the item tree.
        std::os::unix::fs::symlink("/etc/passwd", src.join("evil")).unwrap();

        let result = copy_recursive(&src, &dst);

        assert!(
            result.is_err(),
            "copy_recursive must reject a source tree containing a symlink"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("symlink"),
            "error message must mention 'symlink': {msg}"
        );
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
    }

    /// A source tree nested deeper than the LIFE-52 cap fails with a
    /// structured error instead of overflowing the stack.
    #[test]
    fn copy_recursive_depth_caps_a_pathological_tree() {
        // spec: LIFE-52
        let n = N.fetch_add(1, Ordering::SeqCst);
        let src = std::env::temp_dir().join(format!("mind-cpdeep-src-{}-{n}", std::process::id()));
        let dst = std::env::temp_dir().join(format!("mind-cpdeep-dst-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let mut deep = src.clone();
        for _ in 0..(MAX_ITEM_TREE_DEPTH + 2) {
            deep.push("d");
        }
        std::fs::create_dir_all(&deep).unwrap();

        let result = copy_recursive(&src, &dst);

        assert!(
            result.is_err(),
            "copy_recursive must refuse a tree deeper than the cap"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("nested directories"),
            "error message must name the depth cap: {msg}"
        );
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
    }

    // ---- IGN-10: copy/hash agreement on symlink classification ---------------

    /// A symlink pointing at a directory is classified with `symlink_metadata`
    /// (no-follow), same as the hash walk, so it is never a directory to the
    /// ignore matcher. A no-slash pattern matches an entry regardless of
    /// `is_dir`, so it excludes the symlink from both the copy and the hash
    /// identically, and the excluded entry contributes nothing to either.
    #[cfg(unix)]
    #[test]
    fn symlink_to_dir_ignored_by_no_slash_pattern_is_skipped_by_copy_and_hash() {
        // spec: IGN-10 LIFE-42
        let n = N.fetch_add(1, Ordering::SeqCst);
        let src = std::env::temp_dir().join(format!(
            "mind-symdir-noslash-src-{}-{n}",
            std::process::id()
        ));
        let dst = std::env::temp_dir().join(format!(
            "mind-symdir-noslash-dst-{}-{n}",
            std::process::id()
        ));
        let target = std::env::temp_dir().join(format!(
            "mind-symdir-noslash-tgt-{}-{n}",
            std::process::id()
        ));
        let reference = std::env::temp_dir().join(format!(
            "mind-symdir-noslash-ref-{}-{n}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
        let _ = std::fs::remove_dir_all(&reference);
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("keep.txt"), b"kept").unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(target.join("inner.txt"), b"outside the item").unwrap();
        std::os::unix::fs::symlink(&target, src.join("scratch")).unwrap();

        // Reference tree: what the item looks like with "scratch" absent
        // entirely, i.e. what the hash must equal if "scratch" contributes
        // nothing.
        std::fs::create_dir_all(&reference).unwrap();
        std::fs::write(reference.join("keep.txt"), b"kept").unwrap();

        let ignore = IgnoreSet::new(&["scratch".to_string()], "skill:t").unwrap();

        copy_recursive_ignoring(&src, &dst, &ignore)
            .expect("a no-slash pattern excludes the symlink before LIFE-42's check ever sees it");
        assert!(
            std::fs::symlink_metadata(dst.join("scratch")).is_err(),
            "the ignored symlink must not be copied"
        );
        assert!(dst.join("keep.txt").is_file());

        let hash_with_scratch =
            hash_path_ignoring(&src, &ignore).expect("hash walk must also skip the symlink");
        let hash_without_scratch = hash_path_ignoring(&reference, &IgnoreSet::default())
            .expect("reference tree hashes cleanly");
        assert_eq!(
            hash_with_scratch, hash_without_scratch,
            "an ignored symlink must contribute nothing to the hash (IGN-10)"
        );

        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
        let _ = std::fs::remove_dir_all(&reference);
    }

    /// A directory-only ignore rule does NOT match a symlink pointing at a
    /// directory, because `is_dir` comes from `symlink_metadata` (no-follow)
    /// rather than a following `is_dir()`. So the entry is never skipped by a
    /// `name/` rule (nor by any of the four built-ins) and instead reaches
    /// LIFE-42's symlink rejection, hard-failing the install exactly as it
    /// would without any ignore rule in play.
    #[cfg(unix)]
    #[test]
    fn symlink_to_dir_not_matched_by_dir_only_pattern_hard_fails_life42() {
        // spec: IGN-10 LIFE-42
        let n = N.fetch_add(1, Ordering::SeqCst);
        let src =
            std::env::temp_dir().join(format!("mind-symdir-slash-src-{}-{n}", std::process::id()));
        let dst =
            std::env::temp_dir().join(format!("mind-symdir-slash-dst-{}-{n}", std::process::id()));
        let target =
            std::env::temp_dir().join(format!("mind-symdir-slash-tgt-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("keep.txt"), b"kept").unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::os::unix::fs::symlink(&target, src.join("scratch")).unwrap();

        let ignore = IgnoreSet::new(&["scratch/".to_string()], "skill:t").unwrap();

        let result = copy_recursive_ignoring(&src, &dst, &ignore);
        assert!(
            result.is_err(),
            "a directory-only rule must not exclude a symlink named `scratch`; the \
             install must hard-fail on it via LIFE-42 rather than silently install it"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("symlink"),
            "the failure must be the LIFE-42 symlink rejection: {msg}"
        );

        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
    }

    /// For a tree mixing plain files, a nested directory, and a symlink
    /// excluded by an ignore rule, the copy and the hash walk must agree on
    /// exactly which entries survive: hashing the copied output (no further
    /// ignores needed, since the excluded entry was never copied) must equal
    /// hashing the source tree through the real ignore set.
    #[cfg(unix)]
    #[test]
    fn copy_and_hash_agree_on_file_set_for_mixed_tree() {
        // spec: IGN-10
        let n = N.fetch_add(1, Ordering::SeqCst);
        let src = std::env::temp_dir().join(format!("mind-mixed-src-{}-{n}", std::process::id()));
        let dst = std::env::temp_dir().join(format!("mind-mixed-dst-{}-{n}", std::process::id()));
        let target =
            std::env::temp_dir().join(format!("mind-mixed-tgt-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("top.txt"), b"top level").unwrap();
        std::fs::create_dir_all(src.join("sub")).unwrap();
        std::fs::write(src.join("sub/nested.txt"), b"nested content").unwrap();
        std::fs::create_dir_all(&target).unwrap();
        std::fs::write(target.join("outside.txt"), b"must never appear").unwrap();
        std::os::unix::fs::symlink(&target, src.join("link")).unwrap();

        // "link" (no trailing slash) matches the symlink whether or not it is
        // classified as a directory, so both walks must skip it identically.
        let ignore = IgnoreSet::new(&["link".to_string()], "skill:t").unwrap();

        copy_recursive_ignoring(&src, &dst, &ignore)
            .expect("the symlink is ignored, so it never reaches the LIFE-42 check");
        assert!(
            std::fs::symlink_metadata(dst.join("link")).is_err(),
            "the ignored symlink must not be copied"
        );
        assert!(dst.join("top.txt").is_file());
        assert!(dst.join("sub").join("nested.txt").is_file());

        let hash_src = hash_path_ignoring(&src, &ignore)
            .expect("source hashes cleanly with the symlink excluded");
        let hash_dst = hash_path_ignoring(&dst, &IgnoreSet::default())
            .expect("copied output has no symlink left to trip over");
        assert_eq!(
            hash_src, hash_dst,
            "the copy and the hash walk must agree on the resulting file set (IGN-10)"
        );

        let _ = std::fs::remove_dir_all(&src);
        let _ = std::fs::remove_dir_all(&dst);
        let _ = std::fs::remove_dir_all(&target);
    }
}