mind-cli 0.21.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
//! The on-disk layout for `mind`.
//!
//! ```text
//! ~/.mind/
//!   sources.json                 registry of melded sources (see source.rs)
//!   manifest.json                installed-item manifest (see manifest.rs)
//!   sources/<host>/<owner>/<repo> bare-ish clones of each melded repo
//!   store/<kind>/<name>/          the installed copy of each item
//!
//! <agent home>/                     (one or more; default ~/.claude)
//!   skills/<name>  -> symlink into store/skill/<name>
//!   agents/<name>.md -> symlink into store/agent/<name>
//!   rules/<name>.md  -> symlink into store/rule/<name>
//! ```
//!
//! Items are linked into every configured agent home (see [`Paths::agent_homes`]).
//! Roots are overridable via environment variables so the test harness can point
//! them at temp dirs: `MIND_HOME`, `CLAUDE_HOME`, `MIND_AGENT_HOMES`.
//!
//! A lobe is the parent of `skills/` / `agents/` / `rules/`; the default is
//! `~/.claude`, but a lobe may be any harness home (Gemini, Codex, Windsurf, Antigravity)
//! because the skill/agent layouts double as the cross-tool conventions
//! (spec/harness-lobes.md). A lobe may carry a `kinds` filter (HARN-1): only
//! items of a listed kind link into it. The [`PRESETS`] table maps a harness name
//! to its lobe path and kinds (HARN-4), and [`detect_homes`] reports which preset
//! dirs exist under the detection base (HARN-5), consulting `MIND_DETECT_HOME`
//! (else the home dir) so detection stays hermetic without mutating process HOME.

use std::path::{Path, PathBuf};

use crate::config::Config;
use crate::error::{ItemKind, MindError, Result};
use crate::policy::Policy;

/// A resolved agent home: an absolute path plus the kinds it admits (HARN-1).
/// `kinds == None` is "no filter": it admits every kind, the historical behavior
/// (so a tool with an explicit `link`, TOOL-4, still surfaces). `Some(list)`
/// admits only the listed kinds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lobe {
    pub path: PathBuf,
    pub kinds: Option<Vec<ItemKind>>,
}

impl Lobe {
    /// A lobe with no kinds filter (admits all kinds).
    pub fn all_kinds(path: PathBuf) -> Self {
        Lobe { path, kinds: None }
    }

    /// Whether this lobe accepts an item of `kind` (HARN-1). With no filter every
    /// kind is admitted (preserving the pre-feature behavior, including a tool
    /// with an explicit link); with a filter, only the listed kinds.
    pub fn admits(&self, kind: ItemKind) -> bool {
        match &self.kinds {
            None => true,
            Some(kinds) => kinds.contains(&kind),
        }
    }

    /// Whether this lobe's parent directory exists (STO-56). Returns `true` when
    /// the lobe has no parent (e.g. a root path) so it is treated as always
    /// reachable. A global home like `~/.claude` always has a parent (`~`) that
    /// exists; a project lobe like `<project>/.windsurf` requires `<project>` to
    /// be present.
    ///
    /// This gate must NOT be applied inside `agent_homes()` -- uninstall
    /// confinement and `~/.claude` auto-create-on-link both depend on the full
    /// list. Apply it only at write sites (install fan-out, `link_into_new_lobes`,
    /// `relink`).
    // spec: STO-56
    pub(crate) fn reachable(&self) -> bool {
        self.path.parent().is_none_or(|p| p.exists())
    }
}

/// Whether a lobe is global (linked under a harness home directory) or
/// project-scoped (linked under a per-project subdirectory).
///
/// Global lobes are auto-addable by `config lobes detect` when their marker is
/// found. Project-scoped lobes require an explicit project directory; detect
/// surfaces them so the caller can print guidance, but does not auto-add them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    /// The lobe lives under a user-wide home directory (e.g. `~/.gemini/config`).
    Global,
    /// The lobe lives under a per-project directory (e.g. `<project>/.windsurf`).
    Project,
}

/// A known harness preset (HARN-4): the lobe path (relative to the detection
/// base / home) and the kinds it admits. `marker_rel` is the on-disk signal
/// [`detect_homes`] checks to decide the harness is installed.
#[derive(Debug)]
pub struct Preset {
    /// The preset name used on the CLI (`--preset <name>`).
    pub name: &'static str,
    /// The lobe subdirectory, relative to the base directory (e.g. `.gemini/config`
    /// for Gemini). For a `Global` preset, the base is `~`; for a `Project` preset,
    /// the base is the project directory supplied by the caller.
    pub rel_path: &'static str,
    /// The kinds this preset's lobe admits.
    pub kinds: &'static [ItemKind],
    /// The directory whose presence signals this harness is installed, relative
    /// to the detection base (e.g. `.gemini` for Gemini, `.codex` for Codex,
    /// `.codeium/windsurf` for Windsurf).
    pub marker_rel: &'static str,
    /// Whether this preset is global (linked under a shared harness home) or
    /// project-scoped (linked under a per-project directory).
    pub scope: Scope,
}

/// The harness presets (HARN-4). Detection signals (HARN-5):
/// - `gemini`: `~/.gemini` exists (Gemini CLI / Antigravity shared home; lobe is `~/.gemini/config`).
/// - `codex`: `~/.codex` exists (Codex CLI's home; it reads `~/.agents`).
/// - `universal`: `~/.agents` exists (the vendor-neutral alias dir itself).
/// - `windsurf`: `~/.codeium/windsurf` exists (Windsurf IDE's real global config home;
///   lobe is `<project>/.windsurf`, project-scoped because Windsurf discovers skills
///   only at `<project>/.windsurf/skills/<name>/SKILL.md`, not from a global dir).
pub const PRESETS: &[Preset] = &[
    Preset {
        name: "gemini",
        rel_path: ".gemini/config",
        kinds: &[ItemKind::Skill],
        marker_rel: ".gemini",
        scope: Scope::Global,
    },
    Preset {
        name: "codex",
        rel_path: ".agents",
        kinds: &[ItemKind::Skill],
        marker_rel: ".codex",
        scope: Scope::Global,
    },
    Preset {
        name: "universal",
        rel_path: ".agents",
        kinds: &[ItemKind::Skill],
        marker_rel: ".agents",
        scope: Scope::Global,
    },
    Preset {
        name: "windsurf",
        rel_path: ".windsurf",
        kinds: &[ItemKind::Skill],
        // The real Windsurf global config home is ~/.codeium/windsurf, not ~/.windsurf.
        // Detection checks for the real global home so it fires when Windsurf is installed,
        // not on an arbitrary ~/.windsurf dir. (spec: STO-56)
        marker_rel: ".codeium/windsurf",
        scope: Scope::Project,
    },
];

/// Look up a preset by name, erroring with [`MindError::UnknownPreset`] on a bad
/// name (HARN-4).
pub fn lookup_preset(name: &str) -> Result<&'static Preset> {
    PRESETS
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| MindError::UnknownPreset {
            name: name.to_string(),
        })
}

/// Resolved filesystem roots for a `mind` invocation.
#[derive(Debug, Clone)]
pub struct Paths {
    /// `~/.mind` (or `$MIND_HOME`).
    pub mind_home: PathBuf,
    /// `~/.claude` (or `$CLAUDE_HOME`).
    pub claude_home: PathBuf,
}

impl Paths {
    /// Resolve roots from the environment, falling back to the home directory.
    pub fn resolve() -> Result<Self> {
        let mind_home = match std::env::var_os("MIND_HOME") {
            Some(p) => PathBuf::from(p),
            None => home()?.join(".mind"),
        };
        // spec: CLI-170 - MIND_DEFAULT_LOBE takes precedence over CLAUDE_HOME.
        let claude_home = match std::env::var_os("MIND_DEFAULT_LOBE")
            .or_else(|| std::env::var_os("CLAUDE_HOME"))
        {
            Some(p) => PathBuf::from(p),
            None => home()?.join(".claude"),
        };
        Ok(Self {
            mind_home,
            claude_home,
        })
    }

    /// Path to the global advisory lock file.
    // spec: STO-40
    pub fn lock_file(&self) -> PathBuf {
        self.mind_home.join(".lock")
    }

    pub fn sources_file(&self) -> PathBuf {
        self.mind_home.join("sources.json")
    }

    pub fn manifest_file(&self) -> PathBuf {
        self.mind_home.join("manifest.json")
    }

    /// The user config file (`config.toml`) under the mind home.
    pub fn config_file(&self) -> PathBuf {
        self.mind_home.join("config.toml")
    }

    /// Root under which melded repos are cloned.
    pub fn sources_dir(&self) -> PathBuf {
        self.mind_home.join("sources")
    }

    /// Root under which installed item copies live.
    pub fn store_dir(&self) -> PathBuf {
        self.mind_home.join("store")
    }

    /// The store location for one installed item.
    pub fn store_item(&self, kind: ItemKind, name: &str) -> PathBuf {
        self.mind_home.join(self.store_rel(kind, name))
    }

    /// The store location for one item, relative to `mind_home` (recorded in the
    /// manifest so uninstall removes exactly what was installed).
    pub fn store_rel(&self, kind: ItemKind, name: &str) -> String {
        format!("store/{}/{}", kind.as_str(), name)
    }

    /// Scratch root for transactional installs (staging + backup).
    pub fn tmp_dir(&self) -> PathBuf {
        self.mind_home.join(".tmp")
    }

    /// Where a new item copy is built before it is swapped into the store.
    pub fn staging_path(&self, kind: ItemKind, name: &str) -> PathBuf {
        self.tmp_dir()
            .join("staging")
            .join(kind.as_str())
            .join(name)
    }

    /// Where the previous store copy is held during a swap, for rollback.
    pub fn backup_path(&self, kind: ItemKind, name: &str) -> PathBuf {
        self.tmp_dir().join("backup").join(kind.as_str()).join(name)
    }

    /// The default link target for an item, relative to an agent home, or `None`
    /// for a kind that is store-only by default (a `tool`: it carries no symlink
    /// and the harness does not discover it; items reach it by path token).
    pub fn default_link_rel(&self, kind: ItemKind, name: &str) -> Option<String> {
        let dir = kind.dir();
        match kind {
            ItemKind::Skill => Some(format!("{dir}/{name}")),
            ItemKind::Agent | ItemKind::Rule => Some(format!("{dir}/{name}.md")),
            ItemKind::Tool => None,
        }
    }

    /// The agent homes items are linked into. Without a managed policy this is,
    /// in order: `$MIND_AGENT_HOMES` (a `:`-separated path list), else `lobes`
    /// from `~/.mind/config.toml`, else `[claude_home]`.
    ///
    /// When a managed policy is in effect:
    /// - `[lobes].lock = true` (POL-40): the effective homes are exactly
    ///   `[lobes].targets`; `$MIND_AGENT_HOMES` and config `lobes` are ignored.
    ///   An empty `targets` under a lock falls back to the default (`claude_home`).
    /// - `[lobes].lock = false` (POL-41): `[lobes].targets` is a base set that is
    ///   unioned with the user's normally-resolved homes (deduped; targets first).
    ///
    /// A leading `~` is expanded, and a relative path is resolved to absolute
    /// against the current directory, so the link paths recorded in the manifest
    /// never depend on the working directory at a later uninstall.
    ///
    /// Each returned [`Lobe`] carries its `kinds` filter (HARN-1): config entries
    /// carry the filter they declared; `$MIND_AGENT_HOMES` entries and managed
    /// policy targets resolve to `kinds: None` (all kinds), preserving current
    /// behavior. Lobes are deduplicated by path (first-seen kinds win).
    pub fn agent_homes(&self) -> Result<Vec<Lobe>> {
        // Compute the user's normal homes (pre-policy).
        let user_homes: Vec<Lobe> = {
            let mut h: Vec<Lobe> = Vec::new();
            if let Some(raw) = std::env::var_os("MIND_AGENT_HOMES") {
                // Env-var homes are all-kinds (HARN-2): they preserve the
                // pre-feature behavior of `$MIND_AGENT_HOMES`.
                let parsed = raw
                    .to_string_lossy()
                    .split(':')
                    .filter(|p| !p.is_empty())
                    .map(|p| Ok(Lobe::all_kinds(absolute_home(p)?)))
                    .collect::<Result<Vec<_>>>()?;
                if !parsed.is_empty() {
                    h = parsed;
                }
            }
            if h.is_empty() {
                let configured = Config::load(self)?.lobes;
                if !configured.is_empty() {
                    h = configured
                        .iter()
                        .map(|e| {
                            Ok(Lobe {
                                path: absolute_home(e.path())?,
                                kinds: e.kinds().map(<[ItemKind]>::to_vec),
                            })
                        })
                        .collect::<Result<Vec<_>>>()?;
                }
            }
            if h.is_empty() {
                h = vec![Lobe::all_kinds(make_absolute(self.claude_home.clone())?)];
            }
            h
        };

        // Apply managed-policy lobe rules when a policy is in effect.
        // spec: POL-40
        // spec: POL-41
        match Policy::load()? {
            Some(policy) if policy.lobes_lock() => {
                // POL-40: locked - use exactly the policy targets, ignoring user homes.
                let targets = policy.lobes_targets();
                if targets.is_empty() {
                    // Empty targets under a lock pins the default.
                    Ok(vec![Lobe::all_kinds(make_absolute(
                        self.claude_home.clone(),
                    )?)])
                } else {
                    let resolved: Vec<Lobe> = targets
                        .iter()
                        .map(|p| Ok(Lobe::all_kinds(absolute_home(p)?)))
                        .collect::<Result<_>>()?;
                    Ok(dedup_lobes(resolved))
                }
            }
            Some(policy) => {
                // POL-41: not locked - union policy targets with user homes (targets first,
                // deduped). The whole result is deduped to collapse duplicate targets and
                // targets that equal a user home.
                // spec: POL-41
                let mut result: Vec<Lobe> = Vec::new();
                for p in policy.lobes_targets() {
                    result.push(Lobe::all_kinds(absolute_home(p)?));
                }
                for h in user_homes {
                    result.push(h);
                }
                Ok(dedup_lobes(result))
            }
            None => {
                // POL-4 inert: no policy. Dedup by path (first-seen kinds win),
                // honoring the documented contract so two same-path config lobes
                // (e.g. the codex + universal presets both at ~/.agents) collapse
                // to one, exactly as the policy branches already do.
                Ok(dedup_lobes(user_homes))
            }
        }
    }

    /// The lobe a `--preset <name>` resolves to (HARN-4): the preset's lobe
    /// path (with `~` expanded to absolute, STO-16) and its kinds filter. Errors
    /// with [`MindError::UnknownPreset`] on a bad name.
    ///
    /// For `Global` presets the base is the home directory (`~`). For `Project`
    /// presets the base is the current working directory (a project-local lobe).
    pub fn preset_lobe(name: &str) -> Result<Lobe> {
        let (lobe, _preset) = resolve_lobe(None, Some(name), None)?;
        Ok(lobe)
    }

    /// The base directory detection scans under (HARN-5): `$MIND_DETECT_HOME` if
    /// set (so tests stay hermetic without mutating process HOME), else the home
    /// directory.
    pub fn detect_base() -> Result<PathBuf> {
        match std::env::var_os("MIND_DETECT_HOME") {
            Some(p) => Ok(PathBuf::from(p)),
            None => home(),
        }
    }

    /// Report which known harness preset dirs exist under the detection base
    /// (HARN-5). A preset is reported when its marker dir exists; each entry is
    /// the preset name and the [`Lobe`] (path under the base, plus kinds) to add.
    /// Detection never mutates config on its own; the caller decides.
    pub fn detect_homes() -> Result<Vec<(&'static str, Lobe)>> {
        let base = Self::detect_base()?;
        let mut found = Vec::new();
        for preset in PRESETS {
            if base.join(preset.marker_rel).is_dir() {
                found.push((
                    preset.name,
                    Lobe {
                        path: base.join(preset.rel_path),
                        kinds: Some(preset.kinds.to_vec()),
                    },
                ));
            }
        }
        Ok(found)
    }

    /// The default lobe written into a fresh config: the `$CLAUDE_HOME` override
    /// if set, else `~/.claude`.
    pub fn default_lobe(&self) -> String {
        // spec: CLI-170 - MIND_DEFAULT_LOBE takes precedence over CLAUDE_HOME.
        match std::env::var_os("MIND_DEFAULT_LOBE").or_else(|| std::env::var_os("CLAUDE_HOME")) {
            Some(v) => v.to_string_lossy().into_owned(),
            None => "~/.claude".to_string(),
        }
    }

    /// Create `config.toml` with default values if it does not exist yet.
    pub fn ensure_config(&self) -> Result<()> {
        if !self.config_file().exists() {
            Config {
                lobes: vec![crate::config::LobeEntry::bare(self.default_lobe())],
                ..Default::default()
            }
            .save(self)?;
        }
        Ok(())
    }

    /// Create the `~/.mind` scaffolding (and a default config) if absent.
    pub fn ensure_layout(&self) -> Result<()> {
        mkdir_p(&self.mind_home)?;
        mkdir_p(&self.sources_dir())?;
        mkdir_p(&self.store_dir())?;
        self.ensure_config()?;
        Ok(())
    }

    /// Write `bytes` to `target` atomically by writing a sibling temp file and
    /// renaming it over the target. Callers see either the old file or the new
    /// file, never a partial write.
    ///
    /// The temp file is placed in the same directory as `target` (required for
    /// `rename` to be atomic within one filesystem). Named
    /// `.<filename>.tmp.<pid>` so it is identifiable on crash.
    ///
    /// Called by `source.rs`, `manifest.rs`, and `config.rs` once the
    /// mechanical shard wires them up; until then the unit tests exercise it.
    // spec: STO-43
    pub fn atomic_write(target: &std::path::Path, bytes: &[u8]) -> Result<()> {
        let dir = target
            .parent()
            .ok_or_else(|| MindError::io(target, std::io::Error::other("no parent directory")))?;
        let file_name = target
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "file".into());
        let tmp_name = format!(".{}.tmp.{}", file_name, std::process::id());
        let tmp_path = dir.join(&tmp_name);

        // Write to temp; clean up on error.
        let write_result =
            std::fs::write(&tmp_path, bytes).map_err(|e| MindError::io(&tmp_path, e));
        if let Err(e) = write_result {
            let _ = std::fs::remove_file(&tmp_path);
            return Err(e);
        }

        // Rename over the target; clean up temp on error.
        std::fs::rename(&tmp_path, target).map_err(|e| {
            let _ = std::fs::remove_file(&tmp_path);
            MindError::io(target, e)
        })
    }
}

fn home() -> Result<PathBuf> {
    dirs::home_dir().ok_or(MindError::HomeDirNotFound)
}

/// Expand a leading `~` / `~/` to the home directory; other paths pass through.
fn expand_home(path: &str) -> PathBuf {
    if path == "~" {
        return dirs::home_dir().unwrap_or_else(|| PathBuf::from(path));
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(h) = dirs::home_dir()
    {
        return h.join(rest);
    }
    PathBuf::from(path)
}

/// Expand `~` and then resolve a relative agent-home path to an absolute one.
fn absolute_home(path: &str) -> Result<PathBuf> {
    make_absolute(expand_home(path))
}

/// Resolve a path to absolute against the current directory, leaving an
/// already-absolute path unchanged. Does not touch the filesystem (no symlink
/// resolution), so it works for a home that does not exist yet.
fn make_absolute(path: PathBuf) -> Result<PathBuf> {
    if path.is_absolute() {
        return Ok(path);
    }
    let cwd = std::env::current_dir().map_err(|e| MindError::io(".", e))?;
    Ok(cwd.join(path))
}

/// Deduplicate a `Vec<Lobe>` by path, preserving first-seen order. When the same
/// path appears twice, the first-seen lobe (and its kinds) wins.
fn dedup_lobes(lobes: Vec<Lobe>) -> Vec<Lobe> {
    let mut seen = std::collections::HashSet::new();
    lobes
        .into_iter()
        .filter(|l| seen.insert(l.path.clone()))
        .collect()
}

/// Resolve a lobe from the combination of an optional base directory, an
/// optional harness preset name, and an optional relative subdirectory.
///
/// This is the single resolution entry point for `config lobes add` and the
/// planned `link-project` command. Three dispatch cases:
///
/// - **preset given** (`preset.is_some()`): subdir and kinds come from the
///   preset. `base` provides the root; when absent it defaults to `~` for a
///   [`Scope::Global`] preset or the cwd for a [`Scope::Project`] preset. The
///   resolved lobe path is `base / preset.rel_path`.
///
/// - **`subdir` given, no preset**: `base` defaults to the cwd when absent.
///   The resolved lobe path is `base / subdir`. kinds = `[Skill]`.
///
/// - **neither preset nor subdir** (bare path add): the lobe path is `base`
///   (required; if also absent, returns `MindError::LobeTargetRequired`).
///   kinds = None (all kinds).
///
/// In all cases the resolved path is made absolute (STO-16).
///
/// When `base` is explicitly given and that path does not exist, returns
/// `MindError::LobeBaseMissing` (STO-56). The home directory is not statted.
// spec: STO-16
// spec: STO-56
pub(crate) fn resolve_lobe(
    base: Option<&str>,
    preset: Option<&str>,
    subdir: Option<&str>,
) -> Result<(Lobe, Option<&'static Preset>)> {
    // Helper: check that an explicit base directory exists before using it.
    // We skip the stat when the expanded path is the home directory (always
    // present, and the caller may legitimately supply "~").
    let check_base = |base_str: &str| -> Result<PathBuf> {
        let expanded = expand_home(base_str);
        let home = dirs::home_dir();
        let is_home = home.as_deref().is_some_and(|h| expanded == h);
        if !is_home && !expanded.exists() {
            return Err(MindError::LobeBaseMissing { path: expanded });
        }
        make_absolute(expanded)
    };

    if let Some(name) = preset {
        // --- Case 1: preset given ---
        let p = lookup_preset(name)?;
        let base_path: PathBuf = match base {
            Some(b) => check_base(b)?,
            None => match p.scope {
                Scope::Global => make_absolute(home()?)?,
                Scope::Project => {
                    make_absolute(std::env::current_dir().map_err(|e| MindError::io(".", e))?)?
                }
            },
        };
        let lobe_path = make_absolute(base_path.join(p.rel_path))?;
        Ok((
            Lobe {
                path: lobe_path,
                kinds: Some(p.kinds.to_vec()),
            },
            Some(p),
        ))
    } else if let Some(rel) = subdir {
        // --- Case 2: subdir given, no preset ---
        let base_path: PathBuf = match base {
            Some(b) => check_base(b)?,
            None => make_absolute(std::env::current_dir().map_err(|e| MindError::io(".", e))?)?,
        };
        let lobe_path = make_absolute(base_path.join(rel))?;
        Ok((
            Lobe {
                path: lobe_path,
                kinds: Some(vec![ItemKind::Skill]),
            },
            None,
        ))
    } else {
        // --- Case 3: neither preset nor subdir (bare path add) ---
        match base {
            Some(b) => {
                // Stat the given base (it IS the lobe, not a container).
                let expanded = expand_home(b);
                let lobe_path = make_absolute(expanded)?;
                Ok((Lobe::all_kinds(lobe_path), None))
            }
            None => Err(MindError::LobeTargetRequired),
        }
    }
}

/// `mkdir -p` that tags failures with the offending path.
pub fn mkdir_p(path: &Path) -> Result<()> {
    std::fs::create_dir_all(path).map_err(|e| MindError::io(path, e))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU32, Ordering};

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

    /// Serialize all tests that touch process-global env vars (`MIND_POLICY_FILE`,
    /// `MIND_AGENT_HOMES`, `MIND_HOME`, `CLAUDE_HOME`).
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn absolute_home_resolves_relative_paths() {
        // spec: STO-16
        let abs = absolute_home("rellobe").unwrap();
        assert!(
            abs.is_absolute(),
            "relative lobe should become absolute: {abs:?}"
        );
        assert!(abs.ends_with("rellobe"));
        // An already-absolute path is unchanged.
        assert_eq!(
            absolute_home("/tmp/lobe").unwrap(),
            PathBuf::from("/tmp/lobe")
        );
    }

    #[test]
    fn atomic_write_replaces_target_content() {
        // spec: STO-43
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!("mind-paths-test-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("data.json");

        // Write initial content.
        std::fs::write(&target, b"old").unwrap();

        // Atomically replace with new content.
        Paths::atomic_write(&target, b"new").unwrap();
        let got = std::fs::read(&target).unwrap();
        assert_eq!(got, b"new", "target should contain the new bytes");

        // No temp file should be left behind.
        let leftover: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .collect();
        assert!(
            leftover.is_empty(),
            "temp file was not cleaned up: {leftover:?}"
        );

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

    #[test]
    fn atomic_write_creates_target_if_absent() {
        // spec: STO-43
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-paths-create-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("new.json");

        assert!(!target.exists(), "sanity: target should not exist yet");
        Paths::atomic_write(&target, b"{\"x\":1}").unwrap();
        assert!(target.exists(), "atomic_write should create the target");
        assert_eq!(std::fs::read(&target).unwrap(), b"{\"x\":1}");

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

    #[test]
    fn atomic_write_errors_and_leaves_no_temp_when_dir_is_missing() {
        // If the target's parent directory does not exist, the temp write fails.
        // atomic_write must return an Io error (not panic) and must not leave a
        // stray temp file behind (there is nowhere to leave it, but the cleanup
        // path must run without error).
        // spec: STO-43
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let missing_dir =
            std::env::temp_dir().join(format!("mind-paths-missing-{}-{n}", std::process::id()));
        // Deliberately do NOT create missing_dir.
        let target = missing_dir.join("data.json");

        let result = Paths::atomic_write(&target, b"data");
        match result {
            Err(MindError::Io { .. }) => {}
            other => panic!("expected Io error for missing parent dir, got {other:?}"),
        }
        assert!(
            !target.exists(),
            "target must not exist after a failed atomic_write"
        );
        assert!(
            !missing_dir.exists(),
            "atomic_write must not create the parent directory"
        );
    }

    #[test]
    fn atomic_write_preserves_existing_target_on_write_failure() {
        // A crash/error mid-write must leave the previous file intact (STO-43:
        // "a crash mid-write leaves the previous file intact"). We force the temp
        // write to fail by making the target a path under a *file* (so the temp's
        // parent is not a directory), and assert the original target is unchanged.
        // spec: STO-43
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-paths-failkeep-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        // `blocker` is a regular file; treating it as a directory makes any write
        // under it fail (ENOTDIR), exercising the temp-write error branch.
        let blocker = dir.join("blocker");
        std::fs::write(&blocker, b"i am a file").unwrap();
        let target = blocker.join("data.json");

        let result = Paths::atomic_write(&target, b"new");
        assert!(
            matches!(result, Err(MindError::Io { .. })),
            "expected Io error when temp parent is a file, got {result:?}"
        );
        // The blocker file must be untouched (not clobbered by a temp file name).
        assert_eq!(
            std::fs::read(&blocker).unwrap(),
            b"i am a file",
            "unrelated sibling content must be preserved on failure"
        );

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

    #[test]
    fn atomic_write_to_pathless_target_is_an_error() {
        // A target with no parent (the filesystem root) cannot host a sibling
        // temp; atomic_write must surface that as an Io error, not panic.
        // spec: STO-43
        let result = Paths::atomic_write(std::path::Path::new("/"), b"x");
        assert!(
            matches!(result, Err(MindError::Io { .. })),
            "writing to a target with no usable parent must be an Io error, got {result:?}"
        );
    }

    #[test]
    fn atomic_write_uses_same_directory_for_temp() {
        // The temp file must be in the same directory as the target so rename
        // is atomic (same filesystem).
        // spec: STO-43
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-paths-samedir-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("sources.json");

        // Hook: after write the temp file should be in the same directory.
        // We can verify by checking rename succeeded (no EXDEV cross-device error).
        Paths::atomic_write(&target, b"[]").unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), b"[]");

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

    // ---- managed-policy lobe tests -----------------------------------------

    /// Write a policy.toml, build a Paths pointing at a temp dir, and set
    /// MIND_POLICY_FILE. Returns (Paths, managed-dir, policy-file-path, guard).
    /// The guard must be held for the duration of the test; drop it last to
    /// restore the env var.
    fn setup_policy_test(
        policy_toml: &str,
    ) -> (Paths, PathBuf, PathBuf, std::sync::MutexGuard<'static, ()>) {
        let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base =
            std::env::temp_dir().join(format!("mind-policy-lobe-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();
        let policy_file = base.join("policy.toml");
        std::fs::write(&policy_file, policy_toml).unwrap();
        // Unset MIND_AGENT_HOMES so it doesn't bleed in from the outer env.
        // SAFETY: ENV_LOCK is held, so no concurrent env reads on other threads.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
            std::env::set_var("MIND_POLICY_FILE", &policy_file);
        }
        let paths = Paths {
            mind_home,
            claude_home,
        };
        (paths, base, policy_file, guard)
    }

    // POL-40: with lobes.lock=true and explicit targets, agent_homes returns
    // exactly the policy targets, ignoring $MIND_AGENT_HOMES and config lobes.
    #[test]
    fn pol40_lock_true_uses_exactly_policy_targets() {
        // spec: POL-40
        let managed = {
            let n = COUNTER.fetch_add(1, Ordering::SeqCst);
            std::env::temp_dir().join(format!("mind-managed-lobe-{}-{n}", std::process::id()))
        };
        let policy_toml = format!(
            "[lobes]\nlock = true\ntargets = [\"{managed}\"]\n",
            managed = managed.display()
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // Write a config with a different lobe - it must be ignored under lock.
        let other_lobe = base.join("other-lobe");
        let config_toml = format!(
            "lobes = [\"{other_lobe}\"]\n",
            other_lobe = other_lobe.display()
        );
        std::fs::write(paths.mind_home.join("config.toml"), &config_toml).unwrap();

        // Also set MIND_AGENT_HOMES to yet another path - also must be ignored.
        let env_lobe = base.join("env-lobe");
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", env_lobe.to_str().unwrap());
        }

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();

        // Restore env before any asserts that might panic.
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        assert_eq!(
            homes,
            vec![managed.clone()],
            "POL-40: locked policy must return exactly the managed target, not config/env homes"
        );
        assert!(
            !homes.contains(&other_lobe),
            "config lobe must be ignored under lock"
        );
        assert!(
            !homes.contains(&env_lobe),
            "MIND_AGENT_HOMES must be ignored under lock"
        );

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

    // POL-40: with lobes.lock=true and empty targets, agent_homes falls back to
    // the default (claude_home), not an empty list.
    #[test]
    fn pol40_lock_true_empty_targets_falls_back_to_default() {
        // spec: POL-40
        let policy_toml = "[lobes]\nlock = true\ntargets = []\n";
        let (paths, base, _policy_file, _guard) = setup_policy_test(policy_toml);

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(
            homes,
            vec![paths.claude_home.clone()],
            "POL-40: empty targets under a lock must fall back to the default (claude_home)"
        );

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

    // POL-41: with lobes.lock=false (or absent) and policy targets set, agent_homes
    // returns the union of policy targets and user homes, with targets first and
    // no duplicates.
    #[test]
    fn pol41_lock_false_unions_policy_and_user_homes() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir = std::env::temp_dir().join(format!("mind-pol41-{}-{n}", std::process::id()));
        let policy_target = base_dir.join("policy-base");
        let user_lobe = base_dir.join("user-lobe");
        let policy_toml = format!(
            "[lobes]\nlock = false\ntargets = [\"{policy_target}\"]\n",
            policy_target = policy_target.display()
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // Write a config with a user lobe.
        let config_toml = format!(
            "lobes = [\"{user_lobe}\"]\n",
            user_lobe = user_lobe.display()
        );
        std::fs::write(paths.mind_home.join("config.toml"), &config_toml).unwrap();

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert!(
            homes.contains(&policy_target),
            "POL-41: policy target must be present in union: {homes:?}"
        );
        assert!(
            homes.contains(&user_lobe),
            "POL-41: user lobe must also be present: {homes:?}"
        );
        // Policy target is first.
        assert_eq!(
            homes[0], policy_target,
            "POL-41: policy target must come first in the union"
        );
        // No duplicates.
        let deduped: Vec<_> = {
            let mut seen = std::collections::HashSet::new();
            homes.iter().filter(|h| seen.insert(*h)).cloned().collect()
        };
        assert_eq!(homes, deduped, "POL-41: result must not contain duplicates");

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

    // POL-41: when a policy target is already in the user's homes, it is not
    // duplicated in the result.
    #[test]
    fn pol41_deduplicates_overlapping_target_and_user_home() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let shared =
            std::env::temp_dir().join(format!("mind-pol41-shared-{}-{n}", std::process::id()));
        let policy_toml = format!(
            "[lobes]\nlock = false\ntargets = [\"{shared}\"]\n",
            shared = shared.display()
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // User config also lists the same path.
        let config_toml = format!("lobes = [\"{shared}\"]\n", shared = shared.display());
        std::fs::write(paths.mind_home.join("config.toml"), &config_toml).unwrap();

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(
            homes.len(),
            1,
            "POL-41: identical target + user lobe must be deduped to one entry: {homes:?}"
        );
        assert_eq!(homes[0], shared);

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

    // POL-4 inert: with no MIND_POLICY_FILE set and no system policy file,
    // agent_homes behaves exactly as before the policy feature (uses config lobes).
    #[test]
    fn pol4_inert_no_policy_uses_user_config() {
        // spec: POL-40
        // spec: POL-41
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-pol4-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        // Ensure no policy env var is set.
        // SAFETY: ENV_LOCK is held, so no concurrent env reads on other threads.
        unsafe {
            std::env::remove_var("MIND_POLICY_FILE");
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        let user_lobe = base.join("user-lobe");
        let config_toml = format!(
            "lobes = [\"{user_lobe}\"]\n",
            user_lobe = user_lobe.display()
        );
        std::fs::write(mind_home.join("config.toml"), &config_toml).unwrap();

        let paths = Paths {
            mind_home,
            claude_home,
        };
        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(
            homes,
            vec![user_lobe.clone()],
            "POL-4 inert: without a policy, user config lobes must be used as-is"
        );

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

    // ---- gap-closing managed-policy lobe tests -----------------------------

    // POL-41: the unlocked union must draw the user's homes from the
    // $MIND_AGENT_HOMES source, not only from config lobes. With an unlocked
    // policy target and MIND_AGENT_HOMES set (no config), the env home appears in
    // the union, after the policy target, with no duplicates.
    #[test]
    fn pol41_unions_policy_with_env_agent_homes() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol41-env-{}-{n}", std::process::id()));
        let policy_target = base_dir.join("policy-base");
        let env_lobe = base_dir.join("env-lobe");
        let policy_toml = format!(
            "[lobes]\nlock = false\ntargets = [\"{policy_target}\"]\n",
            policy_target = policy_target.display()
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // Drive user homes via the env var (no config.toml written), to exercise
        // the $MIND_AGENT_HOMES source of user homes specifically.
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", env_lobe.to_str().unwrap());
        }

        let homes = paths.agent_homes();

        // Restore env before any asserts that might panic.
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }
        let homes: Vec<PathBuf> = homes.unwrap().into_iter().map(|l| l.path).collect();

        assert_eq!(
            homes,
            vec![policy_target.clone(), env_lobe.clone()],
            "POL-41: unlocked union must be [policy target, env home], targets first, deduped"
        );

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

    // POL-40: a lock with MULTIPLE targets returns exactly those targets in
    // declaration order, even when several user homes are set via env (all
    // ignored under the lock).
    #[test]
    fn pol40_lock_true_multiple_targets_in_order_ignores_user_homes() {
        // spec: POL-40
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol40-multi-{}-{n}", std::process::id()));
        let t1 = base_dir.join("target-a");
        let t2 = base_dir.join("target-b");
        let t3 = base_dir.join("target-c");
        let policy_toml = format!(
            "[lobes]\nlock = true\ntargets = [\"{t1}\", \"{t2}\", \"{t3}\"]\n",
            t1 = t1.display(),
            t2 = t2.display(),
            t3 = t3.display(),
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // Multiple user homes via env - all must be ignored under the lock.
        let e1 = base_dir.join("env-1");
        let e2 = base_dir.join("env-2");
        let env_val = format!("{}:{}", e1.display(), e2.display());
        // Also write a config lobe to confirm config is ignored too.
        let cfg_lobe = base_dir.join("cfg-lobe");
        std::fs::write(
            paths.mind_home.join("config.toml"),
            format!("lobes = [\"{}\"]\n", cfg_lobe.display()),
        )
        .unwrap();
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", &env_val);
        }

        let homes = paths.agent_homes();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }
        let homes: Vec<PathBuf> = homes.unwrap().into_iter().map(|l| l.path).collect();

        assert_eq!(
            homes,
            vec![t1.clone(), t2.clone(), t3.clone()],
            "POL-40: locked policy must return exactly the targets in order"
        );
        assert!(!homes.contains(&e1) && !homes.contains(&e2));
        assert!(!homes.contains(&cfg_lobe));

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

    // POL-41: unlocked union with MULTIPLE targets and MULTIPLE user homes, where
    // one user home duplicates a policy target. Asserts the exact deduped order:
    // all targets first (in order), then the user homes not already present (in
    // order), with the overlap dropped.
    #[test]
    fn pol41_multiple_targets_and_homes_exact_deduped_order() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol41-multi-{}-{n}", std::process::id()));
        let t1 = base_dir.join("t1");
        let t2 = base_dir.join("t2"); // also a user home (overlap)
        let u_extra = base_dir.join("u-extra");
        let policy_toml = format!(
            "[lobes]\nlock = false\ntargets = [\"{t1}\", \"{t2}\"]\n",
            t1 = t1.display(),
            t2 = t2.display(),
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // User homes (via env): t2 (overlaps target) then u_extra. Order matters:
        // t2 must be dropped as a dup, u_extra kept and appended last.
        let env_val = format!("{}:{}", t2.display(), u_extra.display());
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", &env_val);
        }

        let homes = paths.agent_homes();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }
        let homes: Vec<PathBuf> = homes.unwrap().into_iter().map(|l| l.path).collect();

        assert_eq!(
            homes,
            vec![t1.clone(), t2.clone(), u_extra.clone()],
            "POL-41: targets first in order, then non-duplicate user homes; overlap dropped"
        );

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

    // POL-4 inert via the $MIND_AGENT_HOMES source (not config): with no policy
    // and MIND_AGENT_HOMES set, agent_homes returns those homes unchanged.
    #[test]
    fn pol4_inert_no_policy_uses_env_agent_homes_unchanged() {
        // spec: POL-40
        // spec: POL-41
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-pol4-env-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        let env1 = base.join("env-home-1");
        let env2 = base.join("env-home-2");
        let env_val = format!("{}:{}", env1.display(), env2.display());
        // No policy file; env drives user homes.
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_POLICY_FILE");
            std::env::set_var("MIND_AGENT_HOMES", &env_val);
        }

        let paths = Paths {
            mind_home,
            claude_home,
        };
        let homes = paths.agent_homes();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }
        let homes: Vec<PathBuf> = homes.unwrap().into_iter().map(|l| l.path).collect();

        assert_eq!(
            homes,
            vec![env1.clone(), env2.clone()],
            "POL-4 inert: without a policy, $MIND_AGENT_HOMES homes must be returned unchanged"
        );

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

    // POL-40: a locked target written with a leading `~` is expanded to the home
    // directory and resolved to an absolute path (via absolute_home), so the
    // effective home never depends on the working directory.
    #[test]
    fn pol40_lock_target_tilde_is_expanded_to_absolute() {
        // spec: POL-40
        let policy_toml = "[lobes]\nlock = true\ntargets = [\"~/.claude-managed\"]\n";
        let (paths, base, _policy_file, _guard) = setup_policy_test(policy_toml);

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(homes.len(), 1);
        let got = &homes[0];
        assert!(
            got.is_absolute(),
            "tilde target must resolve absolute: {got:?}"
        );
        assert!(
            got.ends_with(".claude-managed"),
            "tilde target must expand under home: {got:?}"
        );
        let home = dirs::home_dir().expect("home dir for tilde expansion");
        assert_eq!(
            got,
            &home.join(".claude-managed"),
            "POL-40: `~` target must expand to <home>/.claude-managed"
        );

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

    // POL-40: a RELATIVE locked target is resolved to an absolute path against the
    // current directory (make_absolute), so a later uninstall sees a stable,
    // cwd-independent home rather than the verbatim relative string.
    #[test]
    fn pol40_lock_relative_target_becomes_absolute() {
        // spec: POL-40
        let policy_toml = "[lobes]\nlock = true\ntargets = [\"managed-rel-lobe\"]\n";
        let (paths, base, _policy_file, _guard) = setup_policy_test(policy_toml);

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(homes.len(), 1);
        let got = &homes[0];
        assert!(
            got.is_absolute(),
            "POL-40: a relative target must be resolved to absolute: {got:?}"
        );
        assert!(
            got.ends_with("managed-rel-lobe"),
            "the relative component must be preserved: {got:?}"
        );

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

    // POL-41: an unlocked relative target is likewise resolved to absolute before
    // the union, so the targets-first entry is a stable absolute path.
    #[test]
    fn pol41_unlocked_relative_target_becomes_absolute() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol41-rel-{}-{n}", std::process::id()));
        let user_lobe = base_dir.join("user-lobe");
        let policy_toml = "[lobes]\nlock = false\ntargets = [\"unlocked-rel-lobe\"]\n";
        let (paths, base, _policy_file, _guard) = setup_policy_test(policy_toml);

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", user_lobe.to_str().unwrap());
        }
        let homes = paths.agent_homes();
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }
        let homes: Vec<PathBuf> = homes.unwrap().into_iter().map(|l| l.path).collect();

        assert_eq!(homes.len(), 2, "target + one user home: {homes:?}");
        assert!(
            homes[0].is_absolute() && homes[0].ends_with("unlocked-rel-lobe"),
            "POL-41: unlocked relative target must resolve absolute, first: {homes:?}"
        );
        assert_eq!(homes[1], user_lobe, "user home follows the target");

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

    // POL-41: duplicate entries within `targets` itself (e.g. the policy TOML
    // lists the same path twice) collapse to a single entry. A target that
    // duplicates the user home is also collapsed. The deduped result preserves
    // first-seen order.
    #[test]
    fn pol41_duplicate_targets_collapse_to_one_entry() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol41-dup-{}-{n}", std::process::id()));
        let dup_target = base_dir.join("dup-target");
        let user_lobe = base_dir.join("user-lobe");

        // targets has dup_target listed twice.
        let policy_toml = format!(
            "[lobes]\nlock = false\ntargets = [\"{dup}\", \"{dup}\"]\n",
            dup = dup_target.display(),
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        // User home is distinct from the duplicated target.
        let config_toml = format!(
            "lobes = [\"{user_lobe}\"]\n",
            user_lobe = user_lobe.display()
        );
        std::fs::write(paths.mind_home.join("config.toml"), &config_toml).unwrap();

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();

        // dup_target appears only once (duplicate within targets collapsed), then user_lobe.
        assert_eq!(
            homes,
            vec![dup_target.clone(), user_lobe.clone()],
            "POL-41: duplicate targets must collapse to one entry, user home follows: {homes:?}"
        );

        // Also verify: duplicate target that also equals the user home collapses to one.
        let shared = base_dir.join("shared");
        let policy_toml2 = format!(
            "[lobes]\nlock = false\ntargets = [\"{shared}\", \"{shared}\"]\n",
            shared = shared.display(),
        );
        std::fs::write(base.join("policy.toml"), &policy_toml2).unwrap();
        let config_toml2 = format!("lobes = [\"{shared}\"]\n", shared = shared.display());
        std::fs::write(paths.mind_home.join("config.toml"), &config_toml2).unwrap();

        let homes2: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();
        assert_eq!(
            homes2,
            vec![shared.clone()],
            "POL-41: duplicates across targets and user home must all collapse to one: {homes2:?}"
        );

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

    // POL-40: duplicate entries within `targets` in a LOCKED policy collapse to
    // a single entry. The dedup must apply in the locked branch too.
    #[test]
    fn pol40_duplicate_targets_collapse_to_one_entry() {
        // spec: POL-41
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-pol40-dup-{}-{n}", std::process::id()));
        let dup_target = base_dir.join("dup-locked");

        // targets has the same path twice under a lock.
        let policy_toml = format!(
            "[lobes]\nlock = true\ntargets = [\"{dup}\", \"{dup}\"]\n",
            dup = dup_target.display(),
        );
        let (paths, base, _policy_file, _guard) = setup_policy_test(&policy_toml);

        let homes: Vec<PathBuf> = paths
            .agent_homes()
            .unwrap()
            .into_iter()
            .map(|l| l.path)
            .collect();

        assert_eq!(
            homes,
            vec![dup_target.clone()],
            "POL-40: duplicate locked targets must collapse to one entry: {homes:?}"
        );

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

    // ---- HARN: kinds filter, presets, and detection ------------------------

    // HARN-1: a lobe with no kinds filter admits every kind (no filter), while a
    // filtered lobe admits only the listed kinds.
    #[test]
    fn lobe_admits_respects_kinds_filter() {
        // spec: HARN-1
        let all = Lobe::all_kinds(PathBuf::from("/x"));
        assert!(all.admits(ItemKind::Skill));
        assert!(all.admits(ItemKind::Agent));
        assert!(all.admits(ItemKind::Rule));
        assert!(
            all.admits(ItemKind::Tool),
            "an unfiltered lobe admits all kinds, so a tool with an explicit link surfaces (TOOL-4)"
        );

        let skills_only = Lobe {
            path: PathBuf::from("/y"),
            kinds: Some(vec![ItemKind::Skill]),
        };
        assert!(skills_only.admits(ItemKind::Skill));
        assert!(
            !skills_only.admits(ItemKind::Agent),
            "a skill-only lobe must reject an agent (HARN-1)"
        );
        assert!(
            !skills_only.admits(ItemKind::Rule),
            "a skill-only lobe must reject a rule (HARN-3: rules are Claude-only)"
        );
    }

    // HARN-4: each named preset resolves to its parent path and kinds; an unknown
    // name errors with UnknownPreset.
    #[test]
    fn preset_lookup_and_resolution() {
        // spec: HARN-4
        let gemini = lookup_preset("gemini").unwrap();
        assert_eq!(gemini.rel_path, ".gemini/config");
        assert_eq!(gemini.kinds, &[ItemKind::Skill]);
        assert_eq!(gemini.scope, Scope::Global);

        let codex = lookup_preset("codex").unwrap();
        assert_eq!(codex.rel_path, ".agents");
        assert_eq!(codex.kinds, &[ItemKind::Skill]);
        assert_eq!(codex.scope, Scope::Global);

        assert_eq!(lookup_preset("universal").unwrap().rel_path, ".agents");
        assert_eq!(lookup_preset("universal").unwrap().scope, Scope::Global);

        let windsurf = lookup_preset("windsurf").unwrap();
        assert_eq!(windsurf.rel_path, ".windsurf");
        assert_eq!(windsurf.kinds, &[ItemKind::Skill]);
        // Windsurf is project-scoped: it discovers skills only per-project.
        assert_eq!(windsurf.scope, Scope::Project);
        // Windsurf's detection marker is the real global config home, not .windsurf.
        assert_eq!(windsurf.marker_rel, ".codeium/windsurf");

        // preset_lobe("windsurf") returns the cwd/.windsurf lobe (Project scope,
        // no explicit base -> defaults to cwd).
        let ws_lobe = Paths::preset_lobe("windsurf").unwrap();
        assert!(
            ws_lobe.path.is_absolute(),
            "preset path must be absolute (STO-16)"
        );
        assert!(ws_lobe.path.ends_with(".windsurf"));
        assert_eq!(ws_lobe.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));

        // Removed presets are unknown.
        assert!(matches!(
            lookup_preset("antigravity"),
            Err(MindError::UnknownPreset { .. })
        ));
        assert!(matches!(
            lookup_preset("antigravity-cli"),
            Err(MindError::UnknownPreset { .. })
        ));

        // An unknown preset name is a structured error.
        assert!(matches!(
            lookup_preset("emacs"),
            Err(MindError::UnknownPreset { .. })
        ));

        // preset_lobe resolves the path to absolute and carries the kinds.
        let lobe = Paths::preset_lobe("gemini").unwrap();
        assert!(
            lobe.path.is_absolute(),
            "preset path must be absolute (STO-16)"
        );
        assert!(lobe.path.ends_with(".gemini/config"));
        assert_eq!(lobe.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));
        assert!(Paths::preset_lobe("nope").is_err());
    }

    // HARN-5: detect_homes reports a preset only when its marker dir exists under
    // the detection base ($MIND_DETECT_HOME), and reports the lobe under that base.
    // Windsurf's marker changed from `.windsurf` to `.codeium/windsurf` (the real
    // Windsurf global config home); its lobe subdir stays `.windsurf`.
    #[test]
    fn detect_homes_reports_existing_marker_dirs() {
        // spec: HARN-5
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-detect-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        // Create .gemini and .agents but NOT .codex/.gemini/config.
        // Windsurf's detection marker is now .codeium/windsurf (not .windsurf).
        std::fs::create_dir_all(base.join(".gemini")).unwrap();
        std::fs::create_dir_all(base.join(".agents")).unwrap();
        std::fs::create_dir_all(base.join(".codeium/windsurf")).unwrap();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_DETECT_HOME", &base);
        }
        let detected = Paths::detect_homes();
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_DETECT_HOME");
        }
        let detected = detected.unwrap();

        let names: Vec<&str> = detected.iter().map(|(n, _)| *n).collect();
        assert!(names.contains(&"gemini"), "gemini marker exists: {names:?}");
        assert!(
            names.contains(&"universal"),
            "agents marker exists: {names:?}"
        );
        assert!(
            !names.contains(&"codex"),
            "no .codex dir, so codex must not be detected: {names:?}"
        );

        // The reported gemini lobe is under the detection base (.gemini/config) and carries kinds.
        let (_, gemini_lobe) = detected.iter().find(|(n, _)| *n == "gemini").unwrap();
        assert_eq!(gemini_lobe.path, base.join(".gemini/config"));
        assert_eq!(
            gemini_lobe.kinds.as_deref(),
            Some([ItemKind::Skill].as_slice())
        );

        // Windsurf detected via .codeium/windsurf marker; lobe subdir is still .windsurf.
        assert!(
            names.contains(&"windsurf"),
            "windsurf .codeium/windsurf marker exists: {names:?}"
        );
        let (_, ws_lobe) = detected.iter().find(|(n, _)| *n == "windsurf").unwrap();
        assert_eq!(ws_lobe.path, base.join(".windsurf"));
        assert_eq!(ws_lobe.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));

        // .windsurf alone is no longer the windsurf marker; windsurf must NOT be
        // double-detected.
        assert_eq!(
            names.iter().filter(|n| **n == "windsurf").count(),
            1,
            "windsurf must appear exactly once in detected list"
        );

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

    // HARN-5 / windsurf: a bare `.windsurf` directory (without `.codeium/windsurf`)
    // no longer triggers windsurf detection after the marker change.
    #[test]
    fn detect_homes_windsurf_requires_codeium_marker_not_bare_windsurf_dir() {
        // spec: HARN-5
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-detect-ws-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        // Create .windsurf but NOT .codeium/windsurf.
        std::fs::create_dir_all(base.join(".windsurf")).unwrap();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::set_var("MIND_DETECT_HOME", &base);
        }
        let detected = Paths::detect_homes();
        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_DETECT_HOME");
        }
        let detected = detected.unwrap();

        let names: Vec<&str> = detected.iter().map(|(n, _)| *n).collect();
        assert!(
            !names.contains(&"windsurf"),
            "bare .windsurf dir must no longer trigger windsurf detection (marker is .codeium/windsurf): {names:?}"
        );

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

    // HARN-1/HARN-2: a config lobe declaring a kinds filter flows through
    // agent_homes carrying that filter, while a bare config lobe is all-kinds.
    #[test]
    fn agent_homes_carry_config_kinds_filter() {
        // spec: HARN-1
        // spec: HARN-2
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-harn-cfg-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_POLICY_FILE");
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        std::fs::write(
            mind_home.join("config.toml"),
            "lobes = [\"/c/bare\", { path = \"/c/gem\", kinds = [\"skill\"] }]\n",
        )
        .unwrap();

        let paths = Paths {
            mind_home,
            claude_home,
        };
        let homes = paths.agent_homes().unwrap();
        assert_eq!(homes.len(), 2);
        assert_eq!(homes[0].path, PathBuf::from("/c/bare"));
        assert_eq!(homes[0].kinds, None, "a bare config lobe is all-kinds");
        assert_eq!(homes[1].path, PathBuf::from("/c/gem"));
        assert_eq!(
            homes[1].kinds.as_deref(),
            Some([ItemKind::Skill].as_slice()),
            "a filtered config lobe must carry its kinds"
        );
        // And admits reflects the filter.
        assert!(homes[1].admits(ItemKind::Skill));
        assert!(!homes[1].admits(ItemKind::Rule));

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

    // HARN-1/HARN-2: two config lobes naming the SAME path with DIFFERENT kinds
    // dedup to a single lobe, and the first-seen kinds win. This is the direct
    // collision case the codex+universal presets create (both resolve to
    // ~/.agents): `agent_homes` must not emit the same path twice, and must keep
    // the earlier entry's filter.
    #[test]
    fn agent_homes_dedup_collision_first_kinds_win() {
        // spec: HARN-1
        // spec: HARN-2
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-harn-dedup-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let mind_home = base.join("mind");
        let claude_home = base.join("claude");
        std::fs::create_dir_all(&mind_home).unwrap();
        std::fs::create_dir_all(&claude_home).unwrap();

        // SAFETY: ENV_LOCK is held.
        unsafe {
            std::env::remove_var("MIND_POLICY_FILE");
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        // Same path twice: first carries [skill], second carries [agent].
        std::fs::write(
            mind_home.join("config.toml"),
            "lobes = [{ path = \"/c/dup\", kinds = [\"skill\"] }, { path = \"/c/dup\", kinds = [\"agent\"] }]\n",
        )
        .unwrap();

        let paths = Paths {
            mind_home,
            claude_home,
        };
        let homes = paths.agent_homes().unwrap();
        assert_eq!(
            homes.len(),
            1,
            "same-path lobes must dedup to one entry: {homes:?}"
        );
        assert_eq!(homes[0].path, PathBuf::from("/c/dup"));
        assert_eq!(
            homes[0].kinds.as_deref(),
            Some([ItemKind::Skill].as_slice()),
            "first-seen kinds must win on a dedup collision: {homes:?}"
        );
        assert!(homes[0].admits(ItemKind::Skill));
        assert!(
            !homes[0].admits(ItemKind::Agent),
            "the losing entry's [agent] kind must not leak in"
        );

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

    // HARN-2: the codex and universal presets both resolve to the SAME lobe path
    // (~/.agents). `preset_lobe` must produce identical paths for the two, which
    // is what lets `agent_homes`/detect dedup collapse them. (The dedup itself is
    // covered above and in the CLI detect tests; this pins the precondition.)
    #[test]
    fn codex_and_universal_presets_share_a_path() {
        // spec: HARN-2
        // spec: HARN-4
        let codex = Paths::preset_lobe("codex").unwrap();
        let universal = Paths::preset_lobe("universal").unwrap();
        assert_eq!(
            codex.path, universal.path,
            "codex and universal must resolve to the same ~/.agents path"
        );
        assert!(codex.path.ends_with(".agents"));
        // Both are skill-only.
        assert_eq!(codex.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));
        assert_eq!(
            universal.kinds.as_deref(),
            Some([ItemKind::Skill].as_slice())
        );
    }

    // ---- resolve_lobe + Lobe::reachable tests --------------------------------

    // resolve_lobe: a Global preset with no explicit base resolves under home (~).
    #[test]
    fn resolve_lobe_global_preset_defaults_to_home() {
        // spec: STO-16
        // spec: HARN-4
        let (lobe, preset) = resolve_lobe(None, Some("gemini"), None).unwrap();
        assert!(
            lobe.path.is_absolute(),
            "path must be absolute: {:?}",
            lobe.path
        );
        assert!(
            lobe.path.ends_with(".gemini/config"),
            "gemini lobe must be at home/.gemini/config: {:?}",
            lobe.path
        );
        assert_eq!(
            lobe.kinds.as_deref(),
            Some([ItemKind::Skill].as_slice()),
            "gemini lobe must be skill-only"
        );
        let p = preset.expect("gemini must return a preset");
        assert_eq!(p.name, "gemini");
        assert_eq!(p.scope, Scope::Global);
    }

    // resolve_lobe: a Project preset with no explicit base defaults to cwd.
    #[test]
    fn resolve_lobe_project_preset_defaults_to_cwd() {
        // spec: STO-16
        // spec: HARN-4
        let (lobe, preset) = resolve_lobe(None, Some("windsurf"), None).unwrap();
        let cwd = std::env::current_dir().unwrap();
        assert!(
            lobe.path.is_absolute(),
            "path must be absolute: {:?}",
            lobe.path
        );
        assert_eq!(
            lobe.path,
            cwd.join(".windsurf"),
            "windsurf lobe with no base must resolve to cwd/.windsurf"
        );
        assert_eq!(lobe.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));
        let p = preset.expect("windsurf must return a preset");
        assert_eq!(p.scope, Scope::Project);
    }

    // resolve_lobe: an explicit base overrides the default for a Global preset.
    #[test]
    fn resolve_lobe_preset_with_explicit_base() {
        // spec: STO-16
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir =
            std::env::temp_dir().join(format!("mind-rl-base-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base_dir).unwrap();

        let (lobe, preset) =
            resolve_lobe(Some(base_dir.to_str().unwrap()), Some("gemini"), None).unwrap();
        assert_eq!(
            lobe.path,
            base_dir.join(".gemini/config"),
            "explicit base must override the home default for gemini"
        );
        let p = preset.unwrap();
        assert_eq!(p.name, "gemini");

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

    // resolve_lobe: --subdir without a preset uses the cwd as default base.
    #[test]
    fn resolve_lobe_subdir_defaults_base_to_cwd() {
        // spec: STO-16
        let (lobe, preset) = resolve_lobe(None, None, Some(".windsurf")).unwrap();
        let cwd = std::env::current_dir().unwrap();
        assert_eq!(
            lobe.path,
            cwd.join(".windsurf"),
            "--subdir with no base must use cwd"
        );
        assert_eq!(
            lobe.kinds.as_deref(),
            Some([ItemKind::Skill].as_slice()),
            "--subdir lobe must be skill-only"
        );
        assert!(
            preset.is_none(),
            "--subdir with no preset returns None preset"
        );
    }

    // resolve_lobe: --subdir with an explicit base joins base/subdir.
    #[test]
    fn resolve_lobe_subdir_with_explicit_base() {
        // spec: STO-16
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base_dir = std::env::temp_dir().join(format!("mind-rl-sub-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base_dir).unwrap();

        let (lobe, _) =
            resolve_lobe(Some(base_dir.to_str().unwrap()), None, Some(".myharness")).unwrap();
        assert_eq!(lobe.path, base_dir.join(".myharness"));
        assert_eq!(lobe.kinds.as_deref(), Some([ItemKind::Skill].as_slice()));

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

    // resolve_lobe: bare path add -- just a base, no preset or subdir.
    #[test]
    fn resolve_lobe_bare_path_add() {
        // spec: STO-16
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let lobe_dir =
            std::env::temp_dir().join(format!("mind-rl-bare-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&lobe_dir).unwrap();

        let (lobe, preset) = resolve_lobe(Some(lobe_dir.to_str().unwrap()), None, None).unwrap();
        assert_eq!(
            lobe.path, lobe_dir,
            "bare path add must use base as the lobe path"
        );
        assert_eq!(lobe.kinds, None, "bare path add must be all-kinds");
        assert!(preset.is_none());

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

    // resolve_lobe: no base, no preset, no subdir -> LobeTargetRequired.
    #[test]
    fn resolve_lobe_no_args_returns_lobe_target_required() {
        // spec: STO-16
        let err = resolve_lobe(None, None, None).unwrap_err();
        assert!(
            matches!(err, MindError::LobeTargetRequired),
            "no base/preset/subdir must be LobeTargetRequired: {err:?}"
        );
    }

    // resolve_lobe: explicit base that does not exist -> LobeBaseMissing.
    #[test]
    fn resolve_lobe_missing_base_returns_lobe_base_missing() {
        // spec: STO-56
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let missing =
            std::env::temp_dir().join(format!("mind-rl-missing-{}-{n}", std::process::id()));
        // Do NOT create missing.
        let err =
            resolve_lobe(Some(missing.to_str().unwrap()), Some("windsurf"), None).unwrap_err();
        assert!(
            matches!(err, MindError::LobeBaseMissing { .. }),
            "nonexistent explicit base must be LobeBaseMissing: {err:?}"
        );
        // Also for --subdir with a missing base.
        let err2 = resolve_lobe(Some(missing.to_str().unwrap()), None, Some(".ws")).unwrap_err();
        assert!(
            matches!(err2, MindError::LobeBaseMissing { .. }),
            "--subdir with nonexistent base must be LobeBaseMissing: {err2:?}"
        );
    }

    // Lobe::reachable: true when the parent exists, false when it doesn't.
    #[test]
    fn lobe_reachable_true_when_parent_exists() {
        // spec: STO-56
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-reach-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();

        // base exists -> lobe at base/.windsurf: parent (base) exists -> reachable.
        let lobe = Lobe {
            path: base.join(".windsurf"),
            kinds: Some(vec![ItemKind::Skill]),
        };
        assert!(
            lobe.reachable(),
            "lobe is reachable when its parent dir exists (STO-56)"
        );

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

    #[test]
    fn lobe_reachable_false_when_parent_missing() {
        // spec: STO-56
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let vanished = std::env::temp_dir().join(format!("mind-gone-{}-{n}", std::process::id()));
        // Do NOT create vanished.
        let lobe = Lobe {
            path: vanished.join(".windsurf"),
            kinds: Some(vec![ItemKind::Skill]),
        };
        assert!(
            !lobe.reachable(),
            "lobe is unreachable when its parent dir is missing (STO-56)"
        );
    }

    #[test]
    fn lobe_reachable_global_home_always_reachable() {
        // spec: STO-56
        // A global home like ~/.claude always has a parent (~) that exists.
        let home = dirs::home_dir().expect("home dir must exist in test env");
        let claude = home.join(".claude");
        let lobe = Lobe::all_kinds(claude);
        assert!(
            lobe.reachable(),
            "global home lobe parent (~) always exists (STO-56)"
        );
    }

    // resolve_lobe: windsurf scope is Project; gemini/codex/universal are Global.
    #[test]
    fn preset_scope_assignments() {
        // spec: HARN-4
        assert_eq!(lookup_preset("gemini").unwrap().scope, Scope::Global);
        assert_eq!(lookup_preset("codex").unwrap().scope, Scope::Global);
        assert_eq!(lookup_preset("universal").unwrap().scope, Scope::Global);
        assert_eq!(lookup_preset("windsurf").unwrap().scope, Scope::Project);
    }
}