truth-mirror 0.9.1

Truthfulness gate and adversarial reviewer harness for AI coding agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
//! Hook installation, uninstallation, and dry-run planning.

use std::{
    fs,
    io::{self, Read},
    path::{Component, Path, PathBuf},
    process::{Command, ExitCode},
};

use anyhow::{Context, Result, bail};

use crate::{
    claim,
    cli::{self, Agent, HookName},
    gate,
    reviewer::ReviewQueue,
    surface::{self, SurfacePlan},
};

const INSTALLED_HOOKS: &[HookName] =
    &[HookName::CommitMsg, HookName::PostCommit, HookName::PrePush];
pub(crate) const MANAGED_MARKER: &str = "# truth-mirror managed hook";
const MANAGED_END_MARKER: &str = "# truth-mirror hook end";
pub(crate) const FORWARDER_NAME: &str = "_forward-local.sh";
const OUTER_HOOK_MARKERS: &[&str] = &[
    "# Entire CLI hooks",
    "# truth-mirror managed hook",
    "entire hooks git",
];
const STATE_GITIGNORE_HEADER: &str = "# truth-mirror runtime state - machine-generated";
const STATE_GITIGNORE_LINES: &[&str] = &[
    "*",
    "!.gitignore",
    "!config.toml",
    "runs/",
    "review-queue.jsonl",
    "ledger.jsonl",
    "ledger.md",
    "tmp/",
    "logs/",
    "*.local.*",
];
pub(crate) const FORWARDER_SOURCE: &str = r#"#!/bin/sh
# _forward-local.sh - delegate to .git/hooks from a committed core.hooksPath.
# Uses --git-common-dir (resolves to .git/) not core.hooksPath to prevent an infinite loop.
name="$1"; shift
git_dir="$(git rev-parse --git-common-dir 2>/dev/null)"
[ -n "$git_dir" ] || exit 0
local_hook="$git_dir/hooks/$name"
if [ -x "$local_hook" ]; then exec "$local_hook" "$@"; fi
exit 0
"#;

/// Printed after `--pi` install: Pi only executes project extensions once the
/// folder is trusted (verified against Pi 0.80.3 `core/project-trust.js`).
const PI_TRUST_NOTE: &str = "pi: installed .pi/extensions/truth-mirror.js — Pi loads it once you trust this project folder in Pi.";

/// Printed after `--grok` install: skill-based reinjection (Grok ignores passive hook stdout).
const GROK_SKILL_NOTE: &str = "grok: installed .grok/skills/truth-mirror/SKILL.md — Grok does not inject passive hook stdout; run `truth-mirror reinject --agent grok` (skill reminds the agent). Project hooks need `/hooks-trust` if enforcement hooks are installed.";

pub fn run(
    args: cli::InstallHooksArgs,
    state_dir: &Path,
    config_path: Option<&Path>,
    config: &crate::config::TruthMirrorConfig,
) -> Result<ExitCode> {
    let repo_root = git_root()?;
    let hooks_path = repo_root.join(state_dir).join("hooks");
    let plan = HookInstallPlan::new(&repo_root, &hooks_path, args.uninstall);
    // Preserve non-default global flags so the INSTALLED hooks use the same config
    // and state dir at runtime instead of silently reloading defaults.
    let global_args = hook_global_args(config_path, &repo_root, state_dir);
    let plan = HookInstallPlan {
        global_args,
        mode: detect_hook_mode(&repo_root, state_dir)?,
        ..plan
    };
    let agents = file_surface_agents(&args);
    let pi = pi_targeted(&args);
    let grok = grok_targeted(&args);

    if args.dry_run {
        println!("{}", plan.render());
        for agent in &agents {
            println!(
                "surface: {} -> {}",
                surface::agent_slug(*agent),
                surface::surface_relative_path(*agent)
            );
        }
        if pi {
            println!("surface: pi -> {}", surface::PI_EXTENSION_RELATIVE);
        }
        if grok {
            println!("surface: grok -> {}", surface::GROK_SKILL_RELATIVE);
            if config.enforcement.is_enabled() {
                println!(
                    "surface: grok-enforcement -> {}",
                    surface::surface_relative_path(Agent::Grok)
                );
            }
        }
        return Ok(ExitCode::SUCCESS);
    }

    let enforcement_enabled = config.enforcement.is_enabled();

    if args.uninstall {
        uninstall(&plan)?;
        for agent in &agents {
            surface::uninstall_enforcement(&repo_root, *agent)?;
            SurfacePlan::for_agent(&repo_root, *agent).uninstall()?;
        }
        if pi {
            surface::uninstall_pi_extension(&repo_root)?;
            remove_legacy_pi_hooks(&repo_root)?;
        }
        if grok {
            // Best-effort enforcement uninstall first so a corrupt hooks JSON cannot
            // block skill removal (full uninstall is also resilient elsewhere).
            if let Err(error) = surface::uninstall_enforcement(&repo_root, Agent::Grok) {
                eprintln!(
                    "{} grok enforcement uninstall failed (continuing skill cleanup): {error}",
                    crate::messages::diagnostic_prefix()
                );
            }
            surface::uninstall_grok_skill(&repo_root)?;
            surface::cleanup_empty_grok_dirs(&repo_root);
        }
        uninstall_legacy_hook_references(&repo_root)?;
    } else {
        install(&plan, args.inject_forwarder)?;
        print_async_review_guidance(&plan.global_args);
        for agent in &agents {
            SurfacePlan::for_agent(&repo_root, *agent).install()?;
            // Enforcement is opt-in: only install the tool-blocking hook when the
            // repo config enables it. Preserve global flags so it uses this config.
            if enforcement_enabled {
                surface::install_enforcement(&repo_root, *agent, &plan.global_args)?;
            }
        }
        if args.pi {
            // Clean any bogus .pi/hooks.json a prior truth-mirror wrote, install the
            // real project-local extension, and note the one-time trust step.
            remove_legacy_pi_hooks(&repo_root)?;
            surface::install_pi_extension(&repo_root)?;
            println!("{PI_TRUST_NOTE}");
        }
        if args.grok {
            // Grok cannot reinject via UserPromptSubmit stdout (passive hooks).
            // Install a project skill; optional PreToolUse enforcement uses hooks JSON.
            surface::install_grok_skill(&repo_root)?;
            if enforcement_enabled {
                surface::install_enforcement(&repo_root, Agent::Grok, &plan.global_args)?;
            }
            println!("{GROK_SKILL_NOTE}");
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn print_async_review_guidance(global_args: &str) {
    eprintln!(
        "{} post-commit hooks queue async reviews; {}.",
        crate::messages::diagnostic_prefix(),
        crate::messages::async_review_drain_hint(global_args)
    );
}

/// Standalone `uninstall` subcommand: full teardown of all truth-mirror hooks,
/// surfaces, legacy artefacts, and (with `--purge`) state directories.
///
/// Factoring note: the shared hook-uninstall logic reused here lives in
/// [`uninstall`] (hook-mode dispatch) and the per-surface helpers in
/// [`crate::surface`]. Agent-surface resilience (A7) means a malformed
/// `settings.json` must not abort the remaining surfaces; errors are collected
/// and reported together.
pub fn run_uninstall(
    args: cli::UninstallArgs,
    state_dir: &Path,
    config_path: Option<&Path>,
) -> Result<std::process::ExitCode> {
    let repo_root = git_root()?;
    let hooks_path = repo_root.join(state_dir).join("hooks");
    let global_args = hook_global_args(config_path, &repo_root, state_dir);
    let plan = HookInstallPlan {
        repo_root: repo_root.clone(),
        hooks_path: hooks_path.clone(),
        uninstall: true,
        mode: detect_hook_mode(&repo_root, state_dir)?,
        global_args,
    };

    if args.dry_run {
        println!("{}", plan.render());
        let agent_list = surface::FILE_SURFACE_AGENTS
            .iter()
            .map(|agent| surface::agent_slug(*agent))
            .chain(["pi", "grok"])
            .collect::<Vec<_>>()
            .join(", ");
        println!("uninstall: would remove all agent surfaces ({agent_list})");
        println!(
            "uninstall: would clean .pre-entire bridges and orphaned .pre-truth-mirror backups"
        );
        println!("uninstall: would remove legacy .truth-mirror/hooks/ install artifacts");
        println!(
            "uninstall: would scrub legacy truth-mirror hook references without managed markers"
        );
        if args.purge {
            println!(
                "uninstall: --purge: would delete {} and .truth-mirror/ entirely",
                state_dir.display()
            );
        } else {
            println!(
                "uninstall: ledger data in {} is preserved (use --purge to delete)",
                state_dir.display()
            );
        }
        return Ok(std::process::ExitCode::SUCCESS);
    }

    // ── Step 1: uninstall git hooks (mode-specific) ─────────────────────────
    uninstall(&plan)?;
    // R1: Also clean up stale .git/hooks managed shims from a prior plain-mode
    // install, regardless of the current hook mode (e.g. a Husky-mode repo that
    // previously had a plain install). uninstall_plain is guarded by
    // is_truth_mirror_managed so double-running it in Plain mode is a no-op.
    if !matches!(plan.mode, HookInstallMode::Plain) {
        uninstall_plain(&plan)?;
    }

    // ── Step 2: remove all agent surfaces (full teardown, resilient) ─────────
    let mut surface_errors: Vec<String> = Vec::new();
    for &agent in surface::FILE_SURFACE_AGENTS.iter() {
        if let Err(error) = surface::uninstall_enforcement(&repo_root, agent) {
            surface_errors.push(format!(
                "enforcement/{}: {error}",
                surface::agent_slug(agent)
            ));
        }
        if let Err(error) = surface::SurfacePlan::for_agent(&repo_root, agent).uninstall() {
            surface_errors.push(format!("surface/{}: {error}", surface::agent_slug(agent)));
        }
    }
    // Pi extension
    if let Err(error) = surface::uninstall_pi_extension(&repo_root) {
        surface_errors.push(format!("surface/pi-extension: {error}"));
    } else {
        // A6: attempt non-recursive rmdir on .pi/extensions/ then .pi/
        let pi_extensions = repo_root.join(".pi/extensions");
        let pi_dir = repo_root.join(".pi");
        // Ignore ENOTEMPTY (still has other files) — only remove if empty
        let _ = fs::remove_dir(&pi_extensions);
        let _ = fs::remove_dir(&pi_dir);
    }
    // Grok skill + enforcement hook (not in FILE_SURFACE_AGENTS)
    if let Err(error) = surface::uninstall_enforcement(&repo_root, Agent::Grok) {
        surface_errors.push(format!("enforcement/grok: {error}"));
    }
    if let Err(error) = surface::uninstall_grok_skill(&repo_root) {
        surface_errors.push(format!("surface/grok-skill: {error}"));
    } else {
        surface::cleanup_empty_grok_dirs(&repo_root);
    }
    // Legacy .pi/hooks.json
    if let Err(error) = remove_legacy_pi_hooks(&repo_root) {
        surface_errors.push(format!("surface/pi-legacy: {error}"));
    }

    // ── Step 3: .pre-entire bridge cleanup (A2) ───────────────────────────────
    // When Entire takes ownership of a hook it saves the previous hook
    // (truth-mirror's managed shim) as `<hook>.pre-entire`. Remove those when
    // they are still truth-mirror-managed so truth-mirror is fully gone.
    if let Err(e) = uninstall_pre_entire_bridges(&plan) {
        surface_errors.push(format!("bridges: {e}"));
    }

    // ── Step 4: orphaned .pre-truth-mirror backup cleanup (A3) ───────────────
    let git_hooks = repo_root.join(".git/hooks");
    if let Err(e) = cleanup_orphaned_backups(&git_hooks) {
        surface_errors.push(format!("backups/.git/hooks: {e}"));
    }
    if let HookInstallMode::CustomCommitted { ref hooks_path } = plan.mode.clone()
        && let Err(e) = cleanup_orphaned_backups(hooks_path)
    {
        surface_errors.push(format!("backups/{}: {e}", hooks_path.display()));
    }

    // ── Step 5: legacy .truth-mirror/hooks/ install artifact cleanup (A4) ───
    let legacy_state = repo_root.join(crate::config::LEGACY_STATE_DIR);
    let legacy_hooks_dir = legacy_state.join("hooks");
    if legacy_hooks_dir.is_dir()
        && let Err(e) = fs::remove_dir_all(&legacy_hooks_dir)
    {
        surface_errors.push(format!("legacy-hooks-dir: {e}"));
    }

    // ── Step 6: state .gitignore removal (A5) ────────────────────────────────
    let real_state_dir = absolutize(&repo_root, state_dir);
    remove_state_gitignore_if_pristine(&real_state_dir);

    // ── Step 7: purge state directories (A4 --purge) ─────────────────────────
    if args.purge {
        if real_state_dir.is_dir()
            && let Err(e) = fs::remove_dir_all(&real_state_dir)
        {
            surface_errors.push(format!("purge {}: {e}", real_state_dir.display()));
        }
        if legacy_state.is_dir()
            && let Err(e) = fs::remove_dir_all(&legacy_state)
        {
            surface_errors.push(format!("purge {}: {e}", legacy_state.display()));
        }
    }

    // ── Step 8: legacy truth-mirror references without managed markers ───────
    // Older installs and hand-rolled husky/Entire bridges may invoke truth-mirror
    // without the current `# truth-mirror managed hook` / `# truth-mirror hook end`
    // delimiters. Strip or remove those references so the uninstall is complete.
    if let Err(e) = uninstall_legacy_hook_references(&repo_root) {
        surface_errors.push(format!("legacy-hook-refs: {e}"));
    }

    // ── Report all collected errors (A7 + R3) ────────────────────────────────
    // surface_errors accumulates both surface/agent failures (Step 2) and
    // hook-cleanup failures (Steps 3-7) so that a failure in any later step
    // never silently drops earlier diagnostics.
    if !surface_errors.is_empty() {
        for error in &surface_errors {
            eprintln!(
                "{} uninstall error: {error}",
                crate::messages::diagnostic_prefix()
            );
        }
        return Ok(std::process::ExitCode::FAILURE);
    }

    Ok(std::process::ExitCode::SUCCESS)
}

/// Remove `.pre-entire` bridge files from a hooks directory when their content
/// is truth-mirror-managed (A2). These are created when Entire takes ownership
/// of a hook that truth-mirror previously managed.
fn uninstall_pre_entire_bridges(plan: &HookInstallPlan) -> Result<()> {
    let dirs: Vec<PathBuf> = match &plan.mode {
        HookInstallMode::Husky { content_dir } => {
            vec![plan.repo_root.join(".git/hooks"), content_dir.clone()]
        }
        _ => vec![plan.repo_root.join(".git/hooks")],
    };
    for dir in dirs {
        for hook in INSTALLED_HOOKS {
            let bridge = dir.join(format!("{}.pre-entire", hook.as_str()));
            if read_to_string_if_file(&bridge)?
                .as_deref()
                .is_some_and(is_truth_mirror_managed)
            {
                remove_file_if_exists(&bridge)?;
            }
        }
    }
    Ok(())
}

/// Clean up orphaned `.pre-truth-mirror` backup files in `hooks_dir` (A3).
///
/// Safe rules:
/// - Active hook absent → restore backup to active, remove backup.
/// - Active exists and backup bytes == backup bytes → redundant copy, remove.
/// - Active is a directory, or either read fails (non-UTF-8, permissions) →
///   preserve the backup and warn; continue to the next hook.
/// - Otherwise → content differs; preserve the backup and warn.
///
/// Only called when the active hook is NOT truth-mirror-managed (the case where
/// truth-mirror-managed active hooks restoring the backup is already handled by
/// [`uninstall_plain`]).
///
/// Uses raw byte comparison (R4) so non-UTF-8 hook content never aborts the run.
fn cleanup_orphaned_backups(hooks_dir: &Path) -> Result<()> {
    if !hooks_dir.is_dir() {
        return Ok(());
    }
    for hook in INSTALLED_HOOKS {
        let active = hooks_dir.join(hook.as_str());
        let backup = backup_path(&active, "pre-truth-mirror");
        if !backup.is_file() {
            continue;
        }

        // Read backup bytes; a read failure is unexpected — skip and warn.
        let backup_bytes = match fs::read(&backup) {
            Ok(b) => b,
            Err(e) => {
                eprintln!(
                    "{} warning: could not read backup {}; leaving it in place: {e}",
                    crate::messages::diagnostic_prefix(),
                    backup.display(),
                );
                continue;
            }
        };

        // If the active path is a directory we cannot safely proceed.
        if active.is_dir() {
            eprintln!(
                "{} warning: active hook path {} is a directory, not a file; \
                 leaving backup {} in place.",
                crate::messages::diagnostic_prefix(),
                active.display(),
                backup.display(),
            );
            continue;
        }

        // Read the active hook as raw bytes; treat missing as None.
        let active_bytes = match read_bytes_if_file(&active) {
            Ok(b) => b,
            Err(e) => {
                eprintln!(
                    "{} warning: could not read active hook {}; leaving backup {} in place: {e}",
                    crate::messages::diagnostic_prefix(),
                    active.display(),
                    backup.display(),
                );
                continue;
            }
        };

        // Only process backups when the active hook is NOT truth-mirror-managed.
        // (truth-mirror-managed active hook + backup is already handled in uninstall_plain.)
        // Convert to str for the marker check; non-UTF-8 → treat as not managed.
        let active_str = active_bytes
            .as_deref()
            .and_then(|b| std::str::from_utf8(b).ok());
        if active_str.is_some_and(is_truth_mirror_managed) {
            continue;
        }

        match active_bytes {
            None => {
                // Active absent — restore backup (recovery path).
                fs::write(&active, &backup_bytes)?;
                make_executable(&active)?;
                fs::remove_file(&backup)?;
            }
            Some(ref ab) if ab == &backup_bytes => {
                // Backup is a redundant copy — remove it.
                fs::remove_file(&backup)?;
            }
            Some(_) => {
                // Content differs — preserve the backup and warn.
                eprintln!(
                    "{} warning: preserved {} because its content differs from the active \
                     hook {}; inspect and remove manually.",
                    crate::messages::diagnostic_prefix(),
                    backup.display(),
                    active.display(),
                );
            }
        }
    }
    Ok(())
}

/// Remove the machine-generated state `.gitignore` iff its content starts with
/// the managed header. If the file has been user-modified, leave it and warn (A5).
fn remove_state_gitignore_if_pristine(state_dir: &Path) {
    let gitignore = state_dir.join(".gitignore");
    match read_to_string_if_file(&gitignore) {
        Ok(Some(content)) if content.starts_with(STATE_GITIGNORE_HEADER) => {
            if let Err(error) = remove_file_if_exists(&gitignore) {
                eprintln!(
                    "{} warning: could not remove state .gitignore {}: {error}",
                    crate::messages::diagnostic_prefix(),
                    gitignore.display(),
                );
            }
        }
        Ok(Some(_)) => {
            eprintln!(
                "{} hint: {} appears user-modified; leaving it in place.",
                crate::messages::diagnostic_prefix(),
                gitignore.display(),
            );
        }
        _ => {}
    }
}

/// File-surface agents (Claude, Codex) touched by this invocation. Install acts
/// only on explicitly selected agents; a bare `install-hooks --uninstall` clears
/// all file surfaces so it fully reverses a prior per-agent install.
fn file_surface_agents(args: &cli::InstallHooksArgs) -> Vec<Agent> {
    let mut agents = Vec::new();
    if args.claude {
        agents.push(Agent::Claude);
    }
    if args.codex {
        agents.push(Agent::Codex);
    }

    if agents.is_empty() && args.uninstall && !args.pi && !args.grok {
        return surface::FILE_SURFACE_AGENTS.to_vec();
    }
    agents
}

/// Whether this invocation should act on Pi: explicit `--pi`, or a bare
/// `--uninstall` (no agent flags) that clears everything including legacy Pi files.
fn pi_targeted(args: &cli::InstallHooksArgs) -> bool {
    args.pi || (args.uninstall && !args.claude && !args.codex && !args.grok)
}

/// Whether this invocation should act on Grok: explicit `--grok`, or bare uninstall.
fn grok_targeted(args: &cli::InstallHooksArgs) -> bool {
    args.grok || (args.uninstall && !args.claude && !args.codex && !args.pi)
}

/// Remove a `.pi/hooks.json` left by an earlier (incorrect) truth-mirror version.
fn remove_legacy_pi_hooks(repo_root: &Path) -> Result<()> {
    let path = repo_root.join(".pi/hooks.json");
    if path.is_file() {
        fs::remove_file(&path)?;
    }
    Ok(())
}

pub fn dispatch(
    args: cli::HookDispatchArgs,
    state_dir: &Path,
    config_path: Option<&Path>,
    config: &crate::config::TruthMirrorConfig,
) -> Result<ExitCode> {
    run_chained_hook(state_dir, args.hook, &args.args)?;

    match args.hook {
        HookName::CommitMsg => dispatch_commit_msg(state_dir, &args.args, config)?,
        HookName::PostCommit => dispatch_post_commit(state_dir)?,
        HookName::PrePush => dispatch_pre_push(state_dir, config_path, config, &args.args)?,
    }

    Ok(ExitCode::SUCCESS)
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct HookInstallPlan {
    pub repo_root: PathBuf,
    pub hooks_path: PathBuf,
    pub uninstall: bool,
    pub mode: HookInstallMode,
    /// Global CLI flags (`--config`, `--state-dir`) preserved into the shims so a
    /// custom-config install keeps using that config at hook runtime. Empty for a
    /// default install (the trailing space is included when non-empty).
    pub global_args: String,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum HookInstallMode {
    #[default]
    Plain,
    LegacyTruthMirrorHooksPath {
        configured_path: String,
    },
    Husky {
        content_dir: PathBuf,
    },
    CustomCommitted {
        hooks_path: PathBuf,
    },
}

impl HookInstallPlan {
    pub fn new(repo_root: &Path, hooks_path: &Path, uninstall: bool) -> Self {
        Self {
            repo_root: repo_root.to_path_buf(),
            hooks_path: hooks_path.to_path_buf(),
            uninstall,
            mode: HookInstallMode::Plain,
            global_args: String::new(),
        }
    }

    pub fn render(&self) -> String {
        let action = if self.uninstall {
            "uninstall"
        } else {
            "install"
        };
        let mut output = format!(
            "truth-mirror hook plan\nrepo={}\naction={action}\nmode={}\nstateHooks={}\n",
            self.repo_root.display(),
            self.mode.as_str(),
            self.hooks_path.display()
        );
        for hook in INSTALLED_HOOKS {
            output.push_str(&format!(
                "\nhook={}\npath={}\nbody:\n{}",
                hook.as_str(),
                self.active_hook_path(*hook).display(),
                self.render_hook_body(*hook)
            ));
        }
        output
    }

    fn active_hook_path(&self, hook: HookName) -> PathBuf {
        match &self.mode {
            HookInstallMode::Husky { content_dir } => content_dir.join(hook.as_str()),
            HookInstallMode::Plain | HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
                self.repo_root.join(".git/hooks").join(hook.as_str())
            }
            HookInstallMode::CustomCommitted { hooks_path } => hooks_path.join(hook.as_str()),
        }
    }

    fn render_hook_body(&self, hook: HookName) -> String {
        match self.mode {
            HookInstallMode::Husky { .. } => render_husky_block(hook, &self.global_args),
            HookInstallMode::CustomCommitted { .. } => render_custom_forwarder_stub(hook),
            HookInstallMode::Plain | HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
                render_shim(hook, &self.global_args)
            }
        }
    }
}

impl HookInstallMode {
    fn as_str(&self) -> &'static str {
        match self {
            HookInstallMode::Plain => "plain",
            HookInstallMode::LegacyTruthMirrorHooksPath { .. } => "plain-legacy-truth-mirror",
            HookInstallMode::Husky { .. } => "husky",
            HookInstallMode::CustomCommitted { .. } => "custom-committed",
        }
    }
}

/// Build the preserved global-flag prefix (with a trailing space when non-empty).
fn hook_global_args(config_path: Option<&Path>, repo_root: &Path, state_dir: &Path) -> String {
    let mut parts = Vec::new();
    if let Some(config) = config_path {
        parts.push(format!(
            "--config {}",
            quote_git_arg(&absolutize(repo_root, config))
        ));
    }
    if state_dir != Path::new(crate::config::DEFAULT_STATE_DIR) {
        parts.push(format!(
            "--state-dir {}",
            quote_git_arg(&absolutize(repo_root, state_dir))
        ));
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!("{} ", parts.join(" "))
    }
}

fn absolutize(repo_root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        repo_root.join(path)
    }
}

/// POSIX single-quote escaping for a path embedded in the generated `/bin/sh`
/// shim: wrap in single quotes and replace any embedded single quote with `'\''`
/// so no metacharacter (`;`, `$()`, `'`, spaces, …) can break or inject shell.
fn quote_git_arg(path: &Path) -> String {
    let value = path.to_string_lossy();
    format!("'{}'", value.replace('\'', "'\\''"))
}

pub fn render_shim(hook: HookName, global_args: &str) -> String {
    format!(
        "#!/bin/sh\n{MANAGED_MARKER}\nexec truth-mirror {global_args}hook-dispatch {} \"$@\"\n",
        hook.as_str()
    )
}

fn render_husky_block(hook: HookName, global_args: &str) -> String {
    format!(
        "{MANAGED_MARKER}\nif command -v truth-mirror >/dev/null 2>&1; then truth-mirror {global_args}hook-dispatch {} \"$@\"; else :; fi\n{MANAGED_END_MARKER}\n",
        hook.as_str()
    )
}

fn render_custom_forwarder_stub(hook: HookName) -> String {
    format!(
        "#!/bin/sh\n{MANAGED_MARKER}\nexec \"$(dirname \"$0\")/{FORWARDER_NAME}\" {} \"$@\"\n",
        hook.as_str()
    )
}

fn detect_hook_mode(repo_root: &Path, state_dir: &Path) -> Result<HookInstallMode> {
    let Some(configured) = git_config_get(repo_root, "core.hooksPath")? else {
        return Ok(HookInstallMode::Plain);
    };
    let configured = configured.trim().to_owned();
    if configured.is_empty() {
        return Ok(HookInstallMode::Plain);
    }
    if is_managed_hooks_path(repo_root, state_dir, &configured) {
        return Ok(HookInstallMode::LegacyTruthMirrorHooksPath {
            configured_path: configured,
        });
    }
    if configured.contains(".husky") {
        let hooks_path = repo_relative_path(repo_root, Path::new(&configured));
        let content_dir = if hooks_path.file_name().and_then(|name| name.to_str()) == Some("_") {
            hooks_path
                .parent()
                .map_or_else(|| repo_root.join(".husky"), Path::to_path_buf)
        } else {
            hooks_path
        };
        return Ok(HookInstallMode::Husky { content_dir });
    }
    Ok(HookInstallMode::CustomCommitted {
        hooks_path: repo_relative_path(repo_root, Path::new(&configured)),
    })
}

fn repo_relative_path(repo_root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        repo_root.join(path)
    }
}

fn is_managed_hooks_path(repo_root: &Path, state_dir: &Path, configured: &str) -> bool {
    let configured_path = normalize_path(&repo_relative_path(repo_root, Path::new(configured)));
    [
        state_dir.join("hooks"),
        PathBuf::from(crate::config::DEFAULT_STATE_DIR).join("hooks"),
        PathBuf::from(crate::config::LEGACY_STATE_DIR).join("hooks"),
    ]
    .iter()
    .any(|candidate| normalize_path(&repo_relative_path(repo_root, candidate)) == configured_path)
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if normalized.as_os_str().is_empty()
                    || (!normalized.has_root() && normalized.ends_with(".."))
                {
                    normalized.push("..");
                } else {
                    normalized.pop();
                }
            }
            Component::Normal(part) => normalized.push(part),
            Component::RootDir | Component::Prefix(_) => normalized.push(component.as_os_str()),
        }
    }
    normalized
}

fn install(plan: &HookInstallPlan, inject_forwarder: bool) -> Result<()> {
    let state_dir = state_dir_from_hooks_path(&plan.hooks_path);
    match &plan.mode {
        HookInstallMode::Plain => {
            prepare_state_hooks(plan)?;
            migrate_truth_md(&plan.repo_root, state_dir)?;
            install_plain(plan)
        }
        HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
            prepare_state_hooks(plan)?;
            migrate_truth_md(&plan.repo_root, state_dir)?;
            unset_core_hooks_path(&plan.repo_root)?;
            install_plain(plan)
        }
        HookInstallMode::Husky { content_dir } => {
            prepare_state_hooks(plan)?;
            migrate_truth_md(&plan.repo_root, state_dir)?;
            install_husky(plan, content_dir)
        }
        HookInstallMode::CustomCommitted { hooks_path } => {
            install_custom(plan, hooks_path, inject_forwarder)
        }
    }
}

fn uninstall(plan: &HookInstallPlan) -> Result<()> {
    match &plan.mode {
        HookInstallMode::Plain => uninstall_plain(plan)?,
        HookInstallMode::LegacyTruthMirrorHooksPath { .. } => {
            unset_core_hooks_path(&plan.repo_root)?;
            uninstall_plain(plan)?;
        }
        HookInstallMode::Husky { content_dir } => uninstall_husky(plan, content_dir)?,
        HookInstallMode::CustomCommitted { hooks_path } => {
            uninstall_plain(plan)?;
            uninstall_custom_forwarders(hooks_path)?;
        }
    }

    if plan.hooks_path.exists() {
        fs::remove_dir_all(&plan.hooks_path)?;
    }
    Ok(())
}

fn state_dir_from_hooks_path(hooks_path: &Path) -> &Path {
    hooks_path.parent().unwrap_or(hooks_path)
}

fn prepare_state_hooks(plan: &HookInstallPlan) -> Result<()> {
    ensure_state_gitignore(&plan.repo_root, state_dir_from_hooks_path(&plan.hooks_path))?;
    fs::create_dir_all(&plan.hooks_path)?;
    fs::create_dir_all(plan.hooks_path.join("chained"))?;
    clear_chained_hooks(plan)
}

fn install_plain(plan: &HookInstallPlan) -> Result<()> {
    let git_hooks = plan.repo_root.join(".git/hooks");
    fs::create_dir_all(&git_hooks)?;
    for hook in INSTALLED_HOOKS {
        install_local_hook(plan, &git_hooks, *hook)?;
    }
    Ok(())
}

fn install_local_hook(plan: &HookInstallPlan, git_hooks: &Path, hook: HookName) -> Result<()> {
    let active = git_hooks.join(hook.as_str());
    let backup = backup_path(&active, "pre-truth-mirror");
    let chained = plan.hooks_path.join("chained").join(hook.as_str());
    remove_file_if_exists(&chained)?;

    let source = local_hook_source(&active, &backup)?;
    if let Some(source) = source {
        if source.path != backup {
            fs::copy(&source.path, &backup)?;
            make_executable(&backup)?;
        }
        if !has_outer_hook_marker(&source.content) {
            fs::copy(&source.path, &chained)?;
            make_executable(&chained)?;
        }
    }

    fs::write(&active, render_shim(hook, &plan.global_args))?;
    make_executable(&active)?;
    Ok(())
}

fn uninstall_plain(plan: &HookInstallPlan) -> Result<()> {
    let git_hooks = plan.repo_root.join(".git/hooks");
    for hook in INSTALLED_HOOKS {
        let active = git_hooks.join(hook.as_str());
        let backup = backup_path(&active, "pre-truth-mirror");
        let active_content = read_to_string_if_file(&active)?;
        if active_content
            .as_deref()
            .is_some_and(is_truth_mirror_managed)
        {
            if backup.is_file() {
                fs::copy(&backup, &active)?;
                make_executable(&active)?;
                fs::remove_file(&backup)?;
            } else {
                remove_file_if_exists(&active)?;
            }
        }
        remove_file_if_exists(&plan.hooks_path.join("chained").join(hook.as_str()))?;
    }
    Ok(())
}

fn install_husky(plan: &HookInstallPlan, content_dir: &Path) -> Result<()> {
    fs::create_dir_all(content_dir)?;
    for hook in INSTALLED_HOOKS {
        let target = content_dir.join(hook.as_str());
        let block = render_husky_block(*hook, &plan.global_args);
        let next = match read_to_string_if_file(&target)? {
            Some(content) => append_managed_block(&content, &block),
            None => format!("#!/bin/sh\n{block}"),
        };
        fs::write(&target, next)?;
        make_executable(&target)?;
    }
    Ok(())
}

fn uninstall_husky(_plan: &HookInstallPlan, content_dir: &Path) -> Result<()> {
    for hook in INSTALLED_HOOKS {
        let target = content_dir.join(hook.as_str());
        if let Some(content) = read_to_string_if_file(&target)? {
            let next = remove_managed_block(&content);
            if is_empty_or_shebang_only(&next) {
                fs::remove_file(&target)?;
            } else {
                fs::write(&target, next)?;
                make_executable(&target)?;
            }
        }
    }
    Ok(())
}

fn install_custom(plan: &HookInstallPlan, hooks_path: &Path, inject_forwarder: bool) -> Result<()> {
    let missing_forwarder = INSTALLED_HOOKS
        .iter()
        .any(|hook| !custom_forwarder_present(hooks_path, *hook));
    if missing_forwarder && !inject_forwarder {
        bail!(
            "{} core.hooksPath is set to '{}' (a non-husky committed directory).\nTo install, either:\n  (a) run `{}` to write a _forward-local.sh forwarder into that directory (a committed repo change), or\n  (b) unset core.hooksPath and re-run install-hooks",
            crate::messages::diagnostic_prefix(),
            hooks_path.display(),
            crate::messages::command_for_cli(&plan.global_args, "install-hooks --inject-forwarder"),
        );
    }

    if inject_forwarder {
        inject_custom_forwarders(hooks_path)?;
    }

    prepare_state_hooks(plan)?;
    let state_dir = state_dir_from_hooks_path(&plan.hooks_path);
    migrate_truth_md(&plan.repo_root, state_dir)?;
    let git_hooks = plan.repo_root.join(".git/hooks");
    fs::create_dir_all(&git_hooks)?;
    for hook in INSTALLED_HOOKS {
        install_local_hook(plan, &git_hooks, *hook)?;
    }
    Ok(())
}

fn inject_custom_forwarders(hooks_path: &Path) -> Result<()> {
    fs::create_dir_all(hooks_path)?;
    let forwarder = hooks_path.join(FORWARDER_NAME);
    fs::write(&forwarder, FORWARDER_SOURCE)?;
    make_executable(&forwarder)?;

    for hook in INSTALLED_HOOKS {
        let target = hooks_path.join(hook.as_str());
        if custom_forwarder_present(hooks_path, *hook) {
            continue;
        }
        if target.is_file() {
            fs::copy(&target, backup_path(&target, "pre-truth-mirror"))?;
        }
        fs::write(&target, render_custom_forwarder_stub(*hook))?;
        make_executable(&target)?;
    }
    eprintln!(
        "hint: commit the truth-mirror forwarder changes in {}",
        hooks_path.display()
    );
    Ok(())
}

fn uninstall_custom_forwarders(hooks_path: &Path) -> Result<()> {
    for hook in INSTALLED_HOOKS {
        let target = hooks_path.join(hook.as_str());
        let backup = backup_path(&target, "pre-truth-mirror");
        let content = read_to_string_if_file(&target)?;
        if content.as_deref().is_some_and(is_truth_mirror_managed) {
            if backup.is_file() {
                fs::copy(&backup, &target)?;
                make_executable(&target)?;
                fs::remove_file(&backup)?;
            } else {
                remove_file_if_exists(&target)?;
            }
        }
    }
    let forwarder = hooks_path.join(FORWARDER_NAME);
    if read_to_string_if_file(&forwarder)?.as_deref() == Some(FORWARDER_SOURCE) {
        fs::remove_file(forwarder)?;
    }
    Ok(())
}

fn append_managed_block(content: &str, block: &str) -> String {
    let mut next = remove_managed_block(content);
    if !next.ends_with('\n') {
        next.push('\n');
    }
    next.push_str(block);
    next
}

fn remove_managed_block(content: &str) -> String {
    let mut out = Vec::new();
    let mut skipping = false;
    for line in content.lines() {
        if line == MANAGED_MARKER {
            skipping = true;
            continue;
        }
        if skipping {
            if line == MANAGED_END_MARKER {
                skipping = false;
            }
            continue;
        }
        out.push(line);
    }
    if out.is_empty() {
        String::new()
    } else {
        format!("{}\n", out.join("\n"))
    }
}

fn is_empty_or_shebang_only(content: &str) -> bool {
    let lines = content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>();
    lines.is_empty() || lines == ["#!/bin/sh"]
}

/// Check whether a shell script parses successfully with `sh -n`.
fn shell_syntax_ok(path: &Path) -> bool {
    std::process::Command::new("sh")
        .args(["-n"])
        .arg(path)
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// True when the only non-comment content left is a shebang and shell options.
/// Used after stripping legacy truth-mirror lines so that bare `set -e` lines
/// do not keep an otherwise-empty husky hook file alive.
fn is_effectively_empty_shell(content: &str) -> bool {
    content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .all(|line| line == "#!/bin/sh" || line == "#!/usr/bin/env sh" || line.starts_with("set "))
}

#[derive(Debug)]
struct LocalHookSource {
    path: PathBuf,
    content: String,
}

fn local_hook_source(active: &Path, backup: &Path) -> Result<Option<LocalHookSource>> {
    let Some(active_content) = read_to_string_if_file(active)? else {
        return Ok(None);
    };
    if is_truth_mirror_managed(&active_content) {
        return read_to_string_if_file(backup)?.map_or(Ok(None), |content| {
            Ok(Some(LocalHookSource {
                path: backup.to_path_buf(),
                content,
            }))
        });
    }
    Ok(Some(LocalHookSource {
        path: active.to_path_buf(),
        content: active_content,
    }))
}

fn custom_forwarder_present(hooks_path: &Path, hook: HookName) -> bool {
    read_to_string_if_file(&hooks_path.join(hook.as_str()))
        .ok()
        .flatten()
        .is_some_and(|content| {
            active_hook_lines(&content).any(|line| line.contains(FORWARDER_NAME))
                || content_forwards_to_local_git_hook(&content, hook)
                || is_truth_mirror_managed(&content)
        })
}

fn ensure_state_gitignore(repo_root: &Path, state_dir: &Path) -> Result<()> {
    let state_dir = absolutize(repo_root, state_dir);
    fs::create_dir_all(&state_dir)?;
    let gitignore = state_dir.join(".gitignore");
    let existing = read_to_string_if_file(&gitignore)?.unwrap_or_default();
    let content = render_state_gitignore(&existing);
    fs::write(&gitignore, content)?;
    print_tracked_runtime_hints(repo_root, &state_dir)?;
    Ok(())
}

fn render_state_gitignore(existing: &str) -> String {
    let mut content = String::new();
    content.push_str(STATE_GITIGNORE_HEADER);
    content.push('\n');
    for line in STATE_GITIGNORE_LINES {
        content.push_str(line);
        content.push('\n');
    }

    let standard = |line: &str| {
        let trimmed = line.trim();
        trimmed == STATE_GITIGNORE_HEADER || STATE_GITIGNORE_LINES.contains(&trimmed)
    };

    let mut wrote_separator = false;
    for line in existing.lines().filter(|line| !standard(line)) {
        if !wrote_separator {
            content.push('\n');
            wrote_separator = true;
        }
        content.push_str(line);
        content.push('\n');
    }

    content
}

fn print_tracked_runtime_hints(repo_root: &Path, state_dir: &Path) -> Result<()> {
    let rel_state = state_dir.strip_prefix(repo_root).unwrap_or(state_dir);
    for path in [
        rel_state.join("ledger.jsonl"),
        rel_state.join("ledger.md"),
        rel_state.join("review-queue.jsonl"),
        rel_state.join("runs"),
        rel_state.join("tmp"),
        rel_state.join("logs"),
    ] {
        let output = Command::new("git")
            .args(["ls-files", "--"])
            .arg(&path)
            .current_dir(repo_root)
            .output()?;
        if output.status.success() {
            for tracked in String::from_utf8_lossy(&output.stdout)
                .lines()
                .filter(|line| !line.trim().is_empty())
            {
                eprintln!("hint: run: git rm --cached {tracked}");
            }
        }
    }
    Ok(())
}

fn clear_chained_hooks(plan: &HookInstallPlan) -> Result<()> {
    for hook in INSTALLED_HOOKS {
        remove_file_if_exists(&plan.hooks_path.join("chained").join(hook.as_str()))?;
    }
    Ok(())
}

fn has_outer_hook_marker(content: &str) -> bool {
    content.lines().take(20).any(|line| {
        OUTER_HOOK_MARKERS
            .iter()
            .any(|marker| line.contains(marker))
            || (!line.trim_start().starts_with('#') && line_invokes_truth_hook_dispatch(line, None))
    })
}

fn is_truth_mirror_managed(content: &str) -> bool {
    content.contains(MANAGED_MARKER)
        || active_hook_lines(content).any(|line| line_invokes_truth_hook_dispatch(line, None))
}

/// Markers that indicate a hook file also contains Entire CLI integration.
/// When removing legacy truth-mirror references we must preserve Entire.
const ENTIRE_MARKERS: &[&str] = &[
    "# Entire CLI hooks",
    "entire hooks git",
    "command -v entire",
];

/// Detect content that references truth-mirror but does not carry the current
/// managed-block markers. Old husky installs, hand-rolled bridges, and scripts
/// that assign `truth_mirror_bin` all match so that uninstall can finish the
/// teardown that marker-based removal alone cannot.
fn is_legacy_truth_reference(content: &str) -> bool {
    content.contains("truth-mirror")
        || content.contains("truth_mirror_bin")
        || is_truth_mirror_managed(content)
}

/// True when a `.pre-entire` file is already the simple Entire→husky bridge
/// that install/uninstall want to preserve.
fn is_simple_pre_entire_bridge(content: &str, hook_name: &str) -> bool {
    // Normalize whitespace so hand-formatted variants still match.
    let normalized: String = content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .collect::<Vec<_>>()
        .join(" ");
    normalized == format!(r#"exec "$(dirname "$0")/{hook_name}" "$@""#)
}

/// Remove lines that are obviously part of a legacy truth-mirror hook, while
/// leaving Entire or other foreign content intact.
fn strip_legacy_truth_lines(content: &str) -> String {
    let mut out = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.contains("truth-mirror")
            || trimmed.contains("truth_mirror_bin")
            || trimmed.starts_with("# Truthfulness gate")
            || trimmed.starts_with("# truth-mirror's")
        {
            continue;
        }
        out.push(line);
    }
    if out.is_empty() {
        String::new()
    } else {
        format!("{}\n", out.join("\n"))
    }
}

/// Scrub legacy truth-mirror references from `.husky/`, `.git/hooks/`, and
/// `.truth-mirror/hooks/` files that were not written with the current managed
/// block markers. Files that are solely truth-mirror are removed; files that
/// also contain Entire integration are stripped of truth-mirror lines.
///
/// `.pre-entire` bridges created by the husky+Entire+truth-mirror chain are
/// rewritten to a simple bridge so Entire keeps forwarding to the husky hook.
fn uninstall_legacy_hook_references(repo_root: &Path) -> Result<()> {
    let husky_dir = repo_root.join(".husky");
    let git_hooks = repo_root.join(".git/hooks");
    let legacy_hooks = repo_root
        .join(crate::config::LEGACY_STATE_DIR)
        .join("hooks");

    for hook in INSTALLED_HOOKS {
        let hook_name = hook.as_str();
        let names: Vec<String> = vec![hook_name.to_owned(), format!("{hook_name}.pre-entire")];
        for dir in [&husky_dir, &git_hooks, &legacy_hooks] {
            for name in &names {
                let path = dir.join(name);
                let Some(content) = read_to_string_if_file(&path)? else {
                    continue;
                };
                if content.contains(MANAGED_MARKER) {
                    continue;
                }
                if name.ends_with(".pre-entire") {
                    if is_simple_pre_entire_bridge(&content, hook_name) {
                        continue;
                    }
                    if is_legacy_truth_reference(&content) || !shell_syntax_ok(&path) {
                        // Keep the Entire forwarding bridge but drop any custom
                        // truth-mirror logic that may leave broken `else` blocks.
                        let bridge =
                            format!("#!/bin/sh\nexec \"$(dirname \"$0\")/{hook_name}\" \"$@\"\n");
                        fs::write(&path, bridge)?;
                        make_executable(&path)?;
                    }
                    continue;
                }
                if !is_legacy_truth_reference(&content) {
                    continue;
                }
                if ENTIRE_MARKERS.iter().any(|marker| content.contains(marker)) {
                    let stripped = strip_legacy_truth_lines(&content);
                    if is_effectively_empty_shell(&stripped) {
                        fs::remove_file(&path)?;
                    } else {
                        fs::write(&path, stripped)?;
                        make_executable(&path)?;
                    }
                } else {
                    fs::remove_file(&path)?;
                }
            }
        }
    }
    Ok(())
}

/// Move legacy TRUTH.md locations into the current state dir so that install
/// leaves the repo following the `.truth/TRUTH.md` convention.
fn migrate_truth_md(repo_root: &Path, state_dir: &Path) -> Result<()> {
    let target = state_dir.join("TRUTH.md");
    if target.is_file() {
        return Ok(());
    }
    let legacy = repo_root
        .join(crate::config::LEGACY_STATE_DIR)
        .join("TRUTH.md");
    if legacy.is_file() {
        fs::copy(&legacy, &target)?;
        fs::remove_file(&legacy)?;
        return Ok(());
    }
    let root = repo_root.join("TRUTH.md");
    if root.is_file() {
        fs::rename(&root, &target)?;
    }
    Ok(())
}

fn active_hook_lines(content: &str) -> impl Iterator<Item = &str> {
    content
        .lines()
        .map(str::trim_start)
        .filter(|line| !line.trim().is_empty() && !line.starts_with('#'))
}

fn content_forwards_to_local_git_hook(content: &str, hook: HookName) -> bool {
    let resolves_git_dir =
        content.contains("--git-common-dir") || content.contains("git rev-parse --git-common-dir");
    resolves_git_dir
        && active_hook_lines(content)
            .any(|line| line_forwards_to_local_git_hook_with_args(line, hook))
}

fn line_forwards_to_local_git_hook_with_args(line: &str, hook: HookName) -> bool {
    line.contains("$@")
        && (line.contains(&format!("hooks/{}", hook.as_str()))
            || line.contains("hooks/$name")
            || line.contains("hooks/${name}")
            || line.contains("hooks/$hook")
            || line.contains("hooks/${hook}"))
}

fn line_invokes_truth_hook_dispatch(line: &str, expected_hook: Option<HookName>) -> bool {
    crate::shell::shellish_token_segments(line)
        .iter()
        .any(|tokens| token_segment_invokes_truth_hook_dispatch(tokens, expected_hook))
}

fn token_segment_invokes_truth_hook_dispatch(
    tokens: &[&str],
    expected_hook: Option<HookName>,
) -> bool {
    for (index, token) in tokens.iter().enumerate() {
        if !is_truth_binary(token) {
            continue;
        }
        let Some(dispatch_offset) = tokens[index + 1..]
            .iter()
            .position(|candidate| *candidate == "hook-dispatch")
        else {
            continue;
        };
        let hook_index = index + 1 + dispatch_offset + 1;
        let Some(hook) = tokens.get(hook_index) else {
            continue;
        };
        if expected_hook.is_some_and(|expected| hook == &expected.as_str())
            || expected_hook.is_none() && token_is_installed_hook(hook)
        {
            return true;
        }
    }
    false
}

fn is_truth_binary(token: &str) -> bool {
    token == "truth"
        || token == "truth-mirror"
        || token.ends_with("/truth")
        || token.ends_with("/truth-mirror")
}

fn token_is_installed_hook(token: &str) -> bool {
    INSTALLED_HOOKS.iter().any(|hook| token == hook.as_str())
}

fn backup_path(path: &Path, suffix: &str) -> PathBuf {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("hook");
    path.with_file_name(format!("{file_name}.{suffix}"))
}

fn read_to_string_if_file(path: &Path) -> Result<Option<String>> {
    match fs::read_to_string(path) {
        Ok(content) => Ok(Some(content)),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error.into()),
    }
}

/// Read a path as raw bytes, returning `Ok(None)` when absent.
fn read_bytes_if_file(path: &Path) -> Result<Option<Vec<u8>>> {
    match fs::read(path) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error.into()),
    }
}

fn remove_file_if_exists(path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn unset_core_hooks_path(repo_root: &Path) -> Result<()> {
    let status = Command::new("git")
        .args(["config", "--unset", "core.hooksPath"])
        .current_dir(repo_root)
        .status()?;
    if !status.success() {
        // Git exits non-zero when the key is already absent; migration should be idempotent.
        return Ok(());
    }
    Ok(())
}

fn dispatch_commit_msg(
    state_dir: &Path,
    args: &[String],
    config: &crate::config::TruthMirrorConfig,
) -> Result<()> {
    let commit_msg_path = args
        .first()
        .context("commit-msg hook requires COMMIT_EDITMSG path")?;
    let commit_message = fs::read_to_string(commit_msg_path)?;
    let diff = git_stdout(&["diff", "--cached"])?;
    let claim_file = fs::read_to_string(state_dir.join("claim.txt")).ok();
    let policy = config.gates.to_policy();
    claim::evaluate_commit_message(&commit_message, claim_file.as_deref(), Some(&diff), &policy)?;
    Ok(())
}

fn dispatch_post_commit(state_dir: &Path) -> Result<()> {
    let sha = git_stdout(&["rev-parse", "HEAD"])?;
    ReviewQueue::new(state_dir).enqueue(sha.trim())?;
    // Enqueuing a claim must be sufficient to guarantee a consumer exists: kick the
    // idempotent watcher lifecycle so the queue drains without a human running
    // `watch` by hand. Best-effort and non-fatal — a failed spawn must never fail
    // the commit hook, and the next enqueue (or a manual `watch`) will retry.
    if let Err(error) = crate::watcher::ensure_watcher(state_dir) {
        tracing::warn!(%error, "post-commit: failed to ensure a review watcher");
    }
    Ok(())
}

fn dispatch_pre_push(
    state_dir: &Path,
    config_path: Option<&Path>,
    config: &crate::config::TruthMirrorConfig,
    args: &[String],
) -> Result<()> {
    let remote_name = pre_push_remote_name_from_args(args);
    let mut stdin = String::new();
    io::stdin().read_to_string(&mut stdin)?;
    for line in stdin.lines() {
        if let Some(range) = pre_push_range_from_line_for_remote(line, remote_name) {
            gate::run(
                cli::GateArgs {
                    pre_push: Some(range),
                    commit_msg: None,
                    claim_file: None,
                    diff_file: None,
                    fake_markers: Vec::new(),
                    pre_tool_use: false,
                    tool: None,
                },
                state_dir,
                config_path,
                config,
            )?;
        }
    }
    Ok(())
}

fn pre_push_range_from_line_for_remote(line: &str, remote_name: Option<&str>) -> Option<String> {
    let parts = line.split_whitespace().collect::<Vec<_>>();
    let local_sha = parts.get(1)?;
    let remote_sha = parts.get(3)?;
    if is_zero_sha(local_sha) {
        return None;
    }

    if is_zero_sha(remote_sha) {
        match remote_name.filter(|name| safe_pre_push_remote_name(name)) {
            Some(remote_name) => Some(format!("new:{remote_name}:{local_sha}")),
            None => Some(format!("new:{local_sha}")),
        }
    } else {
        Some(format!("{remote_sha}..{local_sha}"))
    }
}

fn pre_push_remote_name_from_args(args: &[String]) -> Option<&str> {
    let remote_name = args.first()?.as_str();
    let remote_url = args.get(1).map(String::as_str);
    if remote_url == Some(remote_name) || !safe_pre_push_remote_name(remote_name) {
        return None;
    }
    Some(remote_name)
}

fn safe_pre_push_remote_name(value: &str) -> bool {
    !value.is_empty()
        && !value.starts_with('-')
        && !value.contains(':')
        && !value.contains("..")
        && !value
            .chars()
            .any(|character| character.is_whitespace() || character.is_control())
        && !value
            .chars()
            .any(|character| matches!(character, '*' | '?' | '['))
}

fn is_zero_sha(value: &str) -> bool {
    value.chars().all(|character| character == '0')
}

fn run_chained_hook(state_dir: &Path, hook: HookName, args: &[String]) -> Result<()> {
    let chained = state_dir.join("hooks/chained").join(hook.as_str());
    if !chained.is_file() {
        return Ok(());
    }
    let content = fs::read_to_string(&chained)?;
    if has_outer_hook_marker(&content) {
        eprintln!(
            "{} skipping unsafe chained hook {} because it appears to invoke an outer hook manager",
            crate::messages::diagnostic_prefix(),
            chained.display()
        );
        return Ok(());
    }

    let status = Command::new(&chained).args(args).status()?;
    if !status.success() {
        bail!(
            "chained hook {} failed with status {status}",
            chained.display()
        );
    }
    Ok(())
}

fn git_root() -> Result<PathBuf> {
    Ok(PathBuf::from(
        git_stdout(&["rev-parse", "--show-toplevel"])?.trim(),
    ))
}

fn git_stdout(args: &[&str]) -> Result<String> {
    let output = Command::new("git").args(args).output()?;
    if !output.status.success() {
        bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

fn git_config_get(repo_root: &Path, key: &str) -> Result<Option<String>> {
    let output = Command::new("git")
        .args(["config", "--get", key])
        .current_dir(repo_root)
        .output()?;
    if output.status.success() {
        return Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()));
    }
    if output.status.code() == Some(1) {
        return Ok(None);
    }
    bail!(
        "git config --get {key} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[cfg(unix)]
fn make_executable(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    let mut permissions = fs::metadata(path)?.permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(path, permissions)?;
    Ok(())
}

#[cfg(not(unix))]
fn make_executable(_path: &Path) -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{fs, process::Command};

    use proptest::prelude::*;

    use super::{HookInstallPlan, pre_push_range_from_line_for_remote, render_shim};
    use crate::cli::HookName;

    #[test]
    fn hook_shim_is_only_exec_delegation() {
        let shim = render_shim(HookName::CommitMsg, "");
        let lines = shim.lines().collect::<Vec<_>>();

        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "#!/bin/sh");
        assert_eq!(lines[1], super::MANAGED_MARKER);
        assert_eq!(
            lines[2],
            "exec truth-mirror hook-dispatch commit-msg \"$@\""
        );
    }

    #[test]
    fn quote_git_arg_escapes_shell_metacharacters() {
        use std::path::Path;
        assert_eq!(super::quote_git_arg(Path::new("/a/b.toml")), "'/a/b.toml'");
        // metacharacters are neutralized by single-quoting
        assert_eq!(
            super::quote_git_arg(Path::new("/a/c;$(touch x).toml")),
            "'/a/c;$(touch x).toml'"
        );
        // an embedded single quote is escaped as '\''
        assert_eq!(
            super::quote_git_arg(Path::new("/a/it's.toml")),
            "'/a/it'\\''s.toml'"
        );
    }

    #[test]
    fn normalize_path_preserves_unmatched_relative_parents() {
        use std::path::{Path, PathBuf};

        assert_eq!(
            super::normalize_path(Path::new("../hooks")),
            PathBuf::from("../hooks")
        );
        assert_eq!(
            super::normalize_path(Path::new("a/../../hooks")),
            PathBuf::from("../hooks")
        );
    }

    #[test]
    fn hook_shim_preserves_global_args() {
        let shim = render_shim(HookName::PrePush, "--config /abs/enforce.toml ");
        let lines = shim.lines().collect::<Vec<_>>();

        assert_eq!(lines.len(), 3, "shim stays <=3 lines + exec-only");
        assert_eq!(
            lines[2],
            "exec truth-mirror --config /abs/enforce.toml hook-dispatch pre-push \"$@\""
        );
    }

    #[test]
    fn dry_run_plan_names_hooks_and_hooks_path() {
        let plan = HookInstallPlan::new(
            std::path::Path::new("/repo"),
            std::path::Path::new("/repo/.truth/hooks"),
            false,
        );
        let rendered = plan.render();

        assert!(rendered.contains("commit-msg"));
        assert!(rendered.contains("post-commit"));
        assert!(rendered.contains("pre-push"));
        assert!(rendered.contains("stateHooks=/repo/.truth/hooks"));
        assert!(rendered.contains("path=/repo/.git/hooks/commit-msg"));
        assert!(rendered.contains("body:\n#!/bin/sh\n# truth-mirror managed hook"));
    }

    #[test]
    fn managed_block_replace_is_idempotent() {
        let block = super::render_husky_block(HookName::CommitMsg, "");
        let original = "#!/bin/sh\necho before\n";
        let once = super::append_managed_block(original, &block);
        let twice = super::append_managed_block(&once, &block);

        assert_eq!(twice.matches(super::MANAGED_MARKER).count(), 1);
        assert!(twice.contains("echo before"));
    }

    #[test]
    fn chained_hook_safety_filter_detects_outer_tools() {
        assert!(super::has_outer_hook_marker(
            "#!/bin/sh\n# Entire CLI hooks\nentire hooks git commit-msg\n"
        ));
        assert!(super::has_outer_hook_marker(
            "#!/bin/sh\n# truth-mirror managed hook\nexec truth-mirror hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(super::has_outer_hook_marker(
            "#!/bin/sh\nexec truth hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(super::has_outer_hook_marker(
            "#!/bin/sh\nexec /usr/local/bin/truth hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(!super::has_outer_hook_marker(
            "#!/bin/sh\n# exec truth hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(!super::has_outer_hook_marker("#!/bin/sh\necho safe\n"));
    }

    #[test]
    fn managed_detection_ignores_commented_and_unrelated_truth_lines() {
        assert!(!super::is_truth_mirror_managed(
            "#!/bin/sh\n# exec truth hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(!super::is_truth_mirror_managed(
            "#!/bin/sh\nexec truth unrelated \"$@\"\n"
        ));
        assert!(!super::is_truth_mirror_managed(
            "#!/bin/sh\nexec truth --version && hook-dispatch commit-msg \"$@\"\n"
        ));
        assert!(!super::is_truth_mirror_managed(
            "#!/bin/sh\nhook-dispatch commit-msg \"$@\"; exec truth --version\n"
        ));
        assert!(super::is_truth_mirror_managed(
            "#!/bin/sh\nexec /opt/bin/truth hook-dispatch pre-push \"$@\"\n"
        ));
    }

    #[test]
    fn run_chained_hook_skips_marker_bearing_stale_hook() {
        let temp = tempfile::tempdir().unwrap();
        let chained = temp.path().join("hooks/chained/commit-msg");
        std::fs::create_dir_all(chained.parent().unwrap()).unwrap();
        std::fs::write(&chained, "#!/bin/sh\n# Entire CLI hooks\nexit 42\n").unwrap();
        super::make_executable(&chained).unwrap();

        super::run_chained_hook(temp.path(), HookName::CommitMsg, &[]).unwrap();
    }

    #[test]
    fn pre_push_line_maps_to_git_range() {
        let line = "refs/heads/main abc123 refs/heads/main def456";

        assert_eq!(
            pre_push_range_from_line_for_remote(line, None),
            Some("def456..abc123".to_owned())
        );
    }

    #[test]
    fn pre_push_new_branch_maps_to_new_branch_token() {
        let line =
            "refs/heads/topic abc123 refs/heads/topic 0000000000000000000000000000000000000000";

        assert_eq!(
            pre_push_range_from_line_for_remote(line, None),
            Some("new:abc123".to_owned())
        );
    }

    #[test]
    fn pre_push_new_branch_includes_safe_remote_name_when_available() {
        let line =
            "refs/heads/topic abc123 refs/heads/topic 0000000000000000000000000000000000000000";

        assert_eq!(
            pre_push_range_from_line_for_remote(line, Some("origin")),
            Some("new:origin:abc123".to_owned())
        );
        assert_eq!(
            pre_push_range_from_line_for_remote(line, Some("../bad")),
            Some("new:abc123".to_owned())
        );
    }

    #[test]
    fn pre_push_args_omit_remote_name_for_direct_path_pushes() {
        assert_eq!(
            super::pre_push_remote_name_from_args(&[
                "origin".to_owned(),
                "git@example/repo".to_owned()
            ]),
            Some("origin")
        );
        assert_eq!(
            super::pre_push_remote_name_from_args(&[
                "../repo.git".to_owned(),
                "../repo.git".to_owned()
            ]),
            None
        );
    }

    #[test]
    fn pre_push_args_omit_glob_like_remote_names() {
        for remote_name in ["bad*remote", "bad?remote", "bad[remote"] {
            assert_eq!(
                super::pre_push_remote_name_from_args(&[
                    remote_name.to_owned(),
                    "git@example/repo".to_owned()
                ]),
                None
            );
        }
    }

    #[test]
    fn legacy_truth_only_husky_hook_is_removed() {
        let temp = tempfile::tempdir().unwrap();
        let husky = temp.path().join(".husky");
        fs::create_dir_all(&husky).unwrap();
        let hook = husky.join("commit-msg");
        fs::write(
            &hook,
            "#!/usr/bin/env sh\nset -e\n# Truthfulness gate\nif command -v truth-mirror >/dev/null 2>&1; then truth-mirror hook-dispatch commit-msg \"$@\"; else :; fi\n",
        )
        .unwrap();
        super::make_executable(&hook).unwrap();
        super::uninstall_legacy_hook_references(temp.path()).unwrap();
        assert!(!hook.exists());
    }

    #[test]
    fn legacy_truth_hook_with_entire_is_stripped_not_removed() {
        let temp = tempfile::tempdir().unwrap();
        let husky = temp.path().join(".husky");
        fs::create_dir_all(&husky).unwrap();
        let hook = husky.join("pre-push");
        fs::write(
            &hook,
            "#!/bin/sh\nif command -v entire >/dev/null 2>&1; then entire hooks git pre-push \"$1\"; fi\nexec truth-mirror hook-dispatch pre-push \"$@\"\n",
        )
        .unwrap();
        super::make_executable(&hook).unwrap();
        super::uninstall_legacy_hook_references(temp.path()).unwrap();
        let content = fs::read_to_string(&hook).unwrap();
        assert!(!content.contains("truth-mirror"));
        assert!(content.contains("entire hooks git pre-push"));
    }

    #[test]
    fn legacy_truth_mirror_bin_pre_entire_bridge_is_rewritten_to_simple_bridge() {
        let temp = tempfile::tempdir().unwrap();
        let husky = temp.path().join(".husky");
        fs::create_dir_all(&husky).unwrap();
        let bridge = husky.join("pre-push.pre-entire");
        fs::write(
            &bridge,
            "#!/usr/bin/env sh\ntruth_mirror_bin=\"$(command -v truth-mirror || true)\"\n[ -n \"$truth_mirror_bin\" ] || exit 0\n\"$truth_mirror_bin\" hook-dispatch pre-push \"$@\"\n",
        )
        .unwrap();
        super::make_executable(&bridge).unwrap();
        super::uninstall_legacy_hook_references(temp.path()).unwrap();
        let content = fs::read_to_string(&bridge).unwrap();
        assert!(!content.contains("truth-mirror"));
        assert!(content.contains(r#"exec "$(dirname "$0")/pre-push" "$@""#));
    }

    #[test]
    fn broken_pre_entire_bridge_is_rewritten_even_without_truth_reference() {
        let temp = tempfile::tempdir().unwrap();
        let husky = temp.path().join(".husky");
        fs::create_dir_all(&husky).unwrap();
        let bridge = husky.join("pre-push.pre-entire");
        // A stripped legacy bridge can end up with an empty `else` branch,
        // which `sh -n` rejects.
        fs::write(
            &bridge,
            "#!/usr/bin/env sh\nset -e\nif command -v entire >/dev/null; then\n  echo ok\nelse\nfi\n",
        )
        .unwrap();
        super::make_executable(&bridge).unwrap();
        super::uninstall_legacy_hook_references(temp.path()).unwrap();
        let content = fs::read_to_string(&bridge).unwrap();
        assert!(content.contains(r#"exec "$(dirname "$0")/pre-push" "$@""#));
    }

    #[test]
    fn simple_pre_entire_bridge_is_preserved() {
        let temp = tempfile::tempdir().unwrap();
        let husky = temp.path().join(".husky");
        fs::create_dir_all(&husky).unwrap();
        let bridge = husky.join("commit-msg.pre-entire");
        fs::write(
            &bridge,
            "#!/bin/sh\nexec \"$(dirname \"$0\")/commit-msg\" \"$@\"\n",
        )
        .unwrap();
        super::make_executable(&bridge).unwrap();
        super::uninstall_legacy_hook_references(temp.path()).unwrap();
        let content = fs::read_to_string(&bridge).unwrap();
        assert!(content.contains(r#"exec "$(dirname "$0")/commit-msg" "$@""#));
    }

    #[test]
    fn install_migrates_root_truth_md_to_state_dir() {
        let temp = tempfile::tempdir().unwrap();
        let repo_root = temp.path().join("repo");
        fs::create_dir_all(&repo_root).unwrap();
        Command::new("git")
            .args(["init"])
            .current_dir(&repo_root)
            .output()
            .unwrap();
        let root_truth = repo_root.join("TRUTH.md");
        fs::write(&root_truth, "# truth\n").unwrap();
        let state_dir = repo_root.join(".truth");
        fs::create_dir_all(&state_dir).unwrap();
        super::migrate_truth_md(&repo_root, &state_dir).unwrap();
        assert!(state_dir.join("TRUTH.md").is_file());
        assert!(!root_truth.exists());
        assert_eq!(
            fs::read_to_string(state_dir.join("TRUTH.md")).unwrap(),
            "# truth\n"
        );
    }

    #[test]
    fn install_migrates_legacy_truth_mirror_md_to_state_dir() {
        let temp = tempfile::tempdir().unwrap();
        let repo_root = temp.path().join("repo");
        fs::create_dir_all(&repo_root).unwrap();
        let legacy_dir = repo_root.join(".truth-mirror");
        fs::create_dir_all(&legacy_dir).unwrap();
        fs::write(legacy_dir.join("TRUTH.md"), "# legacy truth\n").unwrap();
        let state_dir = repo_root.join(".truth");
        fs::create_dir_all(&state_dir).unwrap();
        super::migrate_truth_md(&repo_root, &state_dir).unwrap();
        assert!(state_dir.join("TRUTH.md").is_file());
        assert!(!legacy_dir.join("TRUTH.md").exists());
    }

    proptest! {
        #[test]
        fn hook_shim_rendering_stays_tiny_exec_only(index in 0usize..3) {
            let hook = [HookName::CommitMsg, HookName::PostCommit, HookName::PrePush][index];
            let shim = render_shim(hook, "");
            let lines = shim.lines().collect::<Vec<_>>();

            prop_assert_eq!(lines.len(), 3);
            prop_assert_eq!(lines[0], "#!/bin/sh");
            prop_assert_eq!(lines[1], super::MANAGED_MARKER);
            prop_assert!(lines[2].starts_with("exec truth-mirror hook-dispatch "));
            prop_assert!(lines[2].contains(hook.as_str()));
            prop_assert_eq!(shim.matches(super::MANAGED_MARKER).count(), 1);
            prop_assert_eq!(shim.matches("exec truth-mirror").count(), 1);
        }
    }
}