mind-cli 0.44.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
//! Lifecycle hooks: source-declared (`[source].install`/`[[hooks]]`) or
//! item-declared (`[[items.hooks]]`, HOOK-86) shell commands that run at
//! install, update, or uninstall, plus the per-item `build` step. Because each
//! is arbitrary code from the source, `mind` discloses it and prompts before
//! running (see spec/install-hooks.md).

#[cfg(test)]
use std::io::BufRead;
use std::io::IsTerminal;
use std::io::Write as _;
use std::path::Path;
use std::process::{Command, Stdio};

use crate::error::{MindError, Result};

/// The profile variables every hook runs with (HOOK-140): the enabled profiles
/// of the hook's source, and for an item or build hook the profiles the item is
/// installed for. Both are always set on the child, empty when there is nothing
/// to report, so a value inherited from mind's own environment never leaks in.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HookEnv {
    pub profiles: Vec<String>,
    pub item_profiles: Vec<String>,
}

impl HookEnv {
    /// The `(name, value)` pairs set on the child (HOOK-140): sorted,
    /// deduped, comma-separated, no spaces.
    pub fn vars(&self) -> [(&'static str, String); 2] {
        let join = |v: &[String]| {
            let set: std::collections::BTreeSet<&str> = v.iter().map(String::as_str).collect();
            set.into_iter().collect::<Vec<_>>().join(",")
        };
        [
            ("MIND_PROFILES", join(&self.profiles)),
            ("MIND_ITEM_PROFILES", join(&self.item_profiles)),
        ]
    }
}

/// The hook events run without the safety prompt (`--accept-hooks`, HOOK-23,
/// HOOK-74, HOOK-83). The default accepts nothing: every hook is prompted on a
/// TTY and skipped without one.
// spec: HOOK-150
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Accept {
    pub install: bool,
    pub update: bool,
    pub uninstall: bool,
    pub build: bool,
}

impl Accept {
    /// Every event: what a bare `--accept-hooks` gives.
    pub const ALL: Accept = Accept {
        install: true,
        update: true,
        uninstall: true,
        build: true,
    };

    /// Whether a lifecycle hook for `event` runs without the prompt.
    pub fn event(self, event: crate::mindfile::HookEvent) -> bool {
        use crate::mindfile::HookEvent;
        match event {
            HookEvent::Install => self.install,
            HookEvent::Update => self.update,
            HookEvent::Uninstall => self.uninstall,
        }
    }

    /// [`Accept::event`] by the event's `mind.toml` spelling; an unknown
    /// spelling is never accepted.
    pub fn event_str(self, event: &str) -> bool {
        match event {
            "install" => self.install,
            "update" => self.update,
            "uninstall" => self.uninstall,
            "build" => self.build,
            _ => false,
        }
    }
}

/// The profile state an in-flight profile change leaves behind (HOOK-141),
/// set while a profile install is applied or a profile is disabled, so hooks
/// run deep inside the ordinary install/uninstall path see it before it is
/// recorded.
#[derive(Debug, Clone, Default)]
pub struct ProfileScope {
    /// The registered source identity the change applies to.
    pub source: String,
    /// The enabled set once the change is recorded.
    pub enabled: Vec<String>,
    /// Effective item key -> the profiles it is being installed for.
    pub reasons: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
}

thread_local! {
    static PROFILE_SCOPE: std::cell::RefCell<Option<ProfileScope>> =
        const { std::cell::RefCell::new(None) };
}

/// Holds a [`ProfileScope`] in effect; dropping it restores the previous one.
pub struct ProfileScopeGuard(Option<ProfileScope>);

impl Drop for ProfileScopeGuard {
    fn drop(&mut self) {
        let prev = self.0.take();
        PROFILE_SCOPE.with(|c| *c.borrow_mut() = prev);
    }
}

/// Put `scope` in effect for the lifetime of the returned guard (HOOK-141).
pub fn scope_profiles(scope: ProfileScope) -> ProfileScopeGuard {
    let prev = PROFILE_SCOPE.with(|c| c.borrow_mut().replace(scope));
    ProfileScopeGuard(prev)
}

/// The scoped enabled set for `source`, when a profile change on it is in
/// flight (HOOK-141).
pub fn scoped_profiles(source: &str) -> Option<Vec<String>> {
    PROFILE_SCOPE.with(|c| {
        c.borrow()
            .as_ref()
            .filter(|s| s.source == source)
            .map(|s| s.enabled.clone())
    })
}

/// The profiles the in-flight change installs `key` of `source` for.
pub fn scoped_item_reasons(source: &str, key: &str) -> Vec<String> {
    PROFILE_SCOPE.with(|c| {
        c.borrow()
            .as_ref()
            .filter(|s| s.source == source)
            .and_then(|s| s.reasons.get(key))
            .map(|r| r.iter().cloned().collect())
            .unwrap_or_default()
    })
}

/// The user's response to the three-way hook prompt (HOOK-20).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookChoice {
    RunAndContinue,
    SkipAndContinue,
    Abort,
}

/// The replies of the three-way prompt (HOOK-20, CLI-257): run, skip, abort.
const HOOK_CHOICES: [crate::prompt::Choice<HookChoice>; 3] = [
    crate::prompt::Choice {
        keys: &["y", "yes"],
        value: HookChoice::RunAndContinue,
    },
    crate::prompt::Choice {
        keys: &["n", "no"],
        value: HookChoice::SkipAndContinue,
    },
    crate::prompt::Choice {
        keys: &["a", "abort"],
        value: HookChoice::Abort,
    },
];

/// Set for an unattended `auto-update run` (AUP-15): it never prompts, even
/// when started from a terminal, so every consent gate takes its no-TTY path.
static NON_INTERACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Make every later [`is_tty`] answer no for the rest of the process.
pub fn force_non_interactive() {
    NON_INTERACTIVE.store(true, std::sync::atomic::Ordering::Relaxed);
}

/// Whether stdin is an interactive terminal (the HOOK-22 gate).
///
/// `$MIND_TTY` overrides the answer (HOOK-109) so the interactive branches are
/// reachable from a headless test, following the `MIND_HOME` / `CLAUDE_HOME` /
/// `MIND_DETECT_HOME` test-isolation precedent (`paths.rs`): the variable is
/// read first and, when set, decides on its own; `is_terminal()` is the
/// fallback consulted only when the variable is absent. Values are read as a
/// boolean by [`tty_override`].
// spec: HOOK-109
pub fn is_tty() -> bool {
    if NON_INTERACTIVE.load(std::sync::atomic::Ordering::Relaxed) {
        return false;
    }
    match std::env::var_os("MIND_TTY") {
        Some(v) => tty_override(&v),
        None => std::io::stdin().is_terminal(),
    }
}

/// Read a `$MIND_TTY` value as a boolean (HOOK-109). Empty, `0`, `false`, `no`,
/// and `off` (any case, surrounding whitespace ignored) mean "not a terminal";
/// every other value means "a terminal". Pure, so the mapping is unit-testable
/// without mutating the process environment.
fn tty_override(value: &std::ffi::OsStr) -> bool {
    !matches!(
        value.to_string_lossy().trim().to_ascii_lowercase().as_str(),
        "" | "0" | "false" | "no" | "off"
    )
}

/// The HOOK-20 disclosure shown before running a hook. Pure (returns a String)
/// so it is unit-testable. Includes the source identity, the resolved pin
/// description, the commit, the clone path, the exact command, and a clear
/// arbitrary-code warning. When `declared_override` is Some(declared), also
/// shows the declared command and states the user-supplied command replaces it
/// (HOOK-2's loud override). Prepends a `====== hook: {identity} ======`
/// header so the block reads as distinct from surrounding output.
pub fn disclosure_text(
    identity: &str,
    pin_desc: &str,
    commit: &str,
    clone_path: &str,
    command: &str,
    declared_override: Option<&str>,
    browse_url: Option<&str>,
) -> String {
    // Sanitize identity for the header line; disclosure_body sanitizes all body
    // fields independently (HOOK-91).
    let identity_clean = crate::sanitize::strip_ansi(identity);
    let mut out = String::new();
    out.push_str("====== hook: ");
    out.push_str(&identity_clean);
    out.push_str(" ======\n");
    out.push_str(&disclosure_body(
        identity,
        pin_desc,
        commit,
        clone_path,
        command,
        declared_override,
        browse_url,
    ));
    out
}

/// The three-way question line (HOOK-20).
const HOOK_QUESTION: &str = "Run this hook? [Y/n/a] (default Y): ";

/// Read replies from `reader` until one is valid (CLI-257); Enter and EOF run
/// the hook, the default (HOOK-20, CLI-258). The test seam for the prompt's
/// reply handling; [`prompt_choice`] asks the same way on the terminal.
#[cfg(test)]
fn read_choice<R: BufRead>(mut reader: R) -> Result<HookChoice> {
    crate::prompt::ask_from(
        &mut reader,
        &mut std::io::sink(),
        "",
        &HOOK_CHOICES,
        HookChoice::RunAndContinue,
    )
}

/// Print the disclosure and the three choices, then ask until a valid reply
/// (HOOK-20, CLI-257). Only reached on a TTY (HOOK-22).
pub fn prompt_choice(disclosure: &str) -> Result<HookChoice> {
    // spec: TUI-44
    crate::prompt::guard("running a hook")?;
    // spec: PRG-5
    crate::progress::suspend(|| {
        print!("{disclosure}");
        println!("  [Y] run the hook   [n] skip it   [a] abort - install nothing");
        let stdin = std::io::stdin();
        crate::prompt::ask_from(
            &mut stdin.lock(),
            &mut std::io::stdout(),
            HOOK_QUESTION,
            &HOOK_CHOICES,
            HookChoice::RunAndContinue,
        )
    })
}

/// The user's response to the two-way optional-hook prompt (HOOK-52).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionalChoice {
    Run,
    Skip,
}

/// The replies of the two-way prompt (HOOK-52, CLI-257): run or skip.
const OPTIONAL_CHOICES: [crate::prompt::Choice<OptionalChoice>; 2] = [
    crate::prompt::Choice {
        keys: &["y", "yes"],
        value: OptionalChoice::Run,
    },
    crate::prompt::Choice {
        keys: &["n", "no"],
        value: OptionalChoice::Skip,
    },
];

/// [`read_choice`] for the two-way prompt (HOOK-52).
#[cfg(test)]
fn read_optional_choice<R: BufRead>(mut reader: R) -> Result<OptionalChoice> {
    crate::prompt::ask_from(
        &mut reader,
        &mut std::io::sink(),
        "",
        &OPTIONAL_CHOICES,
        OptionalChoice::Run,
    )
}

/// Print the disclosure and the two optional-hook choices, then ask until a
/// valid reply (HOOK-52, CLI-257). Mirrors `prompt_choice`.
pub fn prompt_choice_optional(disclosure: &str) -> Result<OptionalChoice> {
    // spec: TUI-44
    crate::prompt::guard("running a hook")?;
    // spec: PRG-5
    crate::progress::suspend(|| {
        print!("{disclosure}");
        println!("  [Y] run   [n] skip");
        let stdin = std::io::stdin();
        crate::prompt::ask_from(
            &mut stdin.lock(),
            &mut std::io::stdout(),
            "Run this optional hook? [Y/n] (default Y): ",
            &OPTIONAL_CHOICES,
            OptionalChoice::Run,
        )
    })
}

/// The action chosen for a hook: the decision ladder shared by every source-hook
/// site. `Abort` is reached only by a required hook the user declines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookAct {
    Run,
    Skip,
    Abort,
}

/// Resolve whether to run a hook from its disclosure and flags: a
/// `--accept-hooks` run is unattended (HOOK-23), a non-TTY skips (HOOK-22),
/// an optional hook prompts two-way (run/skip, HOOK-52), and a required hook
/// prompts three-way (run/skip/abort, HOOK-20). An optional hook never aborts.
///
/// `key` is the hook's identity within the run: when a unified plan listed it,
/// the plan's answer decides it without a prompt (HOOK-181), unless that
/// answer was to review each hook. An unlisted hook is prompted (HOOK-185).
pub fn decide(
    key: &crate::consent::HookKey,
    disclosure: &str,
    optional: bool,
    accepted: bool,
) -> Result<HookAct> {
    if accepted {
        return Ok(HookAct::Run);
    }
    if !is_tty() {
        return Ok(HookAct::Skip);
    }
    // spec: HOOK-181 HOOK-185
    match crate::consent::answer_for(key) {
        Some(crate::consent::Answer::RunAll) => return Ok(HookAct::Run),
        Some(crate::consent::Answer::SkipAll) => return Ok(HookAct::Skip),
        Some(crate::consent::Answer::Review) | None => {}
    }
    if optional {
        return Ok(match prompt_choice_optional(disclosure)? {
            OptionalChoice::Run => HookAct::Run,
            OptionalChoice::Skip => HookAct::Skip,
        });
    }
    Ok(match prompt_choice(disclosure)? {
        HookChoice::RunAndContinue => HookAct::Run,
        HookChoice::SkipAndContinue => HookAct::Skip,
        HookChoice::Abort => HookAct::Abort,
    })
}

/// Like `disclosure_text` but prefixed with the hook's label, its lifecycle
/// event, and whether it is required or optional, for the multi-hook
/// disclosures (HOOK-52). Prepends a `====== hook: {label} ======` header so the
/// block is visually distinct.
///
/// spec: HOOK-20 HOOK-120 -- the `Event:` line is what tells the user WHICH
/// step they are approving. Without it an update hook's disclosure is
/// indistinguishable from an install hook's (and an uninstall hook's from
/// either), on the one surface where the answer decides whether arbitrary
/// source code runs.
///
/// `event` is `&'static str`, mirroring `run_hook`'s `event` parameter: it is
/// mind's own word ("install"/"update"/"uninstall"), fixed by the call site
/// and never by the source, never `label` (the next parameter, which IS
/// source-controlled and IS sanitized below). The `'static` bound makes that
/// distinction a type-level fact instead of only a comment, so transposing
/// the two arguments at a call site fails to compile rather than silently
/// putting an unsanitized source string into the consent block.
#[allow(clippy::too_many_arguments)]
pub fn hook_disclosure_text(
    label: &str,
    event: &'static str,
    optional: bool,
    identity: &str,
    pin_desc: &str,
    commit: &str,
    clone_path: &str,
    command: &str,
    declared_override: Option<&str>,
    browse_url: Option<&str>,
) -> String {
    // Sanitize label for the header and "Hook:" lines; disclosure_body
    // sanitizes identity and the remaining body fields independently (HOOK-91).
    let label_clean = crate::sanitize::strip_ansi(label);
    let kind = if optional { "optional" } else { "required" };
    let mut out = String::new();
    out.push_str("====== hook: ");
    out.push_str(&label_clean);
    out.push_str(" ======\n");
    out.push_str("  Hook:      ");
    out.push_str(&label_clean);
    out.push_str(" (");
    out.push_str(kind);
    out.push_str(")\n");
    // The event is `mind`'s own word (install/update/uninstall/build), not
    // source-derived, so it needs no sanitizing.
    out.push_str("  Event:     ");
    out.push_str(event);
    out.push('\n');
    // Append the base disclosure fields (without its own header since we
    // already prepended one above; call the inner builder directly).
    out.push_str(&disclosure_body(
        identity,
        pin_desc,
        commit,
        clone_path,
        command,
        declared_override,
        browse_url,
    ));
    out
}

/// The fields-only portion of a disclosure block (no header line). Used by
/// both `disclosure_text` (which prepends its own header) and
/// `hook_disclosure_text` (which prepends a different header then calls this).
///
/// All source-derived fields are sanitized (ANSI/control/bidi stripped) before
/// being included in the returned string (HOOK-91). When `browse_url` is
/// `Some`, a `Browse:` line is emitted after `Clone:` (HOOK-24).
fn disclosure_body(
    identity: &str,
    pin_desc: &str,
    commit: &str,
    clone_path: &str,
    command: &str,
    declared_override: Option<&str>,
    browse_url: Option<&str>,
) -> String {
    // Sanitize all source-derived fields: ANSI escapes, C0/DEL/C1 control
    // characters, and bidi-override code points are stripped so a malicious
    // source cannot use cursor/line-clear sequences or bidi reordering to make
    // a dangerous command appear innocuous on the exact surface where the user
    // consents to run it (HOOK-91, S8).
    let identity = crate::sanitize::strip_ansi(identity);
    let pin_desc = crate::sanitize::strip_ansi(pin_desc);
    let commit = crate::sanitize::strip_ansi(commit);
    let clone_path = crate::sanitize::strip_ansi(clone_path);
    let command = crate::sanitize::strip_ansi(command);
    let declared_override_owned: Option<String> =
        declared_override.map(crate::sanitize::strip_ansi);
    let declared_override = declared_override_owned.as_deref();
    // spec: HOOK-24, HOOK-91 - browse URL is source-derived and must be sanitized.
    let browse_url_owned: Option<String> = browse_url.map(crate::sanitize::strip_ansi);
    let browse_url = browse_url_owned.as_deref();

    let mut out = String::new();

    out.push_str("  Source:    ");
    out.push_str(&identity);
    out.push('\n');

    out.push_str("  Pin:       ");
    out.push_str(&pin_desc);
    out.push('\n');

    out.push_str("  Commit:    ");
    out.push_str(&commit);
    out.push('\n');

    out.push_str("  Clone:     ");
    out.push_str(&clone_path);
    out.push('\n');

    // spec: HOOK-24 - emit Browse: line only when a URL is available.
    if let Some(url) = browse_url {
        out.push_str("  Browse:    ");
        out.push_str(url);
        out.push('\n');
    }

    if let Some(declared) = declared_override {
        out.push_str("  Declared:  ");
        out.push_str(declared);
        out.push('\n');
        out.push_str("  Override:  ");
        out.push_str(&command);
        out.push('\n');
        out.push_str("  NOTE: the user-supplied command replaces the source's declared command.\n");
    } else {
        out.push_str("  Command:   ");
        out.push_str(&command);
        out.push('\n');
    }

    out.push('\n');
    out.push_str("  WARNING: this executes arbitrary code from the source with your privileges.\n");

    out
}

/// Apply a user-supplied hook override for one event (HOOK-56, HOOK-59).
///
/// Replaces every hook of `event` in `resolved` with one required hook of that
/// event running `supplied`, leaving the other event's hooks in their order.
/// `supplied` is the user command (None or empty/whitespace => no override).
/// Returns the resulting hook list plus, when the override replaced declared
/// hook(s) of that event, the list of declared commands it replaced (for the
/// loud override note). `meld --install-hook` uses `Install`; `unmeld
/// --uninstall-hook` uses `Uninstall`.
pub fn apply_hook_override(
    resolved: Vec<crate::mindfile::ResolvedHook>,
    supplied: Option<&str>,
    event: crate::mindfile::HookEvent,
) -> (Vec<crate::mindfile::ResolvedHook>, Option<Vec<String>>) {
    use crate::mindfile::ResolvedHook;

    // Treat empty/whitespace as absent.
    let effective = match supplied.map(str::trim).filter(|s| !s.is_empty()) {
        Some(s) => s,
        None => return (resolved, None),
    };

    // Split into the overridden event's commands vs. the other event's hooks.
    let mut replaced: Vec<String> = Vec::new();
    let mut others: Vec<ResolvedHook> = Vec::new();
    for hook in resolved {
        if hook.event == event {
            replaced.push(hook.run);
        } else {
            others.push(hook);
        }
    }

    // Result: the override hook first, then the untouched other-event hooks.
    let override_hook = ResolvedHook {
        run: effective.to_owned(),
        name: None,
        optional: false,
        event,
    };
    let mut result = Vec::with_capacity(1 + others.len());
    result.push(override_hook);
    result.extend(others);

    let replaced = if replaced.is_empty() {
        None
    } else {
        Some(replaced)
    };
    (result, replaced)
}

/// Apply a `meld --install-hook` override to a source's resolved hooks (HOOK-56):
/// `apply_hook_override` specialized to the install event.
pub fn apply_install_override(
    resolved: Vec<crate::mindfile::ResolvedHook>,
    supplied: Option<&str>,
) -> (Vec<crate::mindfile::ResolvedHook>, Option<Vec<String>>) {
    apply_hook_override(resolved, supplied, crate::mindfile::HookEvent::Install)
}

/// Run `command` via the shell (`sh -c <command>`) in `clone_dir` (HOOK-30).
/// Stdout and stderr are INHERITED, so the hook's output reaches the terminal
/// as it is produced rather than being collected and replayed at exit. Stdin is
/// closed so a hook cannot consume mind's input. A non-zero exit (or spawn
/// failure) maps to `MindError::HookFailed`.
///
/// Streaming is the point: a hook is often the slowest step of a meld (a build,
/// a package install), and a progress bar, a compiler's file-by-file output, or
/// a prompt-looking line that arrives only after the command finishes tells the
/// user nothing while they are waiting, and cannot be interrupted on the basis
/// of what it says. The cost is that the two streams interleave exactly as they
/// would in a terminal, so they can no longer be framed under separate
/// `hook-stdout`/`hook-stderr` labels, and the frame is unconditional: nothing
/// is buffered, so mind cannot know in advance whether the hook will print.
///
/// The frame below is a plain `println!` on purpose, NOT `render::note`: what
/// it surrounds is arbitrary text chosen by the source author, so no per-line
/// routing rule could bound it (a hook that printed `note:`-prefixed lines, or
/// a forged result envelope, would defeat one). Under `--json`, `main.rs`'s
/// `json_stdout` points fd 1 at fd 2 for the whole run (a real `dup2`) and
/// marks the saved real stdout close-on-exec, so no descriptor that reaches
/// the result document is inherited by the child: a streaming hook cannot
/// corrupt the result document either.
///
/// `event` is what the hook is ("install", "uninstall", "build") and is fixed
/// by the call site, never by the source. `label` is what the frame is headed
/// with and IS source-controlled (a `[[hooks]].name` from `mind.toml`, or the
/// raw `run` command when there is none), so it is sanitized (`strip_ansi`,
/// DSC-95) before it reaches the frame or any `HookFailed` this returns:
/// unsanitized, a hook name carrying cursor-control escapes could erase mind's
/// own progress output the moment the frame opens. Keeping the two apart is
/// what stops a failing uninstall hook from being reported as an install one.
///
/// `env` carries the profile variables the child runs with (HOOK-140).
///
/// Every call files one [`crate::hook_log::HookRecord`] (HOOK-160): `ok` on a
/// zero exit, `failed` otherwise, with the exit code or signal and the run
/// time. The closing frame line carries the same status (HOOK-162). When
/// output logging is on (HOOK-165) the streams are piped instead of inherited
/// and copied to both the terminal and the hook's log file; see [`run_teed`].
///
/// The hook writes to the terminal, so no progress spinner is drawn while it
/// runs: its framed output is its progress (PRG-5).
// spec: CLI-217 HOOK-30 HOOK-140 HOOK-160 HOOK-162 HOOK-165 PRG-5
pub fn run_hook(
    command: &str,
    clone_dir: &Path,
    identity: &str,
    event: &'static str,
    label: &str,
    env: &HookEnv,
    site: crate::hook_log::Site,
) -> Result<()> {
    crate::progress::suspend(|| {
        run_hook_framed(command, clone_dir, identity, event, label, env, site)
    })
}

/// [`run_hook`] without the progress suspension.
fn run_hook_framed(
    command: &str,
    clone_dir: &Path,
    identity: &str,
    event: &'static str,
    label: &str,
    env: &HookEnv,
    site: crate::hook_log::Site,
) -> Result<()> {
    use crate::hook_log::Outcome;

    let label = crate::sanitize::strip_ansi(label);
    let command_clean = crate::sanitize::strip_ansi(command);
    let mut record = crate::hook_log::base(identity, site, event, &label, command, Outcome::Ok);
    let log = crate::hook_log::open_log(identity, site, event, &label, command);
    record.log = log.as_ref().map(|l| l.path.display().to_string());

    // Flush mind's own buffered output first so it does not interleave with
    // the streamed hook output below.
    let _ = std::io::stdout().flush();

    // Opened before the spawn so the header is on screen while the hook runs,
    // not after it finishes.
    println!("====== (hook: {label}) ======");
    let _ = std::io::stdout().flush();

    let started = std::time::Instant::now();
    let mut cmd = Command::new("sh");
    cmd.arg("-c")
        .arg(command)
        .envs(env.vars())
        .current_dir(clone_dir)
        .stdin(Stdio::null());
    // spec: HOOK-171 -- a Ctrl-C reaches the hook (same process group) and
    // `mind`; catching it here lets `mind` outlive the hook to record it.
    let sigint = interrupt::catch();
    let spawned = match log {
        Some(log) => run_teed(&mut cmd, log, started),
        None => cmd
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .map(|s| (s, started.elapsed())),
    };
    let interrupted = sigint.taken();
    drop(sigint);
    let (status, ran_for) = match spawned {
        Ok(done) => done,
        Err(e) => {
            // The spawn never ran, so the frame opened above is left dangling
            // unless we close it here too (L2): HOOK-30 describes the frame as
            // a pair, and the opener must still print before the spawn is
            // attempted (so the header is visible while mind decides whether
            // the spawn will even succeed).
            println!("====== (end hook: {label}) ======");
            // The log was opened before the spawn; end it like any other
            // (HOOK-165), with why there is no exit status.
            if let Some(path) = &record.log
                && let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path)
            {
                let _ = writeln!(f, "# not started: {e}");
            }
            record.outcome = Outcome::Failed;
            record.error = Some(e.to_string());
            crate::hook_log::file(record);
            return Err(MindError::HookFailed {
                event,
                label: label.clone(),
                identity: identity.to_string(),
                command: command_clean.clone(),
                status: None,
                reason: e.to_string(),
                // Spawn failed, so nothing was streamed: the error carries the
                // reason itself rather than pointing at output that never existed.
                streamed: false,
            });
        }
    };

    record.duration_ms = Some(ran_for.as_millis().min(u128::from(u64::MAX)) as u64);
    record.exit_code = status.code();
    record.signal = exit_signal(&status);
    if interrupted {
        record.outcome = Outcome::Interrupted;
    } else if !status.success() {
        record.outcome = Outcome::Failed;
    }
    // spec: HOOK-170 -- a successful hook's log goes when only failures are kept.
    if record.outcome == Outcome::Ok
        && crate::hook_log::keeps_failed_only()
        && let Some(path) = record.log.take()
    {
        crate::hook_log::discard_log(Path::new(&path));
    }
    println!(
        "====== (end hook: {label}, {}) ======",
        record.status_text()
    );
    if let Some(path) = &record.log {
        crate::render::note(format!("note: hook output saved to {path}"));
    }
    crate::hook_log::file(record);

    if interrupted {
        // spec: HOOK-171 -- stop the verb, whatever the hook's exit: the user
        // asked `mind` to stop, not only the hook.
        return Err(MindError::HookInterrupted {
            event,
            label,
            identity: identity.to_string(),
        });
    }
    if status.success() {
        Ok(())
    } else {
        // The hook wrote straight to the terminal, so there is nothing to
        // replay and nothing captured to attach: whatever it said is already on
        // screen inside the frame above. `streamed` means "the process ran",
        // not "it printed something": with inherited streams mind never saw a
        // byte, so it cannot tell those apart, and the message says where
        // output WOULD be rather than asserting that any exists (HOOK-30).
        Err(MindError::HookFailed {
            event,
            label,
            identity: identity.to_string(),
            command: command_clean,
            status: Some(status),
            reason: String::new(),
            streamed: true,
        })
    }
}

/// How long the output copiers may keep draining after the hook exits. A hook
/// that starts a background process can leave that process holding the pipes
/// open; past this grace period `mind` stops waiting and moves on, and the
/// copiers keep writing whatever still arrives until the pipe closes or `mind`
/// exits.
const TEE_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

/// Run `cmd` with its stdout and stderr piped, copying each as it arrives to
/// `mind`'s own stdout/stderr (so output still streams live) and to `log`
/// (HOOK-165). Log lines are tagged `out | ` / `err | ` and written in arrival
/// order; the two streams' relative order is as close as two pipes allow, not
/// exact. The log ends with the exit status. Returns the status and the time
/// from `started` to the hook's exit.
///
/// A piped hook no longer sees a terminal, so a tool that changes its output
/// for one (color, progress bars) behaves as it would in a pipe. A background
/// process the hook leaves writing to those pipes loses its reader when `mind`
/// exits, and a later write fails (`SIGPIPE`/`EPIPE`) where it would have
/// reached the terminal. That is why logging is opt-in.
fn run_teed(
    cmd: &mut Command,
    log: crate::hook_log::Log,
    started: std::time::Instant,
) -> std::io::Result<(std::process::ExitStatus, std::time::Duration)> {
    use std::io::Read;
    use std::sync::{Arc, Mutex, mpsc};

    let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
    let file = Arc::new(Mutex::new(log.file));
    let (done_tx, done_rx) = mpsc::channel::<()>();

    let spawn_copier = |mut src: Box<dyn Read + Send>, tag: &'static str, to_stderr: bool| {
        let file = Arc::clone(&file);
        let done = done_tx.clone();
        std::thread::spawn(move || {
            let mut buf = [0u8; 8192];
            let mut line: Vec<u8> = Vec::new();
            let write_line = |line: &[u8]| {
                let mut f = file.lock().unwrap_or_else(|e| e.into_inner());
                let _ = f.write_all(tag.as_bytes());
                let _ = f.write_all(line);
                let _ = f.write_all(b"\n");
            };
            loop {
                let n = match src.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => n,
                };
                let chunk = &buf[..n];
                if to_stderr {
                    let mut e = std::io::stderr().lock();
                    let _ = e.write_all(chunk);
                    let _ = e.flush();
                } else {
                    let mut o = std::io::stdout().lock();
                    let _ = o.write_all(chunk);
                    let _ = o.flush();
                }
                split_log_lines(&mut line, chunk, &write_line);
            }
            if !line.is_empty() {
                write_line(&line);
            }
            let _ = done.send(());
        })
    };

    let mut copiers = 0;
    if let Some(out) = child.stdout.take() {
        spawn_copier(Box::new(out), "out | ", false);
        copiers += 1;
    }
    if let Some(err) = child.stderr.take() {
        spawn_copier(Box::new(err), "err | ", true);
        copiers += 1;
    }
    drop(done_tx);

    let status = child.wait()?;
    // The run time ends at the hook's exit, not after the drain below.
    let ran_for = started.elapsed();
    let deadline = std::time::Instant::now() + TEE_GRACE;
    for _ in 0..copiers {
        let left = deadline.saturating_duration_since(std::time::Instant::now());
        if done_rx.recv_timeout(left).is_err() {
            break;
        }
    }

    let mut f = file.lock().unwrap_or_else(|e| e.into_inner());
    let end = match (status.code(), exit_signal(&status)) {
        (Some(code), _) => format!("exit {code}"),
        (None, Some(sig)) => format!("signal {sig}"),
        (None, None) => "exited".to_string(),
    };
    let _ = writeln!(f, "# {end}");
    Ok((status, ran_for))
}

/// The longest log line [`run_teed`] holds before writing it out (HOOK-165).
/// Output with no newline (a `\r` progress bar, binary data) would otherwise
/// grow the pending line without bound; past this it is written as a line of
/// its own and the rest continues on the next, tagged again.
const LOG_LINE_MAX: usize = 64 * 1024;

/// Append `chunk` to the pending `line`, calling `emit` with each complete
/// line (without its `\n`) and with each [`LOG_LINE_MAX`]-byte piece of an
/// overlong one. Whatever follows the last newline stays in `line`.
// spec: HOOK-165
fn split_log_lines(line: &mut Vec<u8>, chunk: &[u8], mut emit: impl FnMut(&[u8])) {
    for &b in chunk {
        if b == b'\n' {
            emit(line);
            line.clear();
        } else {
            line.push(b);
            if line.len() >= LOG_LINE_MAX {
                emit(line);
                line.clear();
            }
        }
    }
}

/// Catching Ctrl-C (SIGINT) for the length of one hook (HOOK-171).
///
/// The terminal sends SIGINT to the whole foreground process group, so the
/// hook gets it as usual and `mind`, instead of dying with it, notes it and
/// waits for the hook to exit. A caught signal's handler is reset to the
/// default across `exec`, so the hook still sees the default disposition. When
/// SIGINT is already ignored (a background job started with `&` by a
/// non-interactive shell), nothing is installed: the hook inherits the ignore,
/// as it always did. A second Ctrl-C while the hook still runs (one that traps
/// or ignores SIGINT) ends `mind` at once, as the default disposition would.
mod interrupt {
    use std::sync::atomic::{AtomicBool, Ordering};

    static HIT: AtomicBool = AtomicBool::new(false);

    /// Restores the previous SIGINT disposition when dropped.
    pub struct Guard {
        #[cfg(unix)]
        old: Option<libc::sigaction>,
    }

    #[cfg(unix)]
    extern "C" fn on_sigint(_: libc::c_int) {
        if HIT.swap(true, Ordering::SeqCst) {
            // spec: HOOK-171 -- the second Ctrl-C: die of it. `signal` and
            // `raise` are async-signal-safe; the raised SIGINT is blocked until
            // this handler returns, then delivered with the default action.
            // SAFETY: resets SIGINT to its default and re-raises it.
            unsafe {
                libc::signal(libc::SIGINT, libc::SIG_DFL);
                libc::raise(libc::SIGINT);
            }
        }
    }

    #[cfg(not(unix))]
    pub fn catch() -> Guard {
        HIT.store(false, Ordering::SeqCst);
        Guard {}
    }

    #[cfg(unix)]
    pub fn catch() -> Guard {
        HIT.store(false, Ordering::SeqCst);
        // SAFETY: plain sigaction calls on zeroed structs; the handler only
        // stores to an atomic, which is async-signal-safe.
        unsafe {
            let mut old: libc::sigaction = std::mem::zeroed();
            if libc::sigaction(libc::SIGINT, std::ptr::null(), &mut old) != 0
                || old.sa_sigaction == libc::SIG_IGN
            {
                return Guard { old: None };
            }
            let mut new: libc::sigaction = std::mem::zeroed();
            new.sa_sigaction = on_sigint as extern "C" fn(libc::c_int) as libc::sighandler_t;
            libc::sigemptyset(&mut new.sa_mask);
            new.sa_flags = libc::SA_RESTART;
            if libc::sigaction(libc::SIGINT, &new, std::ptr::null_mut()) != 0 {
                return Guard { old: None };
            }
            Guard { old: Some(old) }
        }
    }

    impl Guard {
        /// Whether a SIGINT arrived since [`catch`].
        pub fn taken(&self) -> bool {
            HIT.load(Ordering::SeqCst)
        }
    }

    impl Drop for Guard {
        fn drop(&mut self) {
            #[cfg(unix)]
            if let Some(old) = &self.old {
                // SAFETY: restores the disposition saved by `catch`.
                unsafe {
                    libc::sigaction(libc::SIGINT, old, std::ptr::null_mut());
                }
            }
        }
    }
}

#[cfg(unix)]
fn exit_signal(status: &std::process::ExitStatus) -> Option<i32> {
    use std::os::unix::process::ExitStatusExt;
    status.signal()
}

#[cfg(not(unix))]
fn exit_signal(_: &std::process::ExitStatus) -> Option<i32> {
    None
}

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

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

    /// `decide` runs unattended under `--accept-hooks` (HOOK-23) and skips in
    /// a non-TTY context (HOOK-22) without prompting, for both optional and
    /// required hooks. (The interactive run/skip/abort branches need a TTY and are
    /// covered by the prompt-parsing tests.)
    // spec: HOOK-22, HOOK-23
    #[test]
    fn decide_accepted_runs_and_non_tty_skips() {
        let key = crate::consent::HookKey::source_hook("s", "install", "make");
        // accepted => Run regardless of optionality (no prompt).
        assert_eq!(decide(&key, "d", false, true).unwrap(), HookAct::Run);
        assert_eq!(decide(&key, "d", true, true).unwrap(), HookAct::Run);
        // Test runs with no TTY on stdout, so a non-skip decision is Skip, never
        // Abort or Run (HOOK-22: never run silently).
        assert_eq!(decide(&key, "d", false, false).unwrap(), HookAct::Skip);
        assert_eq!(decide(&key, "d", true, false).unwrap(), HookAct::Skip);
    }

    /// `Accept` answers per event: each field gates only its own event, and an
    /// unknown event spelling is never accepted.
    // spec: HOOK-150
    #[test]
    fn accept_gates_each_event_on_its_own() {
        use crate::mindfile::HookEvent;
        let none = Accept::default();
        for e in [HookEvent::Install, HookEvent::Update, HookEvent::Uninstall] {
            assert!(!none.event(e));
            assert!(Accept::ALL.event(e));
        }
        let update = Accept {
            update: true,
            ..Accept::default()
        };
        assert!(update.event(HookEvent::Update));
        assert!(!update.event(HookEvent::Install));
        assert!(!update.event(HookEvent::Uninstall));
        assert!(update.event_str("update"));
        assert!(!update.event_str("install"));
        assert!(!update.event_str("build"));
        assert!(
            Accept {
                build: true,
                ..Accept::default()
            }
            .event_str("build")
        );
        assert!(!Accept::ALL.event_str("deploy"));
    }

    /// `$MIND_TTY` is read as a boolean: the falsey spellings mean "not a
    /// terminal" and everything else means "a terminal". Driven through the
    /// pure mapping so no process-wide env mutation is needed (the variable
    /// itself is exercised end to end by the `hooks run` integration tests).
    // spec: HOOK-109
    #[test]
    fn tty_override_reads_a_boolean() {
        use std::ffi::OsStr;
        for falsey in ["", "0", "false", "FALSE", "no", "off", "  0  "] {
            assert!(
                !tty_override(OsStr::new(falsey)),
                "{falsey:?} must read as not-a-terminal"
            );
        }
        for truthy in ["1", "true", "TRUE", "yes", "on", "anything"] {
            assert!(
                tty_override(OsStr::new(truthy)),
                "{truthy:?} must read as a terminal"
            );
        }
    }

    /// RAII guard that removes a temp directory when dropped.
    /// Uses process id + atomic counter to avoid collisions between parallel or
    /// stale runs.
    struct TempDir(std::path::PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            let n = COUNTER.fetch_add(1, Ordering::SeqCst);
            let path = std::env::temp_dir().join(format!(
                "mind-hook-test-{}-{}-{n}",
                std::process::id(),
                tag
            ));
            fs::create_dir_all(&path).expect("create temp dir");
            TempDir(path)
        }

        fn path(&self) -> &std::path::Path {
            &self.0
        }
    }

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

    // ---- read_choice ----

    // spec: HOOK-20
    #[test]
    fn read_choice_accepts_each_reply_in_any_case() {
        let read = |s: &str| read_choice(std::io::Cursor::new(s.to_string())).unwrap();
        assert_eq!(read("Y\n"), HookChoice::RunAndContinue);
        assert_eq!(read(" yes \n"), HookChoice::RunAndContinue);
        assert_eq!(read("N\n"), HookChoice::SkipAndContinue);
        assert_eq!(read("\ta\n"), HookChoice::Abort);
    }

    // spec: HOOK-20 CLI-257
    // An unrecognized reply neither runs nor skips: it is asked again, and the
    // next valid reply decides.
    #[test]
    fn read_choice_asks_again_after_an_unrecognized_reply() {
        let reader = std::io::Cursor::new("garbage\n1\nn\n");
        let result = read_choice(reader).expect("read_choice should not error");
        assert_eq!(result, HookChoice::SkipAndContinue);
    }

    // spec: HOOK-20 CLI-258
    // EOF takes the default, run. Only a TTY reaches the prompt (HOOK-22), so
    // EOF here is the user's Ctrl-D.
    #[test]
    fn read_choice_eof_takes_the_default() {
        let reader = std::io::Cursor::new("");
        let result = read_choice(reader).expect("read_choice should not error on EOF");
        assert_eq!(result, HookChoice::RunAndContinue);
    }

    // spec: HOOK-20
    // "y\n" through the read path must produce RunAndContinue.
    #[test]
    fn read_choice_run_and_continue_on_y() {
        let reader = std::io::Cursor::new("y\n");
        let result = read_choice(reader).expect("read_choice should not error");
        assert_eq!(result, HookChoice::RunAndContinue);
    }

    // spec: HOOK-20
    // "n\n" through the read path must produce SkipAndContinue.
    #[test]
    fn read_choice_skip_and_continue_on_n() {
        let reader = std::io::Cursor::new("n\n");
        let result = read_choice(reader).expect("read_choice should not error");
        assert_eq!(result, HookChoice::SkipAndContinue);
    }

    // spec: HOOK-20
    // A bare "\n" (interactive Enter) through the read path must produce
    // RunAndContinue - the default-run behavior.
    #[test]
    fn read_choice_run_and_continue_on_bare_newline() {
        let reader = std::io::Cursor::new("\n");
        let result = read_choice(reader).expect("read_choice should not error");
        assert_eq!(
            result,
            HookChoice::RunAndContinue,
            "bare Enter must yield RunAndContinue (default Y)"
        );
    }

    // spec: HOOK-20
    // "a\n" through the read path must produce Abort.
    #[test]
    fn read_choice_abort_on_a() {
        let reader = std::io::Cursor::new("a\n");
        let result = read_choice(reader).expect("read_choice should not error");
        assert_eq!(result, HookChoice::Abort);
    }

    // ---- read_optional_choice ----

    // spec: HOOK-52 CLI-257
    #[test]
    fn read_optional_choice_asks_again_after_an_unrecognized_reply() {
        let reader = std::io::Cursor::new("garbage\n a \n N \n");
        let result = read_optional_choice(reader).expect("no error");
        assert_eq!(
            result,
            OptionalChoice::Skip,
            "`a` is not an optional-hook reply"
        );
    }

    // spec: HOOK-52
    // "y\n" through the read path must produce Run.
    #[test]
    fn read_optional_choice_run_on_y() {
        let reader = std::io::Cursor::new("y\n");
        let result = read_optional_choice(reader).expect("no error");
        assert_eq!(result, OptionalChoice::Run);
    }

    // spec: HOOK-52
    // "n\n" through the read path must produce Skip.
    #[test]
    fn read_optional_choice_skip_on_n() {
        let reader = std::io::Cursor::new("n\n");
        let result = read_optional_choice(reader).expect("no error");
        assert_eq!(result, OptionalChoice::Skip);
    }

    // spec: HOOK-52 CLI-258
    // EOF takes the default, run (only a TTY reaches the prompt, HOOK-22).
    #[test]
    fn read_optional_choice_eof_takes_the_default() {
        let reader = std::io::Cursor::new("");
        let result = read_optional_choice(reader).expect("no error on EOF");
        assert_eq!(result, OptionalChoice::Run);
    }

    // spec: HOOK-52
    // A bare "\n" (interactive Enter) through the read path must produce Run.
    #[test]
    fn read_optional_choice_run_on_bare_newline() {
        let reader = std::io::Cursor::new("\n");
        let result = read_optional_choice(reader).expect("no error");
        assert_eq!(
            result,
            OptionalChoice::Run,
            "bare Enter must yield Run (default Y)"
        );
    }

    // ---- disclosure_text ----

    // spec: HOOK-2
    #[test]
    fn disclosure_text_contains_separator_header() {
        let text = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/home/user/.mind/sources/github.com/acme/tools",
            "make install",
            None,
            None,
        );
        assert!(
            text.starts_with("====== hook: github.com/acme/tools ======\n"),
            "disclosure_text must start with the separator header; got: {text}"
        );
    }

    // spec: HOOK-2
    #[test]
    fn disclosure_text_contains_required_fields() {
        let text = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/home/user/.mind/sources/github.com/acme/tools",
            "make install",
            None,
            None,
        );
        assert!(text.contains("github.com/acme/tools"), "missing identity");
        assert!(text.contains("main"), "missing pin_desc");
        assert!(text.contains("abc1234"), "missing commit");
        assert!(
            text.contains("/home/user/.mind/sources/github.com/acme/tools"),
            "missing clone_path"
        );
        assert!(text.contains("make install"), "missing command");
        assert!(text.contains("arbitrary"), "missing arbitrary-code warning");
    }

    // spec: HOOK-2
    #[test]
    fn disclosure_text_override_shows_both_commands_and_replacement_note() {
        let text = disclosure_text(
            "github.com/acme/tools",
            "v1.0",
            "def5678",
            "/tmp/clone",
            "./user-custom.sh",
            Some("make install"),
            None,
        );
        // Both commands must appear.
        assert!(text.contains("make install"), "missing declared command");
        assert!(
            text.contains("./user-custom.sh"),
            "missing override command"
        );
        // Replacement statement must appear.
        assert!(
            text.contains("replaces"),
            "missing replacement statement; text: {text}"
        );
        // Arbitrary-code warning must appear.
        assert!(text.contains("arbitrary"), "missing arbitrary-code warning");
    }

    // spec: HOOK-2
    #[test]
    fn disclosure_text_no_override_does_not_mention_replacement() {
        let text = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            None,
        );
        assert!(
            !text.contains("replaces"),
            "should not mention replacement when no override"
        );
    }

    // spec: HOOK-2
    // disclosure_text must produce the same output as composing the header plus
    // disclosure_body directly. This guards the L1 DRY refactor: one source of
    // truth for the field layout.
    #[test]
    fn disclosure_text_matches_header_plus_disclosure_body() {
        let identity = "github.com/acme/tools";
        let pin_desc = "main";
        let commit = "abc1234";
        let clone_path = "/home/user/.mind/sources/github.com/acme/tools";
        let command = "make install";

        let via_fn = disclosure_text(identity, pin_desc, commit, clone_path, command, None, None);

        let mut expected = String::new();
        expected.push_str("====== hook: ");
        expected.push_str(identity);
        expected.push_str(" ======\n");
        expected.push_str(&disclosure_body(
            identity, pin_desc, commit, clone_path, command, None, None,
        ));

        assert_eq!(
            via_fn, expected,
            "disclosure_text output must equal header + disclosure_body"
        );
    }

    // spec: HOOK-91
    // Source-derived fields containing ANSI escapes and bidi-override code points
    // must be stripped from the produced disclosure string before it reaches the
    // terminal where the user consents to run the hook.
    #[test]
    fn disclosure_sanitizes_ansi_and_bidi_in_source_fields() {
        // The ESC byte (0x1b) starts ANSI sequences; U+202E is a bidi-override.
        let ansi_command = "\x1b[2K\x1b[1A rm -rf /  \x1b[0m";
        let bidi_identity = "github.com/\u{202E}kcal/evil\u{202E}";

        // Test disclosure_text: checks identity in header and command in body.
        let text = disclosure_text(
            bidi_identity,
            "main",
            "abc1234",
            "/tmp/clone",
            ansi_command,
            None,
            None,
        );
        assert!(
            !text.contains('\x1b'),
            "disclosure_text must not contain raw ESC byte; got: {text:?}"
        );
        assert!(
            !text.chars().any(|c| matches!(
                c,
                '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
            )),
            "disclosure_text must not contain bidi-override code points; got: {text:?}"
        );

        // Test hook_disclosure_text: label is also source-derived (hook name from mind.toml).
        let ansi_label = "\x1b[31mbuild\x1b[0m\u{202E}";
        let text2 = hook_disclosure_text(
            ansi_label,
            "install",
            false,
            bidi_identity,
            "main",
            "abc1234",
            "/tmp/clone",
            ansi_command,
            None,
            None,
        );
        assert!(
            !text2.contains('\x1b'),
            "hook_disclosure_text must not contain raw ESC byte; got: {text2:?}"
        );
        assert!(
            !text2.chars().any(|c| matches!(
                c,
                '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
            )),
            "hook_disclosure_text must not contain bidi-override code points; got: {text2:?}"
        );

        // Test with declared_override path: both declared and override commands sanitized.
        let text3 = disclosure_text(
            bidi_identity,
            "v1.0",
            "def5678",
            "/tmp/clone",
            ansi_command,
            Some("\x1b[32m malicious_decl \x1b[0m"),
            None,
        );
        assert!(
            !text3.contains('\x1b'),
            "disclosure with override must not contain raw ESC byte; got: {text3:?}"
        );

        // spec: HOOK-91 - browse URL is also source-derived and must be sanitized.
        let ansi_browse_url = "\x1b[34mhttps://github.com/evil/repo/tree/abc\u{202E}1234\x1b[0m";
        let text4 = disclosure_text(
            "github.com/evil/repo",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            Some(ansi_browse_url),
        );
        assert!(
            !text4.contains('\x1b'),
            "disclosure with browse_url must not contain raw ESC byte; got: {text4:?}"
        );
        assert!(
            !text4.chars().any(|c| matches!(
                c,
                '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
            )),
            "disclosure with browse_url must not contain bidi-override code points; got: {text4:?}"
        );
    }

    // spec: HOOK-2
    // Same as above but with a declared_override, to cover the override branch.
    #[test]
    fn disclosure_text_matches_header_plus_disclosure_body_with_override() {
        let identity = "github.com/acme/tools";
        let pin_desc = "v1.0";
        let commit = "def5678";
        let clone_path = "/tmp/clone";
        let command = "./user-custom.sh";
        let declared = "make install";

        let via_fn = disclosure_text(
            identity,
            pin_desc,
            commit,
            clone_path,
            command,
            Some(declared),
            None,
        );

        let mut expected = String::new();
        expected.push_str("====== hook: ");
        expected.push_str(identity);
        expected.push_str(" ======\n");
        expected.push_str(&disclosure_body(
            identity,
            pin_desc,
            commit,
            clone_path,
            command,
            Some(declared),
            None,
        ));

        assert_eq!(
            via_fn, expected,
            "disclosure_text with override must equal header + disclosure_body"
        );
    }

    // spec: HOOK-24
    // The Browse: line must appear in the disclosure when Some and be absent
    // when None, and must never appear when the URL was stripped to empty.
    #[test]
    fn disclosure_browse_url_line_present_when_some_absent_when_none() {
        // With a URL: Browse: line must appear.
        let with_url = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            Some("https://github.com/acme/tools/tree/abc1234"),
        );
        assert!(
            with_url.contains("Browse:"),
            "disclosure must contain Browse: line when browse_url is Some; got: {with_url}"
        );
        assert!(
            with_url.contains("https://github.com/acme/tools/tree/abc1234"),
            "disclosure must contain the browse URL; got: {with_url}"
        );

        // Without a URL: Browse: line must not appear.
        let without_url = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            None,
        );
        assert!(
            !without_url.contains("Browse:"),
            "disclosure must not contain Browse: line when browse_url is None; got: {without_url}"
        );
    }

    // spec: HOOK-24
    // The Browse: line is positioned immediately after the Clone: line (HOOK-24:
    // the browse URL is added alongside the clone path). Assert ordering, not
    // just presence: a regression that emitted Browse before Clone, or after the
    // command/WARNING block, would still pass a bare `contains` check.
    #[test]
    fn disclosure_browse_line_positioned_after_clone() {
        let text = disclosure_text(
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/home/user/.mind/sources/github.com/acme/tools",
            "make install",
            None,
            Some("https://github.com/acme/tools/tree/abc1234"),
        );

        let clone_at = text.find("  Clone:     ").expect("Clone line present");
        let browse_at = text.find("  Browse:    ").expect("Browse line present");
        assert!(
            browse_at > clone_at,
            "Browse: line must come after Clone: line; got: {text}"
        );

        // Nothing but the two field lines may sit between them: Browse must
        // immediately follow the Clone line (Clone value has no embedded newline
        // in this fixture), so the text between the Clone label and the Browse
        // label contains exactly one newline.
        let between = &text[clone_at..browse_at];
        assert_eq!(
            between.matches('\n').count(),
            1,
            "Browse: must be the line immediately after Clone:; got between: {between:?}"
        );

        // And the Browse line must precede the WARNING/command consent block.
        let warn_at = text
            .find("WARNING")
            .or_else(|| text.find("make install"))
            .expect("consent block present");
        assert!(
            browse_at < warn_at,
            "Browse: line must precede the command/WARNING consent block; got: {text}"
        );
    }

    // ---- hook_disclosure_text ----

    // spec: HOOK-52
    #[test]
    fn hook_disclosure_text_has_separator_header_with_label() {
        let text = hook_disclosure_text(
            "Build step",
            "install",
            true,
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            None,
        );
        assert!(
            text.starts_with("====== hook: Build step ======\n"),
            "hook_disclosure_text must start with '====== hook: <label> ======'; got: {text}"
        );
    }

    /// The consent block names the lifecycle event, so approving an update or
    /// uninstall hook is never indistinguishable from approving an install one.
    #[test]
    fn hook_disclosure_text_names_the_lifecycle_event() {
        // spec: HOOK-20 HOOK-120
        for event in ["install", "update", "uninstall"] {
            let text = hook_disclosure_text(
                "Build step",
                event,
                false,
                "github.com/acme/tools",
                "main",
                "abc1234",
                "/tmp/clone",
                "make install",
                None,
                None,
            );
            assert!(
                text.contains(&format!("Event:     {event}")),
                "the disclosure must name the {event} event: {text}"
            );
        }
    }

    // spec: HOOK-52
    #[test]
    fn hook_disclosure_text_optional_contains_label_and_optional_marker() {
        let text = hook_disclosure_text(
            "Build step",
            "install",
            true,
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "make install",
            None,
            None,
        );
        assert!(text.contains("Build step"), "missing label");
        assert!(text.contains("optional"), "missing optional marker");
        assert!(!text.contains("required"), "should not say required");
        assert!(text.contains("github.com/acme/tools"), "missing identity");
        assert!(text.contains("make install"), "missing command");
        assert!(text.contains("arbitrary"), "missing arbitrary-code warning");
    }

    // spec: HOOK-52
    #[test]
    fn hook_disclosure_text_required_contains_required_marker() {
        let text = hook_disclosure_text(
            "setup.sh",
            "install",
            false,
            "github.com/acme/tools",
            "v1.0",
            "def5678",
            "/tmp/clone",
            "setup.sh",
            None,
            None,
        );
        assert!(text.contains("setup.sh"), "missing label/command");
        assert!(text.contains("required"), "missing required marker");
        assert!(text.contains("github.com/acme/tools"), "missing identity");
        assert!(text.contains("arbitrary"), "missing arbitrary-code warning");
    }

    // spec: HOOK-52
    #[test]
    fn hook_disclosure_text_override_shows_both_commands() {
        let text = hook_disclosure_text(
            "custom.sh",
            "install",
            false,
            "github.com/acme/tools",
            "main",
            "abc1234",
            "/tmp/clone",
            "./user-custom.sh",
            Some("make install"),
            None,
        );
        assert!(text.contains("make install"), "missing declared command");
        assert!(
            text.contains("./user-custom.sh"),
            "missing override command"
        );
        assert!(text.contains("replaces"), "missing replacement note");
        assert!(text.contains("arbitrary"), "missing arbitrary-code warning");
    }

    // ---- apply_install_override ----

    // spec: HOOK-56
    #[test]
    fn apply_install_override_none_supplied_returns_unchanged() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![ResolvedHook {
            run: "make install".into(),
            name: None,
            optional: false,
            event: HookEvent::Install,
        }];
        let (result, replaced) = apply_install_override(hooks.clone(), None);
        assert_eq!(result, hooks, "hooks must be unchanged");
        assert!(replaced.is_none(), "no override => replaced is None");
    }

    // spec: HOOK-56
    #[test]
    fn apply_install_override_empty_supplied_returns_unchanged() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![ResolvedHook {
            run: "make install".into(),
            name: None,
            optional: false,
            event: HookEvent::Install,
        }];
        let (result, replaced) = apply_install_override(hooks.clone(), Some(""));
        assert_eq!(result, hooks, "empty supplied => unchanged");
        assert!(replaced.is_none());

        let (result2, replaced2) = apply_install_override(hooks.clone(), Some("   "));
        assert_eq!(result2, hooks, "whitespace supplied => unchanged");
        assert!(replaced2.is_none());
    }

    // spec: HOOK-56
    #[test]
    fn apply_install_override_replaces_declared_install_and_returns_them() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![
            ResolvedHook {
                run: "make build".into(),
                name: Some("Build".into()),
                optional: false,
                event: HookEvent::Install,
            },
            ResolvedHook {
                run: "make install".into(),
                name: None,
                optional: false,
                event: HookEvent::Install,
            },
        ];
        let (result, replaced) = apply_install_override(hooks, Some("./custom.sh"));
        // Result has exactly one install hook (the override).
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].run, "./custom.sh");
        assert_eq!(result[0].event, HookEvent::Install);
        assert!(!result[0].optional);
        assert_eq!(result[0].name, None);
        // Replaced lists both original install commands.
        let replaced = replaced.expect("should be Some when install hooks were declared");
        assert_eq!(replaced, vec!["make build", "make install"]);
    }

    // spec: HOOK-56
    #[test]
    fn apply_install_override_uninstall_hooks_survive_in_order() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![
            ResolvedHook {
                run: "make install".into(),
                name: None,
                optional: false,
                event: HookEvent::Install,
            },
            ResolvedHook {
                run: "first-uninstall".into(),
                name: Some("First".into()),
                optional: false,
                event: HookEvent::Uninstall,
            },
            ResolvedHook {
                run: "second-uninstall".into(),
                name: None,
                optional: true,
                event: HookEvent::Uninstall,
            },
        ];
        let (result, replaced) = apply_install_override(hooks, Some("./override.sh"));
        // First entry: override install hook.
        assert_eq!(result[0].run, "./override.sh");
        assert_eq!(result[0].event, HookEvent::Install);
        // Then the uninstall hooks in original order.
        assert_eq!(result[1].run, "first-uninstall");
        assert_eq!(result[1].event, HookEvent::Uninstall);
        assert_eq!(result[2].run, "second-uninstall");
        assert_eq!(result[2].event, HookEvent::Uninstall);
        assert_eq!(result.len(), 3);
        // Replaced contains the original install command.
        assert_eq!(replaced, Some(vec!["make install".to_string()]));
    }

    // spec: HOOK-56
    // When the source declared no install hooks, supplied adds one, and replaced is None.
    #[test]
    fn apply_install_override_no_declared_install_adds_hook_replaced_is_none() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![ResolvedHook {
            run: "teardown.sh".into(),
            name: None,
            optional: false,
            event: HookEvent::Uninstall,
        }];
        let (result, replaced) = apply_install_override(hooks, Some("./new-install.sh"));
        // One install hook + one uninstall hook.
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].run, "./new-install.sh");
        assert_eq!(result[0].event, HookEvent::Install);
        assert_eq!(result[1].run, "teardown.sh");
        assert_eq!(result[1].event, HookEvent::Uninstall);
        // No install hooks were declared, so replaced is None.
        assert!(
            replaced.is_none(),
            "no declared install hooks => replaced is None even when supplied is given"
        );
    }

    // spec: HOOK-59
    #[test]
    fn apply_hook_override_uninstall_replaces_uninstall_and_keeps_install() {
        use crate::mindfile::{HookEvent, ResolvedHook};
        let hooks = vec![
            ResolvedHook {
                run: "build".into(),
                name: None,
                optional: false,
                event: HookEvent::Install,
            },
            ResolvedHook {
                run: "old-teardown".into(),
                name: None,
                optional: false,
                event: HookEvent::Uninstall,
            },
        ];
        let (result, replaced) =
            apply_hook_override(hooks, Some("./new-teardown.sh"), HookEvent::Uninstall);
        // The override uninstall hook replaces the declared one; the install hook
        // is untouched.
        let uninstall: Vec<&ResolvedHook> = result
            .iter()
            .filter(|h| h.event == HookEvent::Uninstall)
            .collect();
        assert_eq!(uninstall.len(), 1);
        assert_eq!(uninstall[0].run, "./new-teardown.sh");
        assert!(
            result
                .iter()
                .any(|h| h.event == HookEvent::Install && h.run == "build"),
            "the install hook must survive an uninstall override"
        );
        assert_eq!(replaced.as_deref(), Some(&["old-teardown".to_string()][..]));
    }

    // ---- run_hook ----

    // spec: HOOK-30
    // M11: `label` is source-controlled (a mind.toml `[[hooks]].name`, or the
    // raw `run` command as a fallback) and is written directly into both hook
    // frame lines (`println!("====== (hook: {label}) ======")` and its
    // closing pair) as well as into any `HookFailed` this returns. An
    // ANSI-bearing label (e.g. cursor-erase sequences) must not reach the
    // real terminal at the moment the frame opens -- that is precisely when
    // mind guarantees it happens, on every hook run, and could erase mind's
    // own just-printed progress output. `command` is displayed raw by
    // `HookFailed`'s `Display` too, so it must be sanitized for the error even
    // though the unsanitized value is still what actually gets executed.
    //
    // This asserts on the exact `label`/`command` strings `run_hook` feeds to
    // both `println!` and `HookFailed` (returned here, and embedded in its
    // `Display`) rather than capturing the real terminal: genuine OS-level fd
    // capture is not reliable under `cargo test`'s parallel harness, where
    // other tests' own status lines and child-process output share the same
    // real stdout descriptor. This mirrors how `disclosure_text` /
    // `hook_disclosure_text` are tested elsewhere in this file (asserting on
    // the sanitized string content, not the terminal).
    #[test]
    fn run_hook_sanitizes_ansi_in_label_and_command_for_the_error() {
        let dir = TempDir::new("ansi-label");
        let evil_label = "\x1b[2K\x1b[1A\x1b[2Kbuild";
        // '#' starts a comment in `sh`, so the trailing escape bytes are
        // inert: this always exits 9, while `command` (as text) still carries
        // a raw ESC for the sanitization check below.
        let evil_command = "exit 9 # \x1b[31mcolor\x1b[0m";

        let result = run_hook(
            evil_command,
            dir.path(),
            "github.com/test/repo",
            "install",
            evil_label,
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        let err = result.expect_err("a non-zero exit must produce HookFailed");
        let msg = err.to_string();
        assert!(
            !msg.contains('\x1b'),
            "raw ESC must not appear in the rendered error: {msg:?}"
        );

        match err {
            MindError::HookFailed {
                ref label,
                ref command,
                ..
            } => {
                assert!(
                    !label.contains('\x1b'),
                    "label field must not carry raw ESC: {label:?}"
                );
                assert!(
                    label.contains("build"),
                    "sanitized label text must remain: {label:?}"
                );
                assert!(
                    !command.contains('\x1b'),
                    "command field must not carry raw ESC: {command:?}"
                );
                assert!(
                    command.contains("color"),
                    "sanitized command text must remain: {command:?}"
                );
            }
            other => panic!("expected HookFailed, got: {other:?}"),
        }
    }

    // spec: HOOK-30
    // L2: a spawn failure returns right after the opening frame is printed;
    // the closing divider must still print on that path so the frame stays a
    // matched pair (HOOK-30), not just when a process actually ran. The
    // return-value shape (`streamed: false`, a non-empty `reason`, `status:
    // None`) is exercised elsewhere; this specifically exercises that the
    // spawn-failure branch is the one taken (a nonexistent `clone_dir` makes
    // the underlying `chdir` in the child fail, so `Command::status()` itself
    // returns an `Err` rather than the process running and exiting non-zero).
    #[test]
    fn run_hook_spawn_failure_produces_unstreamed_hook_failed() {
        let missing_dir = std::env::temp_dir().join(format!(
            "mind-hook-test-missing-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::SeqCst)
        ));
        assert!(
            !missing_dir.exists(),
            "the dir must not exist for this test to force a spawn failure"
        );

        let result = run_hook(
            "true",
            &missing_dir,
            "github.com/test/repo",
            "install",
            "spawn-fail",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        match result {
            Err(MindError::HookFailed {
                ref label,
                status,
                streamed,
                ref reason,
                ..
            }) => {
                assert_eq!(label, "spawn-fail");
                assert!(!streamed, "a spawn failure never ran the hook");
                assert!(
                    status.is_none(),
                    "a process that never ran has no exit status"
                );
                assert!(
                    !reason.is_empty(),
                    "a spawn failure must carry its own reason, since nothing was streamed"
                );
            }
            other => panic!("expected a spawn failure to produce HookFailed, got: {other:?}"),
        }
    }

    // spec: HOOK-30
    #[test]
    fn run_hook_success_creates_marker_file() {
        let dir = TempDir::new("success");
        let marker = dir.path().join("marker.txt");
        let marker_str = marker.to_str().expect("marker path is utf8");
        let command = format!("touch {marker_str}");
        let result = run_hook(
            &command,
            dir.path(),
            "github.com/test/repo",
            "install",
            "test-label",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        assert!(result.is_ok(), "expected Ok, got: {result:?}");
        assert!(
            marker.exists(),
            "marker file should exist after successful hook"
        );
    }

    // spec: HOOK-140
    #[test]
    fn run_hook_sets_profile_vars_sorted_and_always_present() {
        let dir = TempDir::new("env");
        let out = dir.path().join("env.txt");
        let command = format!(
            "printf '%s|%s|%s' \"$MIND_PROFILES\" \"$MIND_ITEM_PROFILES\" \
             \"${{MIND_ITEM_PROFILES+set}}\" > '{}'",
            out.display()
        );
        let env = HookEnv {
            profiles: vec!["full".into(), "default".into(), "full".into()],
            item_profiles: Vec::new(),
        };
        run_hook(
            &command,
            dir.path(),
            "local/a/b",
            "install",
            "env",
            &env,
            crate::hook_log::Site::default(),
        )
        .unwrap();
        let got = std::fs::read_to_string(&out).unwrap();
        // Sorted and deduped; the empty item list is still set (not unset).
        assert_eq!(got, "default,full||set");
    }

    // spec: HOOK-141
    #[test]
    fn profile_scope_applies_to_its_source_and_restores_on_drop() {
        assert_eq!(scoped_profiles("local/a/b"), None);
        {
            let mut reasons = std::collections::BTreeMap::new();
            reasons.insert(
                "skill:x".to_string(),
                std::collections::BTreeSet::from(["full".to_string()]),
            );
            let _g = scope_profiles(ProfileScope {
                source: "local/a/b".into(),
                enabled: vec!["default".into(), "full".into()],
                reasons,
            });
            assert_eq!(
                scoped_profiles("local/a/b"),
                Some(vec!["default".to_string(), "full".to_string()])
            );
            assert_eq!(scoped_profiles("local/other"), None);
            assert_eq!(scoped_item_reasons("local/a/b", "skill:x"), vec!["full"]);
            assert!(scoped_item_reasons("local/a/b", "skill:y").is_empty());
            assert!(scoped_item_reasons("local/other", "skill:x").is_empty());
        }
        assert_eq!(scoped_profiles("local/a/b"), None);
    }

    // spec: HOOK-30
    #[test]
    fn run_hook_nonzero_exit_returns_hook_failed() {
        let dir = TempDir::new("fail");
        let result = run_hook(
            "exit 3",
            dir.path(),
            "github.com/test/repo",
            "install",
            "test-label",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        match result {
            Err(
                ref e @ MindError::HookFailed {
                    event,
                    ref label,
                    ref identity,
                    ref command,
                    status,
                    reason: ref stderr,
                    streamed,
                },
            ) => {
                assert_eq!(event, "install", "wrong event");
                assert_eq!(label, "test-label", "wrong label");
                assert_eq!(identity, "github.com/test/repo", "wrong identity");
                assert_eq!(command, "exit 3", "wrong command");
                assert!(
                    status.is_some(),
                    "exit status should be Some for a process that ran"
                );
                let code = status.unwrap().code();
                assert_eq!(code, Some(3), "expected exit code 3, got {code:?}");
                // spec: HOOK-30 -- the hook's streams were inherited, so nothing
                // was captured to attach and the frame is already on screen.
                // `streamed` is therefore true even for a hook that
                // printed nothing: streaming cannot tell a silent hook from a
                // talkative one, and the message points at the (empty) frame
                // rather than claiming "(no output)" for a hook that may have
                // printed plenty. The captured form used to distinguish these.
                assert!(
                    stderr.is_empty(),
                    "an inherited hook captures no stderr to attach"
                );
                assert!(
                    streamed,
                    "a hook that ran streamed its own output, so the error points at the frame"
                );
                let msg = e.to_string();
                assert!(
                    msg.contains("its output, if any, is in the frame above"),
                    "a streamed hook failure must point at the frame: {msg}"
                );
                assert!(
                    !msg.contains("see the hook"),
                    "must not say 'see the hook's output above' when nothing was printed: {msg}"
                );
            }
            other => panic!("expected HookFailed, got: {other:?}"),
        }
    }

    // spec: HOOK-30
    // A hook that prints output before failing must produce a HookFailed with
    // streamed=true, so its Display says "its output, if any, is in the frame above" rather than
    // the contradictory "(no output)".
    #[test]
    fn run_hook_with_output_before_failure_points_at_the_frame() {
        let dir = TempDir::new("output-fail");
        // Print to stdout, then exit non-zero.
        let result = run_hook(
            "echo 'hook output'; exit 2",
            dir.path(),
            "github.com/test/repo",
            "install",
            "test-label",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        match result {
            Err(
                ref e @ MindError::HookFailed {
                    streamed,
                    reason: ref stderr,
                    ..
                },
            ) => {
                assert!(streamed, "streamed must be true when hook produced stdout");
                assert!(
                    stderr.is_empty(),
                    "stderr field must be empty (output was streamed, not captured)"
                );
                let msg = e.to_string();
                assert!(
                    msg.contains("its output, if any, is in the frame above"),
                    "must point at the frame when output was streamed: {msg}"
                );
                assert!(
                    !msg.contains("(no output)"),
                    "must not say '(no output)' when output was printed: {msg}"
                );
            }
            other => panic!("expected HookFailed, got: {other:?}"),
        }
    }

    // spec: HOOK-30
    // Same as above but with stderr output (not stdout): the framed output path
    // uses `printed_any` which covers either stream.
    #[test]
    fn run_hook_with_stderr_output_before_failure_points_at_the_frame() {
        let dir = TempDir::new("stderr-fail");
        let result = run_hook(
            "echo 'hook stderr' >&2; exit 1",
            dir.path(),
            "github.com/test/repo",
            "install",
            "test-label",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        match result {
            Err(ref e @ MindError::HookFailed { streamed, .. }) => {
                assert!(streamed, "streamed must be true when hook produced stderr");
                let msg = e.to_string();
                assert!(
                    msg.contains("its output, if any, is in the frame above"),
                    "stderr output must also trigger '(see output above)': {msg}"
                );
            }
            other => panic!("expected HookFailed, got: {other:?}"),
        }
    }

    // spec: HOOK-165
    #[test]
    fn log_lines_split_on_newlines_and_at_the_length_cap() {
        let mut lines: Vec<Vec<u8>> = Vec::new();
        let mut line = Vec::new();
        split_log_lines(&mut line, b"a\nb", |l| lines.push(l.to_vec()));
        split_log_lines(&mut line, b"c\n\nd", |l| lines.push(l.to_vec()));
        assert_eq!(lines, vec![b"a".to_vec(), b"bc".to_vec(), Vec::new()]);
        assert_eq!(line, b"d", "the partial line waits for more");

        // Output with no newline is written in capped pieces, not held.
        let mut lines: Vec<usize> = Vec::new();
        let mut line = Vec::new();
        let long = vec![b'x'; LOG_LINE_MAX * 2 + 5];
        split_log_lines(&mut line, &long, |l| lines.push(l.len()));
        assert_eq!(lines, vec![LOG_LINE_MAX, LOG_LINE_MAX]);
        assert_eq!(line.len(), 5);
    }

    // spec: HOOK-30
    #[test]
    fn run_hook_identity_and_command_propagate_to_error() {
        let dir = TempDir::new("propagate");
        let result = run_hook(
            "false",
            dir.path(),
            "github.com/acme/special",
            "install",
            "my-hook",
            &HookEnv::default(),
            crate::hook_log::Site::default(),
        );
        match result {
            Err(MindError::HookFailed {
                ref identity,
                ref command,
                ..
            }) => {
                assert_eq!(identity, "github.com/acme/special");
                assert_eq!(command, "false");
            }
            other => panic!("expected HookFailed, got: {other:?}"),
        }
    }
}