ljos 0.35.7

Memory, a work tracker and a shell-command gate for coding agents (Claude Code, Codex, Grok Build, agy, opencode) over MCP and hooks.
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
//! Global git hooks that book a commit when the runner has no prompt hook.
//!
//! When `core.hooksPath` is unset, `install` writes a stub for every
//! standard git hook and points the global config at ljos's directory. The
//! stub calls `ljos git-hook <name>`, then runs the repository's
//! `.git/hooks/<name>` or the previous path an older install recorded, with
//! the same arguments. `post-rewrite` copies stdin first, so `ljos git-hook`
//! and the chained hook both see the old and new shas.
//!
//! When `core.hooksPath` already names a directory, install leaves that
//! setting alone and appends a delimited block to each hook there. The
//! block calls `ljos git-hook <name>`. A missing hook file is created
//! executable. Text that was already in the file is kept. Uninstall removes
//! only that block, and deletes a file that held nothing else.
//!
//! `post-commit` and `post-rewrite` book the commit. Booking never fails
//! the hook. `pre-commit` and `pre-push` run the sitting gate under an
//! agent runner: a commit needs a live sitting, and a push onto a
//! protected branch also needs the sitting's ticket to clear it. That
//! refusal fails the hook. `pre-push` also refuses a commit it would
//! send whose message has a by-trailer, a made-with line, or a
//! generated line, and it refuses when those commits cannot be read.
//! A Tests paragraph is not that line. The check runs with or without
//! a runner. `pre-push` copies stdin like `post-rewrite`.
//!
//! `pre-commit install` follows `core.hooksPath` and would replace stubs
//! ljos owns. Install the framework into the repository, then let the stub
//! chain to it:
//!
//! ```text
//! dir=$(git rev-parse --git-dir)
//! git config --local core.hooksPath "$dir/hooks"
//! pre-commit install
//! git config --local --unset core.hooksPath
//! ```
//!
//! A commit is booked only when a seat resolves from `LJOS_SEAT`, then an
//! agy or opencode conversation id. A conversation id does not name a seat.
//! The process tree is not a seat.
//! The holder is `SEAT@TAG`, the same name `ljos claim` uses. Paths in
//! `[git_hooks] skip` of `ljos.toml`, plus `/tmp`, `/var/tmp`, `/dev/shm`,
//! the tracker, `CLAIMDAG_DIR` and the deedar store, are not booked.
//! An amend or a rebase moves the citation onto the new sha.

use std::cell::Cell;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

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

/// Every hook git looks up by name. A global `core.hooksPath` hides the
/// repository's copy of each of these, so the stub has to exist for each.
const HOOK_NAMES: &[&str] = &[
    "applypatch-msg",
    "pre-applypatch",
    "post-applypatch",
    "pre-commit",
    "pre-merge-commit",
    "prepare-commit-msg",
    "commit-msg",
    "post-commit",
    "pre-rebase",
    "post-checkout",
    "post-merge",
    "pre-push",
    "pre-receive",
    "update",
    "proc-receive",
    "post-receive",
    "post-update",
    "reference-transaction",
    "push-to-checkout",
    "pre-auto-gc",
    "post-rewrite",
    "sendemail-validate",
    "fsmonitor-watchman",
    "p4-changelist",
    "p4-prepare-changelist",
    "p4-post-changelist",
    "p4-pre-submit",
    "post-index-change",
];

fn books_commit(name: &str) -> bool {
    matches!(name, "post-commit" | "post-rewrite")
}

fn gates_git(name: &str) -> bool {
    matches!(name, "pre-commit" | "pre-push")
}

/// `install`, `uninstall`, or `status`.
///
/// # Errors
///
/// `action` is not one of those, or git cannot record `core.hooksPath`.
pub fn run(action: &str) -> Result<()> {
    match action {
        "install" => {
            let dir = install()?;
            println!("installed {}", dir.display());
            Ok(())
        }
        "uninstall" => {
            uninstall()?;
            println!("uninstalled");
            Ok(())
        }
        "status" => {
            print!("{}", status());
            Ok(())
        }
        other => bail!("git-hooks: {other} is not install, uninstall, or status"),
    }
}

/// Install the hooks `ljos doctor` checks.
///
/// An unset `core.hooksPath` is pointed at ljos's hook directory. A path
/// that already names a directory is left alone, and each hook there gains
/// a block that calls `ljos git-hook`.
///
/// # Errors
///
/// The directory cannot be written, or `git config` fails.
pub fn install() -> Result<PathBuf> {
    install_at(&hooks_dir(), &[])
}

/// [`install`] into `dir`, with `git_env` on the child `git config`.
///
/// An empty `git_env` leaves that child with this process's environment.
/// `GIT_CONFIG_GLOBAL` and `HOME` belong here when the caller is keeping
/// the login config untouched.
///
/// # Errors
///
/// The directory cannot be written, or `git config` fails.
pub(crate) fn install_at(dir: &Path, git_env: &[(&str, &str)]) -> Result<PathBuf> {
    let current = global_hooks_path(git_env);
    if let Some(path) = nonempty(current.as_deref()) {
        if !same_dir(Path::new(path), dir) {
            chain_user_hooks(Path::new(path))?;
            return Ok(PathBuf::from(path));
        }
    }
    write_owned_hooks(dir)?;
    if nonempty(current.as_deref()).is_none() {
        let _ = fs::remove_file(dir.join("previous-hooks-path"));
        set_global_hooks_path(dir, git_env)?;
    }
    Ok(dir.to_path_buf())
}

/// Remove ljos from the hooks git runs.
///
/// A directory ljos does not own loses only the ljos block. A file that
/// held nothing else is deleted. When ljos owns `core.hooksPath`, the
/// previous path is restored and the stubs are removed.
///
/// # Errors
///
/// `git config` cannot restore or unset the path, or a hook file cannot
/// be rewritten.
pub fn uninstall() -> Result<()> {
    let dir = hooks_dir();
    let current = global_hooks_path(&[]);
    match nonempty(current.as_deref()) {
        Some(path) if same_dir(Path::new(path), &dir) => {
            let previous = fs::read_to_string(dir.join("previous-hooks-path"))
                .ok()
                .map(|text| text.trim().to_string())
                .filter(|text| !text.is_empty());
            if let Some(prev) = previous {
                set_global_hooks_path(Path::new(&prev), &[])?;
            } else {
                unset_global_hooks_path(&[])?;
            }
            remove_owned_hooks(&dir);
        }
        Some(path) => strip_user_hooks(Path::new(path))?,
        None => remove_owned_hooks(&dir),
    }
    Ok(())
}

/// Where the hooks are, and what `core.hooksPath` says.
#[must_use]
pub fn status() -> String {
    let dir = hooks_dir();
    let configured_path = global_hooks_path(&[]);
    let configured = configured_path.clone().unwrap_or_else(|| "(unset)".into());
    let present = nonempty(configured_path.as_deref())
        .is_some_and(|path| hooks_present(Path::new(path), &dir));
    let stale = nonempty(configured_path.as_deref())
        .filter(|_| present)
        .and_then(|path| stale_note(Path::new(path), &dir));
    let hooks = if present {
        configured.clone()
    } else if owned_installed(&dir) {
        dir.display().to_string()
    } else {
        "not installed".into()
    };
    let reach = if present && stale.is_none() {
        "ljos hooks run".to_string()
    } else if let Some(note) = stale {
        format!("ljos hooks run, but {note}; {HOOKS_FIX}")
    } else {
        format!("ljos hooks do not run; {HOOKS_FIX}")
    };
    format!("hooks: {hooks}\ncore.hooksPath: {configured}\n{reach}\n")
}

/// The start of the doctor's `git hooks` state when `core.hooksPath` is
/// unset. That row is `info`: a seat that has not onboarded books no
/// commits, and nothing else is wrong.
pub const HOOKS_UNSET: &str = "core.hooksPath is unset";

/// The one command that installs the hooks doctor checks.
pub const HOOKS_FIX: &str = "ljos git-hooks install";

/// The doctor's `git hooks` row. It passes when `ljos git-hook` runs from
/// the directory `core.hooksPath` names: ljos's own stubs, or a block in
/// each hook of a directory the user already set. The `pre-commit` and
/// `pre-push` there must carry this build's block, so that a refusal
/// fails the hook; the other hooks only book. It does not ask to take
/// that path over. An env file that sets `LJOS_GIT_HOOKS` to another
/// directory fails the row.
#[must_use]
pub fn doctor_row() -> crate::Habitat {
    let dir = hooks_dir();
    let (ok, state) = doctor_state(&dir, global_hooks_path(&[]).as_deref(), &config_ljos_dir());
    crate::Habitat {
        name: "git hooks",
        state,
        ok,
    }
}

/// [`doctor_row`] for a chosen hooks directory, the global `core.hooksPath`,
/// and the config directory that holds env files.
#[must_use]
pub fn doctor_state(dir: &Path, configured: Option<&str>, config_dir: &Path) -> (bool, String) {
    let (mut ok, mut state) = hooks_state(dir, configured);
    if let Some(drift) = env_hooks_drift(config_dir, dir) {
        ok = false;
        // A mismatch is a failed row. The unset-path prefix would keep it `info`.
        state = if state.starts_with(HOOKS_UNSET) {
            drift
        } else {
            format!("{state}; {drift}")
        };
    }
    (ok, state)
}

/// An env file under `config_dir` that sets `LJOS_GIT_HOOKS` to a directory
/// other than `onboard_dir`. The expression [`HOOKS_ENV_LINE`] writes is the
/// same directory and is not a mismatch. `None` when every assignment agrees.
#[must_use]
pub fn env_hooks_drift(config_dir: &Path, onboard_dir: &Path) -> Option<String> {
    let mut files = Vec::new();
    for name in ["env.sh", "env"] {
        let path = config_dir.join(name);
        if path.is_file() {
            files.push(path);
        }
    }
    if let Ok(entries) = fs::read_dir(config_dir) {
        let mut more: Vec<PathBuf> = entries
            .flatten()
            .map(|entry| entry.path())
            .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("env"))
            .collect();
        more.sort();
        files.extend(more);
    }
    let ours = onboard_dir.display().to_string();
    for path in files {
        let Ok(text) = fs::read_to_string(&path) else {
            continue;
        };
        for line in text.lines() {
            let Some(value) = hooks_assignment(line) else {
                continue;
            };
            if assignment_agrees(&value, onboard_dir) {
                continue;
            }
            return Some(format!(
                "{} sets LJOS_GIT_HOOKS to {value}, not {ours}, the hooks `ljos onboard` installs",
                path.display()
            ));
        }
    }
    None
}

fn hooks_assignment(line: &str) -> Option<String> {
    let line = line.trim();
    if line.is_empty() || line.starts_with('#') {
        return None;
    }
    let rest = line.strip_prefix("export ").unwrap_or(line).trim();
    let rest = rest.strip_prefix("LJOS_GIT_HOOKS=")?;
    let value = unquote_assignment(rest.trim());
    if value.is_empty() {
        None
    } else {
        Some(value)
    }
}

fn unquote_assignment(value: &str) -> String {
    let value = value.trim();
    if let Some(inner) = value
        .strip_prefix('"')
        .and_then(|text| text.strip_suffix('"'))
    {
        return inner.to_string();
    }
    if let Some(inner) = value
        .strip_prefix('\'')
        .and_then(|text| text.strip_suffix('\''))
    {
        return inner.to_string();
    }
    value.split_whitespace().next().unwrap_or("").to_string()
}

fn assignment_agrees(value: &str, onboard: &Path) -> bool {
    if value.contains("${XDG_DATA_HOME:-$HOME/.local/share}/ljos/git-hooks") {
        return true;
    }
    if value.contains('$') || value.contains('`') {
        return false;
    }
    same_dir(Path::new(value), onboard)
}

fn config_ljos_dir() -> PathBuf {
    let base = std::env::var_os("XDG_CONFIG_HOME")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME")
                .filter(|value| !value.is_empty())
                .map(|home| PathBuf::from(home).join(".config"))
        })
        .unwrap_or_else(|| PathBuf::from(".config"));
    base.join("ljos")
}

/// The `LJOS_GIT_HOOKS` line `ljos onboard` writes into a shell runner's
/// env file. It names the same directory [`install`] writes.
pub const HOOKS_ENV_LINE: &str = "\
# Git hooks directory. `ljos git-hooks install` writes the stubs here.\n\
export LJOS_GIT_HOOKS=\"${LJOS_GIT_HOOKS:-${XDG_DATA_HOME:-$HOME/.local/share}/ljos/git-hooks}\"";

/// [`doctor_row`]'s verdict for the onboard hooks at `ours` and the global
/// `core.hooksPath` git reports.
#[must_use]
pub fn hooks_state(ours: &Path, configured: Option<&str>) -> (bool, String) {
    let Some(path) = nonempty(configured) else {
        return (
            false,
            format!("{HOOKS_UNSET}, so commits are not booked; {HOOKS_FIX}"),
        );
    };
    let dir = Path::new(path);
    if hooks_reachable(dir, ours) {
        let state = if same_dir(dir, ours) {
            format!("core.hooksPath is {path}; commits are booked")
        } else {
            format!("core.hooksPath is {path}; ljos git-hook runs from those hooks")
        };
        return (true, state);
    }
    let stale = if hooks_present(dir, ours) {
        stale_note(dir, ours)
    } else {
        None
    };
    let state = if let Some(note) = stale {
        format!("core.hooksPath is {path}, but {note}; {HOOKS_FIX}")
    } else if same_dir(dir, ours) {
        format!("core.hooksPath is {path}, but some hook stubs are missing there; {HOOKS_FIX}")
    } else {
        format!("core.hooksPath is {path}, and ljos is not chained there; {HOOKS_FIX}")
    };
    (false, state)
}

fn hooks_dir() -> PathBuf {
    if let Some(dir) = std::env::var_os("LJOS_GIT_HOOKS").filter(|value| !value.is_empty()) {
        return PathBuf::from(dir);
    }
    data_home().join("ljos").join("git-hooks")
}

pub(crate) fn onboard_hooks_dir() -> PathBuf {
    hooks_dir()
}

pub(crate) fn onboard_hook_paths(dir: &Path) -> Vec<PathBuf> {
    HOOK_NAMES.iter().map(|name| dir.join(name)).collect()
}

pub(crate) fn configured_hooks_path(git_env: &[(&str, &str)]) -> Option<PathBuf> {
    let configured = global_hooks_path(git_env);
    nonempty(configured.as_deref()).map(PathBuf::from)
}

pub(crate) fn onboarding_installed() -> bool {
    let dir = hooks_dir();
    let configured = global_hooks_path(&[]);
    match nonempty(configured.as_deref()) {
        Some(path) if same_dir(Path::new(path), &dir) => owned_installed(&dir),
        Some(path) => hooks_present(Path::new(path), &dir),
        None => owned_installed(&dir),
    }
}

fn data_home() -> PathBuf {
    if let Some(dir) = std::env::var_os("XDG_DATA_HOME").filter(|value| !value.is_empty()) {
        return PathBuf::from(dir);
    }
    std::env::var_os("HOME")
        .filter(|value| !value.is_empty())
        .map(|home| PathBuf::from(home).join(".local").join("share"))
        .unwrap_or_else(|| PathBuf::from("."))
}

const BLOCK_BEGIN: &str = "# ljos:begin git-hook";
const BLOCK_END: &str = "# ljos:end git-hook";

fn nonempty(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|path| !path.is_empty())
}

fn ljos_executable() -> String {
    std::env::current_exe()
        .map(|path| path.display().to_string())
        .unwrap_or_else(|_| "ljos".to_string())
}

/// The block appended to a hook. `post-commit` and `post-rewrite` book
/// through `ljos git-hook`, and the `pre-commit` and `pre-push` blocks
/// fail the hook when it refuses. The absolute path is the fallback when
/// `ljos` is not on `PATH`; a `pre-commit` or `pre-push` with neither
/// runs nothing. `post-rewrite` and `pre-push` copy stdin when the caller
/// has not, so this block and a chained hook can both read the shas and
/// refs.
fn hook_block(name: &str) -> String {
    hook_block_for(name, &shell_quote(&ljos_executable()))
}

/// [`hook_block`] with `bin`, already quoted, as the fallback binary.
fn hook_block_for(name: &str, bin: &str) -> String {
    let (otherwise, fail) = if gates_git(name) {
        (format!("elif [ -x {bin} ]; then"), "exit 1")
    } else {
        ("else".to_string(), "true")
    };
    if matches!(name, "post-rewrite" | "pre-push") {
        return format!(
            "{BLOCK_BEGIN}\n\
             if [ -z \"${{_ljos_in:-}}\" ]; then\n\
             \t_ljos_in=$(mktemp 2>/dev/null || true)\n\
             \tif [ -n \"$_ljos_in\" ]; then\n\
             \t\tcat > \"$_ljos_in\" || true\n\
             \tfi\n\
             fi\n\
             if command -v ljos >/dev/null 2>&1; then\n\
             \tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
             \t\tljos git-hook {name} \"$@\" < \"$_ljos_in\" >&2 || {fail}\n\
             \telse\n\
             \t\tljos git-hook {name} \"$@\" >&2 || {fail}\n\
             \tfi\n\
             {otherwise}\n\
             \tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
             \t\t{bin} git-hook {name} \"$@\" < \"$_ljos_in\" >&2 || {fail}\n\
             \telse\n\
             \t\t{bin} git-hook {name} \"$@\" >&2 || {fail}\n\
             \tfi\n\
             fi\n\
             {BLOCK_END}\n"
        );
    }
    format!(
        "{BLOCK_BEGIN}\n\
         if command -v ljos >/dev/null 2>&1; then\n\
         \tljos git-hook {name} \"$@\" >&2 || {fail}\n\
         {otherwise}\n\
         \t{bin} git-hook {name} \"$@\" >&2 || {fail}\n\
         fi\n\
         {BLOCK_END}\n"
    )
}

fn has_block(text: &str, name: &str) -> bool {
    text.contains(&hook_block(name))
}

/// Whether `text` holds the block this build writes for `name`, whatever
/// binary it falls back to. Another `ljos` on the box wrote a different
/// path into the same block. A block from an older build, such as one
/// whose gated call ends in `|| true`, does not count.
fn carries_block(text: &str, name: &str) -> bool {
    // A path cannot hold NUL, so it marks where the fallback goes.
    let template = hook_block_for(name, "\0");
    let mut parts = template.split('\0');
    let (Some(head), Some(next)) = (parts.next(), parts.next()) else {
        return text.contains(&template);
    };
    text.match_indices(head).any(|(at, _)| {
        let rest = &text[at + head.len()..];
        let line = rest.find('\n').unwrap_or(rest.len());
        rest.match_indices(next)
            .take_while(|(end, _)| *end <= line)
            .any(|(end, _)| rest.starts_with(&template.replace('\0', &rest[..end])[head.len()..]))
    })
}

fn strip_block(text: &str) -> String {
    let Some(start) = text.find(BLOCK_BEGIN) else {
        return text.to_string();
    };
    let Some(rel) = text[start..].find(BLOCK_END) else {
        return text.to_string();
    };
    let mut end = start + rel + BLOCK_END.len();
    if text[end..].starts_with('\n') {
        end += 1;
    }
    let mut out = String::new();
    out.push_str(&text[..start]);
    out.push_str(&text[end..]);
    out
}

fn strip_all(text: &str) -> String {
    let mut out = text.to_string();
    loop {
        let next = strip_block(&out);
        if next == out {
            return out;
        }
        out = next;
    }
}

fn merge_block(text: &str, name: &str) -> String {
    if has_block(text, name) {
        return text.to_string();
    }
    let stripped = strip_all(text);
    let block = hook_block(name);
    if stripped.trim().is_empty() {
        return format!("#!/bin/sh\n{block}");
    }
    if stripped.ends_with('\n') {
        format!("{stripped}{block}")
    } else {
        format!("{stripped}\n{block}")
    }
}

fn block_only(text: &str) -> bool {
    matches!(text.trim(), "" | "#!/bin/sh")
}

fn hook_calls_ljos(text: &str, name: &str) -> bool {
    text.contains(&format!("ljos git-hook {name} "))
}

fn is_executable(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::metadata(path)
            .map(|meta| meta.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        path.is_file()
    }
}

fn ensure_executable(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let meta = fs::metadata(path).with_context(|| format!("git-hooks: {}", path.display()))?;
        let mode = meta.permissions().mode();
        if mode & 0o111 == 0 {
            fs::set_permissions(path, fs::Permissions::from_mode(mode | 0o111))?;
        }
    }
    Ok(())
}

fn owned_installed(dir: &Path) -> bool {
    HOOK_NAMES.iter().all(|name| {
        let path = dir.join(name);
        let Ok(text) = fs::read_to_string(&path) else {
            return false;
        };
        is_executable(&path) && (text.contains("#!/bin/sh") || hook_calls_ljos(&text, name))
    })
}

fn user_chained(dir: &Path) -> bool {
    HOOK_NAMES.iter().all(|name| {
        let path = dir.join(name);
        let Ok(text) = fs::read_to_string(&path) else {
            return false;
        };
        is_executable(&path) && hook_calls_ljos(&text, name)
    })
}

fn hooks_present(configured: &Path, ours: &Path) -> bool {
    if same_dir(configured, ours) {
        owned_installed(configured)
    } else {
        user_chained(configured)
    }
}

/// The first `pre-commit` or `pre-push` in `dir` without this build's
/// block. Git ignores the gate's refusal when that hook drops its exit
/// status.
fn stale_gate(dir: &Path) -> Option<&'static str> {
    HOOK_NAMES
        .iter()
        .copied()
        .filter(|name| gates_git(name))
        .find(|name| {
            !fs::read_to_string(dir.join(name)).is_ok_and(|text| carries_block(&text, name))
        })
}

/// Why the gated hooks in `configured` let a refusal through, or `None`.
fn stale_note(configured: &Path, ours: &Path) -> Option<String> {
    let name = stale_gate(configured)?;
    let verb = if name == "pre-push" { "push" } else { "commit" };
    let what = if same_dir(configured, ours) {
        "stub"
    } else {
        "hook's ljos block"
    };
    Some(format!(
        "the {name} {what} predates the current gate and lets a refused {verb} through"
    ))
}

fn hooks_reachable(configured: &Path, ours: &Path) -> bool {
    hooks_present(configured, ours) && stale_gate(configured).is_none()
}

fn write_owned_hooks(dir: &Path) -> Result<()> {
    fs::create_dir_all(dir).with_context(|| format!("git-hooks: {}", dir.display()))?;
    for name in HOOK_NAMES {
        let path = dir.join(name);
        fs::write(&path, hook_body(name))
            .with_context(|| format!("git-hooks: {}", path.display()))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
        }
    }
    Ok(())
}

fn chain_user_hooks(dir: &Path) -> Result<()> {
    fs::create_dir_all(dir).with_context(|| format!("git-hooks: {}", dir.display()))?;
    for name in HOOK_NAMES {
        let path = dir.join(name);
        let existing = if path.is_file() {
            Some(fs::read(&path).with_context(|| format!("git-hooks: {}", path.display()))?)
        } else {
            None
        };
        if let Some(bytes) = &existing {
            if bytes.contains(&0) || std::str::from_utf8(bytes).is_err() {
                eprintln!("ljos: {} is not a shell script; left it", path.display());
                continue;
            }
        }
        let text = existing
            .as_deref()
            .map(|bytes| std::str::from_utf8(bytes).unwrap_or(""))
            .unwrap_or("");
        let next = merge_block(text, name);
        if existing.is_none() || next != text {
            fs::write(&path, next).with_context(|| format!("git-hooks: {}", path.display()))?;
        }
        ensure_executable(&path)?;
    }
    Ok(())
}

fn strip_user_hooks(dir: &Path) -> Result<()> {
    if !dir.is_dir() {
        return Ok(());
    }
    for name in HOOK_NAMES {
        let path = dir.join(name);
        let Ok(bytes) = fs::read(&path) else {
            continue;
        };
        let Ok(text) = std::str::from_utf8(&bytes) else {
            continue;
        };
        if !text.contains(BLOCK_BEGIN) {
            continue;
        }
        let stripped = strip_all(text);
        if block_only(&stripped) {
            fs::remove_file(&path).with_context(|| format!("git-hooks: {}", path.display()))?;
        } else if stripped != text {
            fs::write(&path, stripped).with_context(|| format!("git-hooks: {}", path.display()))?;
        }
    }
    Ok(())
}

fn remove_owned_hooks(dir: &Path) {
    for name in HOOK_NAMES {
        let _ = fs::remove_file(dir.join(name));
    }
    let _ = fs::remove_file(dir.join("previous-hooks-path"));
}

fn hook_body(name: &str) -> String {
    let block = hook_block(name);
    format!(
        "#!/bin/sh\n\
         # ljos books the commit, then chains to this repository's\n\
         # .git/hooks/{name}, or to the core.hooksPath recorded in\n\
         # previous-hooks-path. Booking cannot fail the hook; a refusal\n\
         # from ljos in pre-commit or pre-push does. The chained hook's\n\
         # exit status is kept. post-rewrite and pre-push keep a copy of\n\
         # stdin for that hook.\n\
         #\n\
         # pre-commit install follows core.hooksPath and would replace this\n\
         # file. Install the framework into the repository, then re-run\n\
         # `ljos git-hooks install` if a stub was overwritten:\n\
         #   dir=$(git rev-parse --git-dir)\n\
         #   git config --local core.hooksPath \"$dir/hooks\"\n\
         #   pre-commit install\n\
         #   git config --local --unset core.hooksPath\n\
         {block}\
         git_dir=$(git rev-parse --git-dir 2>/dev/null || true)\n\
         if [ -n \"$git_dir\" ]; then\n\
         \tcase \"$git_dir\" in\n\
         \t\t/*) ;;\n\
         \t\t*) git_dir=$(pwd)/$git_dir ;;\n\
         \tesac\n\
         \trepo_hook=\"$git_dir/hooks/{name}\"\n\
         \tif [ -x \"$repo_hook\" ] && [ \"$repo_hook\" != \"$0\" ]; then\n\
         \t\tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
         \t\t\texec \"$repo_hook\" \"$@\" < \"$_ljos_in\"\n\
         \t\tfi\n\
         \t\texec \"$repo_hook\" \"$@\"\n\
         \tfi\n\
         fi\n\
         here=$(dirname \"$0\")\n\
         here=$(CDPATH= cd -- \"$here\" && pwd) || exit 0\n\
         prev=$(sed -n '1s/[[:space:]]*$//p' \"$here/previous-hooks-path\" 2>/dev/null || true)\n\
         if [ -n \"$prev\" ] && [ \"$prev\" != \"$here\" ]; then\n\
         \tprev_hook=\"$prev/{name}\"\n\
         \tif [ -x \"$prev_hook\" ] && [ \"$prev_hook\" != \"$0\" ]; then\n\
         \t\tif [ -n \"${{_ljos_in:-}}\" ]; then\n\
         \t\t\texec \"$prev_hook\" \"$@\" < \"$_ljos_in\"\n\
         \t\tfi\n\
         \t\texec \"$prev_hook\" \"$@\"\n\
         \tfi\n\
         fi\n\
         exit 0\n"
    )
}

fn shell_quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', "'\\''"))
}

/// Book the commit that just landed. Always succeeds: the commit stands.
///
/// # Errors
///
/// None. A habitat that did not answer is a line in the book log.
pub fn run_git_commit(hook: &str) -> Result<()> {
    if let Err(err) = book_commit(hook) {
        crate::bookkeep::log_line(&format!("git-hooks: {err:#}"));
    }
    Ok(())
}

/// Run the ljos part of git hook `name`.
///
/// `post-commit` and `post-rewrite` book the commit. `pre-commit` and
/// `pre-push` run the sitting gate ([`gate`]). `pre-push` also refuses
/// a pushed commit whose message matches [`line_refused`]. Any other
/// name succeeds and does nothing. Arguments git passed the hook are
/// ignored.
///
/// # Errors
///
/// The sitting gate's refusal. Booking that did not land is a line in
/// the book log.
pub fn run_named(name: &str) -> Result<()> {
    let name = name.trim();
    if books_commit(name) {
        return run_git_commit(name);
    }
    if name == "pre-push" {
        let refs = std::io::read_to_string(std::io::stdin())
            .map_err(|err| anyhow!("pre-push: cannot read the refs ({err})"))?;
        refuse_push_messages(&refs)?;
        return gate(name, &refs).map_err(|err| dropped(name, err));
    }
    if gates_git(name) {
        return gate(name, "").map_err(|err| dropped(name, err));
    }
    Ok(())
}

fn dropped(name: &str, err: anyhow::Error) -> anyhow::Error {
    match dropped_refusal(name) {
        Some(why) => anyhow!("{err:#}\n{why}"),
        None => err,
    }
}

/// Refuse when a commit the push would send cannot be read, or its
/// message has a line [`line_refused`] names. A delete sends nothing.
/// A line that is not a ref update is refused.
fn refuse_push_messages(refs: &str) -> Result<()> {
    for line in refs.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() != 4 {
            bail!("pre-push: cannot read `{line}`");
        }
        let local_sha = fields[1];
        let remote_sha = fields[3];
        if !is_object_name(local_sha) || !is_object_name(remote_sha) {
            bail!("pre-push: cannot read `{line}`");
        }
        if is_zero_name(local_sha) {
            continue;
        }
        let listed = if is_zero_name(remote_sha) {
            listed_commits(&[local_sha, "--not", "--remotes"])?
        } else {
            let range = format!("{remote_sha}..{local_sha}");
            listed_commits(&[&range])?
        };
        for sha in listed {
            let body = commit_body(&sha)?;
            if message_refused(&body) {
                bail!("pre-push: {sha} message is refused");
            }
        }
    }
    Ok(())
}

fn is_object_name(text: &str) -> bool {
    matches!(text.len(), 40 | 64) && text.bytes().all(|b| b.is_ascii_hexdigit())
}

fn is_zero_name(text: &str) -> bool {
    is_object_name(text) && text.bytes().all(|b| b == b'0')
}

fn listed_commits(args: &[&str]) -> Result<Vec<String>> {
    let mut git_args = vec!["rev-list"];
    git_args.extend_from_slice(args);
    let shown = args.join(" ");
    let out = git_command(&git_args, &[])
        .stdin(std::process::Stdio::null())
        .output()
        .with_context(|| format!("pre-push: cannot read commits in {shown}"))?;
    if !out.status.success() {
        let err = String::from_utf8_lossy(&out.stderr);
        bail!("pre-push: cannot read commits in {shown} ({})", err.trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|line| !line.is_empty())
        .map(str::to_string)
        .collect())
}

fn commit_body(sha: &str) -> Result<String> {
    let out = git_command(&["log", "-1", "--format=%B", sha], &[])
        .stdin(std::process::Stdio::null())
        .output()
        .with_context(|| format!("pre-push: cannot read {sha}"))?;
    if !out.status.success() {
        bail!("pre-push: cannot read {sha}");
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

fn message_refused(body: &str) -> bool {
    phrase_refused(&body.to_ascii_lowercase()) || body.lines().any(line_refused)
}

/// A by-trailer, a made-with line, a generated line at the start of
/// the line, or a machine account mark anywhere on the line. A Tests
/// or note paragraph is none of those. A generated phrase
/// mid-sentence is not a generated line.
fn line_refused(line: &str) -> bool {
    let lower = line.to_ascii_lowercase();
    account_anywhere(&lower) || phrase_refused(&lower) || anchored_mark(&lower)
}

/// `cursor agent` and `cursoragent` match anywhere on the line.
fn account_anywhere(lower: &str) -> bool {
    lower.contains("cursor agent") || lower.contains("cursoragent")
}

/// `generated with` and `made with cursor` match only at the start of
/// the line, after optional blanks.
fn phrase_refused(lower: &str) -> bool {
    let rest = lower.trim_start_matches([' ', '\t']);
    rest.starts_with("generated with") || rest.starts_with("made with cursor")
}

fn anchored_mark(lower: &str) -> bool {
    let rest = lower.trim_start_matches([' ', '\t']);
    made_with_mark(rest) || by_mark(rest) || cursor_assign(rest)
}

fn made_with_mark(rest: &str) -> bool {
    let Some(after) = rest.strip_prefix("made-with") else {
        return false;
    };
    after.trim_start_matches([' ', '\t']).starts_with(':')
}

fn by_mark(rest: &str) -> bool {
    let Some(colon) = rest.find(':') else {
        return false;
    };
    let token = rest[..colon].trim_end_matches([' ', '\t']);
    let Some(name) = token.strip_suffix("-by") else {
        return false;
    };
    !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
}

fn cursor_assign(rest: &str) -> bool {
    let Some(after_cursor) = rest.strip_prefix("cursor") else {
        return false;
    };
    let after_sep = after_cursor
        .strip_prefix('_')
        .or_else(|| after_cursor.strip_prefix('-'))
        .unwrap_or(after_cursor);
    let Some(after_agent) = after_sep.strip_prefix("agent") else {
        return false;
    };
    let mut end = 0;
    for c in after_agent.chars() {
        if c.is_ascii_alphanumeric() || c == '_' {
            end += c.len_utf8();
        } else {
            break;
        }
    }
    let after = after_agent[end..].trim_start_matches([' ', '\t']);
    after.starts_with('=') || after.starts_with(':')
}

/// Why git goes on after the gate refuses, when the hook file it is
/// running carries an ljos block older than this build's. Such a block
/// can end in `|| true`, and this process cannot change the exit status
/// the hook returns. A hook that calls `ljos git-hook` with no block is
/// the user's own and is not judged.
fn dropped_refusal(name: &str) -> Option<String> {
    let raw = git_line(&["rev-parse", "--git-path", &format!("hooks/{name}")])?;
    let path = std::env::current_dir().ok()?.join(raw);
    let text = fs::read_to_string(&path).ok()?;
    if !text.contains(BLOCK_BEGIN) || carries_block(&text, name) {
        return None;
    }
    let verb = if name == "pre-push" { "push" } else { "commit" };
    Some(format!(
        "sitting-gate: {} predates this gate and drops its refusal, so git will {verb} anyway; {HOOKS_FIX} replaces it",
        path.display()
    ))
}

/// The guard's sitting gate for a commit or push it did not see, such as
/// one a script runs: under a runner, `pre-commit` needs a live sitting,
/// and `pre-push` also needs that ticket to clear each ref it sends onto
/// a branch [`crate::gates::consensus_push`] names. A store or a tracker
/// checkout, which ljos writes itself, is not gated, and nor is the
/// person. When a runner variable is the only cause, and the call would
/// be refused, the person is asked for their passphrase on the
/// controlling terminal; a right answer lets this one call through.
fn gate(name: &str, refs: &str) -> Result<()> {
    let Some(cause) = crate::runner_cause() else {
        return Ok(());
    };
    let refused = match gate_runner(name, refs) {
        Ok(()) => return Ok(()),
        Err(refused) => refused,
    };
    if cause == crate::RunnerCause::Hard {
        return Err(refused);
    }
    let verb = if name == "pre-push" { "push" } else { "commit" };
    let marks = crate::runner_marks();
    match crate::person_key::ask_person(&marks, &format!("git {verb}")) {
        Ok(()) => Ok(()),
        Err(why) => {
            let detail = format!("{refused:#}");
            let detail = detail.strip_prefix("sitting-gate: ").unwrap_or(&detail);
            let text = crate::sitting_gate::for_marks(
                detail,
                &marks,
                verb,
                crate::person_key::is_set(),
                &why,
            );
            Err(anyhow!("sitting-gate: {text}"))
        }
    }
}

fn gate_runner(name: &str, refs: &str) -> Result<()> {
    let repo = git_line(&["rev-parse", "--show-toplevel"])
        .map(PathBuf::from)
        .or_else(git_dir);
    if repo
        .as_deref()
        .is_some_and(|repo| is_store(repo) || holds_tracker(repo))
    {
        return Ok(());
    }
    // A commit is not this check. The push below is.
    if name != "pre-push" {
        return Ok(());
    }
    // In a hook the process tree names the hook's own shell. The seat a
    // booking would take is the one the sitting was taken under. With a
    // conversation id in the environment only that conversation's holder
    // counts, or for a subagent its parent's records and process when
    // that process carries a conversation id. With no id it falls back
    // to the process match.
    let seat = crate::git_hook_seat();
    let _actor = seat.as_deref().map(crate::HookActor::enter);
    let _push = crate::PushCheck::enter();
    let issue = match crate::sitting_gate::live_sitting() {
        Ok(issue) => issue,
        Err(_) => {
            let named = crate::sitting_gate::open_or_name_sitting().unwrap_or_default();
            if crate::push_slow() {
                if named.is_empty() {
                    eprintln!("{}", crate::push_slow_line());
                } else {
                    eprintln!("{}; sitting {named}", crate::push_slow_line());
                }
            }
            named
        }
    };
    let cfg = match crate::gates::consensus_push(repo.as_deref()) {
        Ok(cfg) => cfg,
        Err(why) => {
            return Err(anyhow!(
                "sitting-gate: {}",
                crate::sitting_gate::unread_settings(&why)
            ))
        }
    };
    let dest = protected_ref(refs, &cfg.branches);
    let Some(dest) = dest else {
        return Ok(());
    };
    // The tracker read already missed its bound. Stop before the
    // consensus checks. Empty notes would fail as a missing family.
    if crate::push_tracker_slow() {
        return Err(anyhow!("sitting-gate: {}", crate::push_tracker_slow_line()));
    }
    if issue.is_empty() {
        let why = "the sitting has no settled consensus".to_string();
        let wait = crate::sitting_gate::seats_wait(&dest, &cfg.branches, &issue, &why);
        return Err(anyhow!("sitting-gate: {wait}"));
    }
    if let Err(reason) = crate::protected_push_refusal(&issue, &crate::seat_name(), cfg.quorum) {
        let why = format!("the sitting has no settled consensus: {reason}");
        let wait = crate::sitting_gate::seats_wait(&dest, &cfg.branches, &issue, &why);
        return Err(anyhow!("sitting-gate: {wait}"));
    }
    Ok(())
}

/// What a push whose pre-push stdin is `refs` sends onto a branch in
/// `branches`, as `sends BRANCH`, or `None` when no ref lands on one.
/// Git runs the hook with no lines when nothing is to be sent. A line
/// not in git's four-field form cannot be read, so it is taken to land
/// on one.
fn protected_ref(refs: &str, branches: &[String]) -> Option<String> {
    for line in refs.lines().filter(|l| !l.trim().is_empty()) {
        let fields: Vec<&str> = line.split_whitespace().collect();
        let [_, _, remote, _] = fields[..] else {
            return Some(format!("lists `{line}`, which is not a ref git would send"));
        };
        let Some(branch) = remote.strip_prefix("refs/heads/") else {
            continue;
        };
        if let Some(b) = branches.iter().find(|b| b.eq_ignore_ascii_case(branch)) {
            return Some(format!("sends `{b}`"));
        }
    }
    None
}

/// Whether `repo` is a tracker checkout: it holds `vissue.toml`, or a
/// `Software/<project>/issues.org` as `vissue` reads a tracker root. A
/// bare `Software/` directory is any repository's.
fn holds_tracker(repo: &Path) -> bool {
    if repo.join("vissue.toml").is_file() {
        return true;
    }
    std::fs::read_dir(repo.join("Software")).is_ok_and(|entries| {
        entries
            .flatten()
            .any(|entry| entry.path().join("issues.org").is_file())
    })
}

fn book_commit(hook: &str) -> Result<()> {
    if std::env::var_os("LJOS_GIT_HOOK").is_some() || booking_off() {
        return Ok(());
    }
    if foreign_session() {
        return Ok(());
    }
    if hook != "post-rewrite" && mid_rewrite() {
        return Ok(());
    }
    let Some(repo) = git_line(&["rev-parse", "--show-toplevel"]) else {
        return Ok(());
    };
    let repo_path = PathBuf::from(&repo);
    // A commit in the tracker's checkout is a tracker write: never booked,
    // but its seat is checked as any other write's is.
    let tracker = tracker_repo(&repo_path);
    if !tracker && (crate::bookkeep::path_is_temp(Some(&repo_path)) || skip_repo(&repo_path)) {
        return Ok(());
    }
    let Some(head) = git_line(&["rev-parse", "HEAD"]) else {
        return Ok(());
    };
    // The process tree is not a seat. Without LJOS_SEAT, or an agy or
    // opencode conversation, the commit stays unbooked; a subagent is told.
    let Some(seat) = crate::git_hook_seat() else {
        if tracker {
            refuse_tracker_commit(
                &head,
                "no seat is named; export LJOS_SEAT=<your seat> to write the tracker",
            );
        } else if crate::unseated_subagent() {
            // Stdout: the installed hook shows that line and drops stderr.
            println!(
                "ljos: commit {} not booked: this subagent has no seat; export LJOS_SEAT=<your seat> (the parent's) to book it",
                &head[..head.len().min(12)]
            );
        }
        return Ok(());
    };
    let _actor = crate::HookActor::enter(&seat);
    // Every path below writes the tracker: a repointed citation, a named
    // issue, an open sitting, a new claim.
    if let Err(e) = crate::write_seat("commit") {
        if tracker {
            refuse_tracker_commit(&head, &format!("{e:#}"));
        } else {
            println!(
                "ljos: commit {} not booked: {e:#}",
                &head[..head.len().min(12)]
            );
        }
        return Ok(());
    }
    if tracker {
        return Ok(());
    }
    let _children = HookChildren::enter();
    // An amend or a rebase lists old and new shas. Move the citation
    // before the "already booked" return: post-commit may have cited the
    // new HEAD already, and the old sha would otherwise stay on the issue.
    if already_booked(&repo, &head) {
        return Ok(());
    }
    let subject = git_line(&["log", "-1", "--format=%s"]).unwrap_or_default();
    println!(
        "{}",
        crate::bookkeep::note_after_commit(&repo, &head, &subject)
    );
    remember_booked(&repo, &head);
    Ok(())
}

fn booking_off() -> bool {
    matches!(
        std::env::var("LJOS_OFF").ok().as_deref(),
        Some("1" | "true" | "TRUE" | "yes" | "YES" | "on" | "ON")
    ) || crate::bookkeep::guard_suspended()
}

fn foreign_session() -> bool {
    // OpenCode's shell sets OPENCODE_SESSION_ID and never calls the plugin's
    // tool.execute.after, so the git hook is the booker. Claude and Codex
    // book from their own hooks.
    ["CLAUDECODE", "CODEX_THREAD_ID", "CODEX_SESSION_ID"]
        .iter()
        .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
}

fn mid_rewrite() -> bool {
    let Some(dir) = git_dir() else {
        return false;
    };
    dir.join("rebase-merge").is_dir()
        || dir.join("rebase-apply").is_dir()
        || dir.join("MERGE_HEAD").is_file()
}

/// Whether `repo` is the tracker's checkout, `VISSUE_ROOT` or `ISSUE_ROOT`.
fn tracker_repo(repo: &Path) -> bool {
    ["VISSUE_ROOT", "ISSUE_ROOT"].iter().any(|key| {
        std::env::var_os(key)
            .filter(|value| !value.is_empty())
            .map(PathBuf::from)
            .is_some_and(|root| useful_root(&root) && covered(repo, &root))
    })
}

/// A tracker commit no seat that may write the tracker made. It has landed
/// and a post-commit hook cannot take it back, so the refusal is said on
/// stdout, which the installed hook shows, and kept in the book log.
fn refuse_tracker_commit(head: &str, why: &str) {
    let line = format!(
        "ljos: tracker commit {} was not made by a seat that may write the tracker: {why}",
        &head[..head.len().min(12)]
    );
    println!("{line}");
    crate::bookkeep::log_line(&format!("git-hooks: {line}"));
}

fn skip_repo(repo: &Path) -> bool {
    if is_store(repo) {
        return true;
    }
    skip_roots().iter().any(|root| covered(repo, root))
}

/// Paths a commit under which is not booked. The defaults always apply.
/// `[git_hooks] skip` in `ljos.toml` adds box-specific paths, and a
/// reinstall rewrites the hook scripts without touching that file.
fn skip_roots() -> Vec<PathBuf> {
    let mut roots = vec![
        PathBuf::from("/tmp"),
        PathBuf::from("/var/tmp"),
        PathBuf::from("/dev/shm"),
    ];
    for key in ["VISSUE_ROOT", "ISSUE_ROOT", "CLAIMDAG_DIR"] {
        if let Some(path) = std::env::var_os(key).filter(|value| !value.is_empty()) {
            roots.push(PathBuf::from(path));
        }
    }
    roots.extend(store_dirs());
    for path in config_files() {
        roots.extend(configured_skips(&path));
    }
    roots.retain(|path| useful_root(path));
    roots
}

fn useful_root(path: &Path) -> bool {
    let text = path.to_string_lossy();
    let text = text.trim();
    !text.is_empty() && text != "/" && text != "."
}

fn config_files() -> Vec<PathBuf> {
    let mut out = Vec::new();
    let base = std::env::var_os("XDG_CONFIG_HOME")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME")
                .filter(|value| !value.is_empty())
                .map(|home| PathBuf::from(home).join(".config"))
        });
    if let Some(base) = base {
        out.push(base.join("ljos").join("ljos.toml"));
        if let Some(seat) = std::env::var("LJOS_SEAT")
            .ok()
            .map(|name| name.trim().to_string())
            .filter(|name| !name.is_empty() && !name.contains('/') && !name.contains(".."))
        {
            out.push(base.join("ljos").join("seats").join(seat).join("ljos.toml"));
        }
    }
    if let Some(path) = std::env::var_os("LJOS_CONFIG").filter(|value| !value.is_empty()) {
        out.push(PathBuf::from(path));
    }
    if let Ok(cwd) = std::env::current_dir() {
        out.push(cwd.join("ljos.toml"));
    }
    out
}

fn configured_skips(path: &Path) -> Vec<PathBuf> {
    let Ok(text) = fs::read_to_string(path) else {
        return Vec::new();
    };
    let Ok(value) = toml::from_str::<toml::Value>(&text) else {
        return Vec::new();
    };
    let Some(list) = value
        .get("git_hooks")
        .and_then(|table| table.get("skip"))
        .and_then(toml::Value::as_array)
    else {
        return Vec::new();
    };
    list.iter()
        .filter_map(toml::Value::as_str)
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(PathBuf::from)
        .collect()
}

fn covered(repo: &Path, root: &Path) -> bool {
    let repo = canonical_or(repo);
    let root = canonical_or(root);
    repo == root || repo.starts_with(&root)
}

fn canonical_or(path: &Path) -> PathBuf {
    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Whether `repo` is a deed or claim store ljos writes itself, read from
/// the store settings; a path that merely contains `claimdag` is not one.
fn is_store(repo: &Path) -> bool {
    store_dirs()
        .iter()
        .any(|root| same_dir(repo, root) || repo_starts(repo, root))
}

fn store_dirs() -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Ok(url) = std::env::var("DEEDAR_URL") {
        if let Some(path) = url.strip_prefix("file://") {
            out.push(PathBuf::from(path));
        }
    }
    if let Some(data) = std::env::var_os("XDG_DATA_HOME").filter(|value| !value.is_empty()) {
        out.push(PathBuf::from(data).join("deedar").join("store"));
    } else if let Some(home) = std::env::var_os("HOME").filter(|value| !value.is_empty()) {
        out.push(
            PathBuf::from(home)
                .join(".local")
                .join("share")
                .join("deedar")
                .join("store"),
        );
    }
    out
}

fn same_dir(left: &Path, right: &Path) -> bool {
    let left = fs::canonicalize(left).unwrap_or_else(|_| left.to_path_buf());
    let right = fs::canonicalize(right).unwrap_or_else(|_| right.to_path_buf());
    left == right
}

fn repo_starts(repo: &Path, root: &Path) -> bool {
    if !root.exists() {
        return false;
    }
    let repo = fs::canonicalize(repo).unwrap_or_else(|_| repo.to_path_buf());
    let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    repo.starts_with(root)
}

fn already_booked(repo: &str, head: &str) -> bool {
    let key = format!("{repo}\t{head}");
    fs::read_to_string(booked_path())
        .map(|text| text.lines().any(|line| line == key))
        .unwrap_or(false)
}

fn remember_booked(repo: &str, head: &str) {
    let path = booked_path();
    if let Some(dir) = path.parent() {
        let _ = fs::create_dir_all(dir);
    }
    let mut lines: Vec<String> = fs::read_to_string(&path)
        .unwrap_or_default()
        .lines()
        .map(str::to_string)
        .filter(|line| !line.starts_with(&format!("{repo}\t")))
        .collect();
    lines.push(format!("{repo}\t{head}"));
    if lines.len() > 200 {
        lines.drain(0..lines.len() - 200);
    }
    let _ = fs::write(path, lines.join("\n") + "\n");
}

fn booked_path() -> PathBuf {
    crate::runtime_dir().join("git-hooks-booked")
}

fn git_dir() -> Option<PathBuf> {
    let raw = git_line(&["rev-parse", "--git-dir"])?;
    let path = PathBuf::from(&raw);
    if path.is_absolute() {
        Some(path)
    } else {
        std::env::current_dir().ok().map(|cwd| cwd.join(path))
    }
}

/// `GIT_*` values a hook exports. A later `git -C` follows `GIT_DIR` and
/// ignores `-C`, so a tracker commit would land in the checkout that just
/// finished.
const HOOK_GIT_ENV: &[&str] = &[
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_INDEX_FILE",
    "GIT_PREFIX",
    "GIT_OBJECT_DIRECTORY",
    "GIT_COMMON_DIR",
    "GIT_NAMESPACE",
];

thread_local! {
    static HOOK_CHILDREN: Cell<bool> = const { Cell::new(false) };
}

/// While this guard is alive, child processes started through
/// [`hook_child_env`] carry `LJOS_GIT_HOOK=1` and do not inherit the hook's
/// `GIT_DIR`. Dropping it restores the previous flag. The process
/// environment is not changed.
#[must_use]
struct HookChildren {
    previous: bool,
}

impl HookChildren {
    fn enter() -> Self {
        let previous = HOOK_CHILDREN.with(Cell::get);
        HOOK_CHILDREN.with(|flag| flag.set(true));
        Self { previous }
    }
}

impl Drop for HookChildren {
    fn drop(&mut self) {
        HOOK_CHILDREN.with(|flag| flag.set(self.previous));
    }
}

/// Put the re-entry guard on a child `git` or `ljos`, and drop the hook's
/// git directory from that child. No effect unless a git hook is booking
/// a commit on this thread.
pub(crate) fn hook_child_env(cmd: &mut Command) {
    if !HOOK_CHILDREN.with(Cell::get) {
        return;
    }
    cmd.env("LJOS_GIT_HOOK", "1");
    for key in HOOK_GIT_ENV {
        cmd.env_remove(key);
    }
}

#[cfg(test)]
pub(crate) fn with_hook_children_for_test<T>(run: impl FnOnce() -> T) -> T {
    let _guard = HookChildren::enter();
    run()
}

fn git_command(args: &[&str], git_env: &[(&str, &str)]) -> Command {
    let mut cmd = crate::git_cmd();
    cmd.args(args);
    for (key, value) in git_env {
        cmd.env(key, value);
    }
    hook_child_env(&mut cmd);
    cmd
}

fn git_line(args: &[&str]) -> Option<String> {
    let out = git_command(args, &[]).output().ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8(out.stdout).ok()?;
    let text = text.trim();
    if text.is_empty() {
        None
    } else {
        Some(text.to_string())
    }
}

fn global_hooks_path(git_env: &[(&str, &str)]) -> Option<String> {
    let out = git_command(&["config", "--global", "--get", "core.hooksPath"], git_env)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8(out.stdout).ok()?;
    let text = text.trim();
    if text.is_empty() {
        None
    } else {
        Some(text.to_string())
    }
}

fn set_global_hooks_path(path: &Path, git_env: &[(&str, &str)]) -> Result<()> {
    let value = path.display().to_string();
    let status = git_command(&["config", "--global", "core.hooksPath", &value], git_env)
        .status()
        .context("git-hooks: git config")?;
    if !status.success() {
        bail!("git-hooks: could not set core.hooksPath");
    }
    Ok(())
}

fn unset_global_hooks_path(git_env: &[(&str, &str)]) -> Result<()> {
    let status = git_command(
        &["config", "--global", "--unset", "core.hooksPath"],
        git_env,
    )
    .status()
    .context("git-hooks: git config")?;
    if !status.success() {
        bail!("git-hooks: could not unset core.hooksPath");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;

    use super::*;

    fn mapped<'a>(cmd: &'a Command, key: &str) -> Option<Option<&'a OsStr>> {
        cmd.get_envs()
            .find(|(name, _)| *name == OsStr::new(key))
            .map(|(_, value)| value)
    }

    #[test]
    fn the_doctor_names_a_hooks_path_that_is_not_the_onboard_one() {
        let dir = tempfile::tempdir().unwrap();
        let ours = dir.path().join("ljos").join("git-hooks");
        let other = dir.path().join("user-hooks");
        std::fs::create_dir_all(&other).unwrap();
        let prior = "#!/bin/sh\nprintf 'user-hook\\n'\n";
        std::fs::write(other.join("post-commit"), prior).unwrap();
        let ours_s = ours.display().to_string();
        let other_s = other.display().to_string();

        let (ok, state) = super::hooks_state(&ours, None);
        assert!(!ok);
        assert!(state.starts_with(super::HOOKS_UNSET), "{state}");
        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");

        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
        assert!(!ok, "{state}");
        assert!(state.contains(&other_s), "{state}");
        assert!(!state.contains(&ours_s), "{state}");
        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");

        super::chain_user_hooks(&other).unwrap();
        let (ok, state) = super::hooks_state(&ours, Some(&other_s));
        assert!(ok, "{state}");
        assert!(state.contains("ljos git-hook runs"), "{state}");
        let hooked = std::fs::read_to_string(other.join("post-commit")).unwrap();
        assert!(hooked.starts_with(prior), "{hooked}");
        assert_eq!(
            hooked.matches("# ljos:begin git-hook").count(),
            1,
            "{hooked}"
        );
        super::chain_user_hooks(&other).unwrap();
        assert_eq!(
            std::fs::read_to_string(other.join("post-commit")).unwrap(),
            hooked
        );
        assert!(other.join("pre-push").is_file());

        super::strip_user_hooks(&other).unwrap();
        assert_eq!(
            std::fs::read_to_string(other.join("post-commit")).unwrap(),
            prior
        );
        assert!(!other.join("pre-push").exists());

        let config = dir.path().join("config");
        std::fs::create_dir_all(&config).unwrap();
        std::fs::write(
            config.join("env.sh"),
            format!("export LJOS_GIT_HOOKS={}\n", other.display()),
        )
        .unwrap();
        let drift = super::env_hooks_drift(&config, &ours).expect("a drifted env file");
        assert!(drift.contains(&other_s), "{drift}");
        assert!(drift.contains(&ours_s), "{drift}");
        let (ok, state) = super::doctor_state(&ours, None, &config);
        assert!(!ok, "{state}");
        assert!(
            !state.starts_with(super::HOOKS_UNSET),
            "a mismatch stayed info: {state}"
        );
        assert!(state.contains(&other_s), "{state}");
        assert!(state.contains(&ours_s), "{state}");

        std::fs::write(
            config.join("env.sh"),
            format!("{}\n", super::HOOKS_ENV_LINE),
        )
        .unwrap();
        assert!(super::env_hooks_drift(&config, &ours).is_none());
        let body = super::hook_body("post-rewrite");
        assert!(body.contains("mktemp"), "{body}");
        assert!(body.contains("git-hook post-rewrite"), "{body}");
        assert!(body.contains("< \"$_ljos_in\""), "{body}");
        let commit = super::hook_body("post-commit");
        assert!(!commit.contains("mktemp"), "{commit}");
        assert!(commit.contains("git-hook post-commit"), "{commit}");

        super::write_owned_hooks(&ours).unwrap();
        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
        assert!(ok, "{state}");
        std::fs::remove_file(ours.join("pre-push")).unwrap();
        let (ok, state) = super::hooks_state(&ours, Some(&ours_s));
        assert!(!ok, "{state}");
        assert!(state.contains(super::HOOKS_FIX), "{state}");
    }

    /// The `pre-push` block a build before 64e489f5 wrote. `|| true`
    /// drops the gate's refusal, so git pushes anyway.
    const OLD_PRE_PUSH: &str = "# ljos:begin git-hook\n\
        if command -v ljos >/dev/null 2>&1; then\n\
        \tljos git-hook pre-push \"$@\" >&2 || true\n\
        else\n\
        \t'/usr/local/bin/ljos' git-hook pre-push \"$@\" >&2 || true\n\
        fi\n\
        # ljos:end git-hook\n";

    #[test]
    fn the_doctor_fails_a_pre_push_stub_that_drops_a_refusal() {
        let dir = tempfile::tempdir().unwrap();
        let ours = dir.path().join("git-hooks");
        let ours_s = ours.display().to_string();
        let config = dir.path().join("config");
        super::write_owned_hooks(&ours).unwrap();
        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
        assert!(ok, "{state}");

        let fresh = super::hook_body("pre-push");
        let stale = fresh.replace(&super::hook_block("pre-push"), OLD_PRE_PUSH);
        assert_ne!(stale, fresh);
        std::fs::write(ours.join("pre-push"), &stale).unwrap();
        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
        assert!(!ok, "a stale pre-push stub passed: {state}");
        assert!(state.contains("pre-push stub predates"), "{state}");
        assert_eq!(state.matches(super::HOOKS_FIX).count(), 1, "{state}");

        let moved = fresh.replace(
            &super::shell_quote(&super::ljos_executable()),
            "'/opt/other/ljos'",
        );
        assert_ne!(moved, fresh);
        std::fs::write(ours.join("pre-push"), moved).unwrap();
        let (ok, state) = super::doctor_state(&ours, Some(&ours_s), &config);
        assert!(ok, "another fallback path failed the row: {state}");

        let user = dir.path().join("user-hooks");
        super::chain_user_hooks(&user).unwrap();
        let user_s = user.display().to_string();
        let prior = format!("#!/bin/sh\necho mine\n{OLD_PRE_PUSH}");
        std::fs::write(user.join("pre-push"), &prior).unwrap();
        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
        assert!(!ok, "a stale user block passed: {state}");
        assert!(state.contains("pre-push hook's ljos block"), "{state}");
        super::chain_user_hooks(&user).unwrap();
        let (ok, state) = super::hooks_state(&ours, Some(&user_s));
        assert!(ok, "install left the stale block: {state}");
        let hooked = std::fs::read_to_string(user.join("pre-push")).unwrap();
        assert!(hooked.starts_with("#!/bin/sh\necho mine\n"), "{hooked}");
        assert_eq!(hooked.matches("# ljos:begin git-hook").count(), 1);
        assert!(!hooked.contains("\"$@\" >&2 || true"), "{hooked}");
    }

    #[test]
    fn a_hook_that_does_not_book_succeeds() {
        super::run_named("post-checkout").unwrap();
    }

    #[test]
    fn a_pre_push_ref_list_names_the_protected_branch_it_sends() {
        let branches = vec!["develop".to_string(), "main".to_string()];
        let line = |dst: &str| format!("refs/heads/x 1111 {dst} 0000\n");
        assert_eq!(protected_ref("", &branches), None);
        assert_eq!(protected_ref(&line("refs/heads/topic"), &branches), None);
        assert_eq!(protected_ref(&line("refs/tags/main"), &branches), None);
        let both = line("refs/heads/topic") + &line("refs/heads/Main");
        assert_eq!(
            protected_ref(&both, &branches).as_deref(),
            Some("sends `main`")
        );
        let odd = protected_ref("refs/heads/x main\n", &branches).unwrap();
        assert!(odd.contains("not a ref git would send"), "{odd}");
    }

    #[test]
    fn hook_children_carry_the_guard_without_touching_the_process() {
        let before_hook = std::env::var_os("LJOS_GIT_HOOK");
        let before_dir = std::env::var_os("GIT_DIR");
        let mut plain = Command::new("true");
        plain.env("GIT_DIR", "keep");
        hook_child_env(&mut plain);
        assert_eq!(mapped(&plain, "GIT_DIR"), Some(Some(OsStr::new("keep"))));
        assert_eq!(mapped(&plain, "LJOS_GIT_HOOK"), None);

        let _guard = HookChildren::enter();
        let mut cmd = Command::new("true");
        cmd.env("GIT_DIR", "from-the-hook");
        cmd.env("PATH", "/usr/bin");
        hook_child_env(&mut cmd);
        assert_eq!(mapped(&cmd, "LJOS_GIT_HOOK"), Some(Some(OsStr::new("1"))));
        for key in HOOK_GIT_ENV {
            assert_eq!(mapped(&cmd, key), Some(None), "{key}");
        }
        assert_eq!(mapped(&cmd, "PATH"), Some(Some(OsStr::new("/usr/bin"))));
        assert_eq!(std::env::var_os("LJOS_GIT_HOOK"), before_hook);
        assert_eq!(std::env::var_os("GIT_DIR"), before_dir);
    }

    #[test]
    fn a_tests_paragraph_is_kept_and_a_by_line_is_refused() {
        assert!(!super::line_refused("Tests: cargo test"));
        assert!(!super::message_refused("note\n\nTests: cargo test\n"));
        assert!(super::line_refused("Co-authored-by: Ada <ada@example.com>"));
        assert!(super::line_refused("Signed-off-by: Ada <ada@example.com>"));
        assert!(super::message_refused(
            "note\nCo-authored-by: Ada <ada@example.com>\n"
        ));
        assert!(super::line_refused("Made-with: a tool"));
        assert!(super::line_refused("Generated with a tool"));
        assert!(super::line_refused("made with cursor"));
        assert!(!super::line_refused(
            "See Co-authored-by: Ada <ada@example.com>"
        ));
        assert!(super::line_refused("Cursor Agent wrote this"));
        assert!(super::line_refused("cursoragent"));
        assert!(super::line_refused("see cursoragent in the note"));
        assert!(super::line_refused("see a cursor agent in the note"));
        assert!(!super::line_refused("the plot was made with cursor tools"));
        assert!(super::line_refused("CURSOR_AGENT=1"));
        assert!(super::line_refused("  CURSOR_AGENT=1"));
        assert!(super::line_refused("CURSOR_AGENT: 1"));
        assert!(super::line_refused("Co-authored-by : x"));
        assert!(super::line_refused("  Co-authored-by: x"));
        assert!(super::line_refused("Made-with : x"));
        assert!(super::line_refused(" Made-with: x"));
        assert!(!super::line_refused("Note: kept"));
        assert!(!super::line_refused("The Signed-off-by line is gone."));
        assert!(!super::line_refused("see CURSOR_AGENT in the prose"));
        assert!(super::line_refused("\tCo-authored-by: A"));
        assert!(super::line_refused("Co-authored-by\t: A"));
        assert!(super::line_refused("\tCURSOR_AGENT=1"));
        assert!(super::line_refused("CURSOR_AGENT\t=1"));
        assert!(!super::line_refused(
            "The figures are generated with matplotlib."
        ));
        assert!(!super::line_refused("Tests: ran cargo test"));
        assert!(!super::line_refused("Ask the author by mail."));
        assert!(!super::line_refused("Signed-off-by"));
    }
}