silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
use anyhow::{bail, Context, Result};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use crate::check;
use crate::hash;
use crate::log;
use crate::parse;
use crate::resolve;
use crate::workspace::Workspace;

/// Hooks belong to the workspace: each event runs on every project that is not external.
pub fn run(ws: &Workspace, event: &str, args: &[String]) -> Result<()> {
    // § smn8drkh4.b@dh0rs
    match event {
        "pre-commit" => pre_commit(ws),
        "post-merge" => post_merge(ws),
        "post-rewrite" => post_rewrite(ws, args),
        "commit-msg" => commit_msg(&ws.root, args),
        "pre-merge-commit" => pre_merge_commit(ws),
        "pre-push" => pre_push(ws),
        other => bail!("unknown hook event `{other}`"),
    }
}

/// Checks a merge as the index holds it before git commits it: a failing merge into a shared
/// branch is refused, and one into a branch that is not shared warned on, as `pre-commit` does.
fn pre_merge_commit(ws: &Workspace) -> Result<()> {
    // § kehczgymw.a@nh29n
    let index = IndexTree::export(&ws.root)?;
    let outcome = check_index(ws, &index);
    index.remove()?;
    // Git read the copy as the worktree of this index, so its stat data names the copy:
    // `git merge --abort` refuses a stale index.
    crate::workspace::git(&ws.root)
        .args(["update-index", "-q", "--refresh"])
        .status()?;
    match outcome? {
        Outcome::Passed => Ok(()),
        Outcome::Refused => {
            println!("\n`pre-merge-commit` refused the merge: repair each error, then commit the merge with `git commit`.");
            crate::cache::flush();
            std::process::exit(1)
        }
        Outcome::Warned(branch) => {
            let_through("pre-merge-commit", &branch);
            Ok(())
        }
    }
}

/// The check of the index, as `pre-commit` reads it, with nothing fixed.
fn check_index(ws: &Workspace, index: &IndexTree) -> Result<Outcome> {
    let copy = index_workspace(ws, index)?;
    let mut report = check::validate(&copy, &copy.local(), true)?;
    report.harness = staged_harness(ws, &copy)?;
    report.errors.extend(stray_markers(&copy)?);
    if report.is_closed() {
        check::print_report(&report, false, None, false, &check::Owned::Off);
        return Ok(Outcome::Passed);
    }
    let (outcome, _) = failed(ws)?;
    let warned = matches!(outcome, Outcome::Warned(_));
    check::print_report(&report, false, None, warned, &check::Owned::Off);
    Ok(outcome)
}

/// Checks the commit of each branch a push updates on the remote, when the remote already
/// holds that branch or it is the default branch, and refuses the push when one fails. Git
/// writes one line per ref on stdin: local ref, local object, remote ref, remote object.
fn pre_push(ws: &Workspace) -> Result<()> {
    // § kehczgymw.b@hq4me
    let dirs: Vec<&Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
    let default = format!("refs/heads/{}", crate::published::branch(&dirs)?);
    let mut input = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut input)?;
    let absent = |sha: &str| sha.bytes().all(|b| b == b'0');
    let mut checked = BTreeSet::new();
    let mut refused = Vec::new();
    for line in input.lines().filter(|line| !line.trim().is_empty()) {
        let [_, local, remote_ref, remote] = line.split_whitespace().collect::<Vec<_>>()[..] else {
            bail!("pre-push: git wrote a line that is not `<local ref> <local object> <remote ref> <remote object>`: {line:?}");
        };
        let held = !absent(remote) || remote_ref == default;
        if absent(local) || !remote_ref.starts_with("refs/heads/") || !held {
            continue;
        }
        if checked.insert(local.to_string()) && !commit_passes(ws, local)? {
            refused.push(remote_ref.trim_start_matches("refs/heads/").to_string());
        }
    }
    if !refused.is_empty() {
        println!(
            "\n`pre-push` refused the push: {} would share a commit that fails `check`. Repair each error, commit, then push again.",
            refused.join(", ")
        );
        crate::cache::flush();
        std::process::exit(1);
    }
    Ok(())
}

/// Whether the tree `rev` commits passes `check`, read from a copy outside the repository, and
/// its report printed when it does not.
fn commit_passes(ws: &Workspace, rev: &str) -> Result<bool> {
    let dir = std::env::temp_dir().join(format!(
        "silcrow-push-{}-{}",
        std::process::id(),
        crate::published::short(rev)
    ));
    if dir.exists() {
        std::fs::remove_dir_all(&dir)?;
    }
    let report = crate::published::write_tree(&ws.root, rev, &dir).and_then(|()| {
        let copy = Workspace::at(dir.clone())?;
        let mut report = check::validate(&copy, &copy.local(), true)?;
        report.errors.extend(stray_markers(&copy)?);
        Ok(report)
    });
    std::fs::remove_dir_all(&dir)?;
    let report = report?;
    if report.is_closed() {
        return Ok(true);
    }
    println!("Commit {} fails `check`:", crate::published::short(rev));
    check::print_report(&report, false, None, false, &check::Owned::Off);
    Ok(false)
}

fn pre_commit(ws: &Workspace) -> Result<()> {
    // § gyhzk1qye.c@e714j
    let staged = staged_paths(&ws.root)?;
    let index = IndexTree::export(&ws.root)?;
    let outcome = fix_and_check_index(ws, &index, &staged);
    index.remove()?;
    match outcome? {
        Outcome::Passed => Ok(()),
        Outcome::Refused => {
            crate::cache::flush();
            std::process::exit(1)
        }
        Outcome::Warned(branch) => {
            let_through("pre-commit", &branch);
            Ok(())
        }
    }
}

/// Says why a commit whose check failed goes through on `branch`, which is not shared, `hook`
/// being the hook that let it.
fn let_through(hook: &str, branch: &str) {
    // § pga7yfvm9.e@47f7p
    println!(
        "\nThe branch `{branch}` is not shared: it is not the default branch and no remote-tracking ref bears its name. So `{hook}` reported each error as a warning and let the commit through, writing nothing `fix` rewrote. Once the branch is pushed, they block a commit, and `pre-push` refuses to update a shared branch with them."
    );
}

/// What the check of a commit came to: it passed, it refuses the commit, or it failed on a
/// branch that is not shared, which it names, and lets the commit through.
enum Outcome {
    Passed,
    Refused,
    Warned(String),
}

/// The outcome of a failed check: a warning on a branch that is not shared, else a refusal,
/// with the tag its error lines print.
fn failed(ws: &Workspace) -> Result<(Outcome, &'static str)> {
    // § pga7yfvm9.e@m3spw
    let dirs: Vec<&Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
    Ok(match crate::published::unshared(&ws.root, &dirs)? {
        Some(branch) => (Outcome::Warned(branch), "WRN"),
        None => (Outcome::Refused, "ERR"),
    })
}

/// Fixes the index copy, carries each rewrite into the index and the worktree, then checks
/// the copy: the tree the commit records.
fn fix_and_check_index(ws: &Workspace, index: &IndexTree, staged: &[PathBuf]) -> Result<Outcome> {
    // § gyhzk1qye.d@qsj7v
    let copy = index_workspace(ws, index)?;
    let unstaged = unstaged_projects(ws, &copy);
    if !unstaged.is_empty() {
        let (outcome, tag) = failed(ws)?;
        println!(
            "  {tag} {} carries a Silcrow block in the worktree but not in the index, so the commit would be checked without its project. Stage it, then commit.",
            unstaged.join(", ")
        );
        return Ok(outcome);
    }
    let mut rewritten = Vec::new();
    // § ave4h4m3g.c@dpsvj
    let projects: Vec<(&crate::workspace::ProjectRef, Option<Vec<PathBuf>>)> = copy
        .local()
        .into_iter()
        .map(|project| {
            // § j3m715h92.f@xrasx
            let rel = project.dir.strip_prefix(&index.dir).unwrap_or(&project.dir);
            let mine: Vec<PathBuf> = staged
                .iter()
                .filter_map(|path| path.strip_prefix(rel).ok().map(Path::to_path_buf))
                .collect();
            (project, Some(mine))
        })
        .collect();
    let mut fixed = |project: &crate::workspace::ProjectRef, paths: Option<Vec<PathBuf>>| {
        let rel = project.dir.strip_prefix(&index.dir).unwrap_or(&project.dir);
        rewritten.extend(paths.into_iter().flatten().map(|path| rel.join(path)));
    };
    // Projects that rewrite no decision note read nothing another writes: they run beside
    // each other, and each prints in project order what it would have printed alone.
    match (projects.len() > 1).then(|| resolve::independent_plans(&copy, &projects)) {
        Some(Some(plans)) => {
            let runs = crate::par::map(
                projects.iter().zip(plans).collect(),
                |_| 1,
                |((project, mine), plan)| {
                    let mine = mine.as_deref().unwrap_or_default();
                    crate::out::held(|| resolve::resolve_planned(&copy, project, mine, false, plan))
                },
            );
            for ((project, _), (paths, written)) in projects.iter().zip(runs) {
                crate::out::release(&written);
                fixed(project, paths?);
            }
        }
        _ => {
            for (project, mine) in &projects {
                let mine = mine.as_deref().unwrap_or_default();
                fixed(
                    project,
                    resolve::resolve_staged(&copy, project, mine, false)?,
                );
            }
        }
    }
    // § end ave4h4m3g.c
    rewritten.sort();
    rewritten.dedup();
    // § pga7yfvm9.b@37217
    let partial: Vec<String> = rewritten
        .iter()
        .filter(|rel| differs_from_index(&ws.root, rel))
        .map(|rel| rel.display().to_string())
        .collect();
    if !partial.is_empty() {
        let (outcome, tag) = failed(ws)?;
        println!(
            "  {tag} {} is partially staged and `silcrow fix` would rewrite it, so the hook writes nothing. Stage each whole, or run `silcrow fix` and stage what it wrote, then commit.",
            partial.join(", ")
        );
        return Ok(outcome);
    }
    // § end pga7yfvm9.b
    let mut report = check::validate(&copy, &copy.local(), true)?;
    report.harness = staged_harness(ws, &copy)?;
    report.errors.extend(stray_markers(&copy)?);
    if !report.is_closed() {
        // § pga7yfvm9.a@9ynav
        // A failed check writes nothing back: an id minted for a `+name` that a file left
        // out of the index also names would leave that file a pointer `fix` cannot resolve.
        let (outcome, _) = failed(ws)?;
        check::print_report(
            &report,
            false,
            None,
            matches!(outcome, Outcome::Warned(_)),
            &check::Owned::Off,
        );
        return Ok(outcome);
    }
    check::print_report(&report, false, None, false, &check::Owned::Off);
    crate::walk::forget();
    for rel in &rewritten {
        std::fs::copy(index.dir.join(rel), ws.root.join(rel))?;
    }
    restage(&ws.root, &rewritten)?;
    Ok(Outcome::Passed)
}

/// The workspace the index holds. The index keeps a nested repository as a gitlink or not at
/// all, so each external project is read from the worktree.
fn index_workspace(ws: &Workspace, index: &IndexTree) -> Result<Workspace> {
    // § gyhzk1qye.d@ctdmj
    let mut copy = Workspace::discover(&index.dir)?;
    for project in ws.projects.iter().filter(|project| project.external) {
        if copy.get(&project.key).is_none() {
            copy.projects.push(project.clone());
        }
    }
    copy.projects.sort_by(|a, b| a.key.cmp(&b.key));
    Ok(copy)
}

/// The `AGENTS.md` of each project of the worktree that the index does not hold as a project.
fn unstaged_projects(ws: &Workspace, copy: &Workspace) -> Vec<String> {
    // § pga7yfvm9.c@7s2aq
    ws.local()
        .into_iter()
        .filter(|project| copy.get(&project.key).is_none_or(|staged| staged.external))
        .map(|project| {
            crate::workspace::in_workspace(&project.key, Path::new("AGENTS.md"))
                .display()
                .to_string()
        })
        .collect()
}

/// The versioned harness of the index that differs from what this binary writes, each named by
/// its path in the workspace: unstaged when the worktree holds it as this binary writes it.
fn staged_harness(ws: &Workspace, copy: &Workspace) -> Result<Vec<String>> {
    // § gyhzk1qye.d@9m5hv
    let versioned =
        |root: &Path, projects: Vec<&crate::workspace::ProjectRef>| -> Result<Vec<PathBuf>> {
            let mut out = Vec::new();
            for d in crate::harness::workspace_drift(root)? {
                if d.versioned {
                    out.push(d.path);
                }
            }
            for project in projects {
                if let Some(d) = crate::harness::project_drift(&project.dir)? {
                    out.push(d.path);
                }
            }
            Ok(out
                .into_iter()
                .map(|path| path.strip_prefix(root).unwrap_or(&path).to_path_buf())
                .collect())
        };
    let worktree = versioned(&ws.root, ws.local())?;
    Ok(versioned(&copy.root, copy.local())?
        .into_iter()
        .map(|rel| {
            if !worktree.contains(&rel) {
                format!(
                    "{} is not staged as `silcrow install` wrote it. Stage it, with `git add -f` when git ignores it.",
                    rel.display()
                )
            } else if copy.root.join(&rel).exists() {
                format!(
                    "{} differs from this binary. Run `silcrow install`, then stage it.",
                    rel.display()
                )
            } else {
                format!(
                    "{} is missing. Run `silcrow install`, then stage it.",
                    rel.display()
                )
            }
        })
        .collect())
}

/// Each marker or end in a file outside every project, which no project checks. A workspace
/// with no project has Silcrow installed nowhere, so it has none.
pub fn stray_markers(ws: &Workspace) -> Result<Vec<String>> {
    // § r4dndth75.e@cn6wy
    let mut out = Vec::new();
    if ws.projects.is_empty() {
        return Ok(out);
    }
    for path in crate::walk::files_outside_projects(&ws.root)? {
        let text =
            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        if !text.contains('§') {
            continue;
        }
        let dialect = crate::marker::Dialect::of(&path);
        let fenced = crate::marker::fenced_lines(dialect.is_markdown(), &text);
        let rel = path.strip_prefix(&ws.root).unwrap_or(&path);
        for (idx, line) in text.lines().enumerate() {
            let line = line.trim();
            if fenced[idx] || !crate::marker::opens_like_a_marker(line) || !dialect.opens_with(line)
            {
                continue;
            }
            out.push(format!(
                "{}:{}: `{line}` is in a file outside every project, so no project checks it. Move it into a project, or give its directory, or one above it, an `AGENTS.md` with a Silcrow block.",
                rel.display(),
                idx + 1
            ));
        }
    }
    Ok(out)
}

/// Whether the worktree holds `rel` with content the index does not: a partially staged file.
fn differs_from_index(root: &Path, rel: &Path) -> bool {
    !crate::workspace::git(root)
        .args(["diff", "--quiet", "--"])
        .arg(rel)
        .status()
        .is_ok_and(|status| status.success())
}

/// The index written out as a tree beside the repository, read through the same git
/// directory so the default branch and the scheme trailers resolve as from the worktree.
struct IndexTree {
    dir: PathBuf,
}

impl IndexTree {
    fn export(root: &Path) -> Result<Self> {
        let git_dir = git_line(root, &["rev-parse", "--absolute-git-dir"])?;
        let dir = PathBuf::from(&git_dir).join("silcrow-index");
        write_index(root, &dir, true)?;
        crate::walk::forget();
        // § faq86xmas.f@e6c0w
        if std::env::var_os("SILCROW_CACHE_VERIFY").is_some() {
            let full = PathBuf::from(&git_dir).join("silcrow-index-full");
            write_index(root, &full, false)?;
            let (fast, all) = (tree_of(&dir)?, tree_of(&full)?);
            std::fs::remove_dir_all(&full)?;
            if fast != all {
                bail!(
                    "the index written from the worktree differs from the index git writes at {}",
                    dir.display()
                );
            }
        }
        // § end faq86xmas.f
        std::fs::write(dir.join(".git"), format!("gitdir: {git_dir}\n"))?;
        Ok(Self { dir })
    }

    fn remove(&self) -> Result<()> {
        crate::walk::forget();
        remove_tree(&self.dir)
    }
}

/// Writes the index as a tree at `dir`. With `from_worktree`, a staged file the worktree holds
/// as staged is copied from it, and git writes the rest.
fn write_index(root: &Path, dir: &Path, from_worktree: bool) -> Result<()> {
    if dir.exists() {
        remove_tree(dir)?;
    }
    std::fs::create_dir_all(dir)?;
    let mut checkout = crate::workspace::git(root);
    checkout
        .args(["checkout-index", "--force"])
        .arg(format!("--prefix={}/", dir.display()));
    let rest = match from_worktree {
        true => cloned_from_worktree(root, dir),
        false => None,
    };
    let ok = match rest {
        Some(rest) if rest.is_empty() => true,
        Some(rest) => {
            checkout
                .args(["-z", "--stdin"])
                .stdin(std::process::Stdio::piped());
            let mut child = checkout.spawn()?;
            let mut stdin = child.stdin.take().expect("piped stdin");
            let paths: Vec<u8> = rest.iter().flat_map(|p| p.bytes().chain([0])).collect();
            std::io::Write::write_all(&mut stdin, &paths)?;
            drop(stdin);
            child.wait()?.success()
        }
        None => checkout.arg("--all").status()?.success(),
    };
    if !ok {
        bail!(
            "git checkout-index could not write the index to {}",
            dir.display()
        );
    }
    Ok(())
}

/// Removes the tree at `dir`, its files on every core, then its directories, deepest first.
fn remove_tree(dir: &Path) -> Result<()> {
    let mut files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];
    let mut at = 0;
    while at < dirs.len() {
        for item in std::fs::read_dir(&dirs[at])? {
            let item = item?;
            match item.file_type()?.is_dir() {
                true => dirs.push(item.path()),
                false => files.push(item.path()),
            }
        }
        at += 1;
    }
    for removed in crate::par::map_many(files, std::fs::remove_file) {
        removed?;
    }
    for dir in dirs.iter().rev() {
        std::fs::remove_dir(dir)?;
    }
    Ok(())
}

/// Every file and link under `dir`, by its path, with its bytes or target and whether it runs.
fn tree_of(dir: &Path) -> Result<std::collections::BTreeMap<PathBuf, (Vec<u8>, bool)>> {
    let mut out = std::collections::BTreeMap::new();
    let mut dirs = vec![dir.to_path_buf()];
    while let Some(at) = dirs.pop() {
        for item in std::fs::read_dir(&at)? {
            let path = item?.path();
            let meta = std::fs::symlink_metadata(&path)?;
            let rel = path.strip_prefix(dir).unwrap_or(&path).to_path_buf();
            if meta.is_dir() {
                dirs.push(path);
            } else if meta.file_type().is_symlink() {
                let target = std::fs::read_link(&path)?;
                out.insert(rel, (target.to_string_lossy().as_bytes().to_vec(), false));
            } else {
                out.insert(rel, (std::fs::read(&path)?, runs(&meta)));
            }
        }
    }
    Ok(out)
}

/// Copies into `dir` each staged file whose worktree bytes are its staged blob, checked on the
/// copy itself, and returns the paths git has to write: every other entry of the index. None
/// when the index cannot be read this way, which a full export then covers: a conflict, a
/// sparse checkout, or a repository whose objects are not named by SHA-1.
fn cloned_from_worktree(root: &Path, dir: &Path) -> Option<Vec<String>> {
    // § pga7yfvm9@zsq1m
    let format = git_line(root, &["rev-parse", "--show-object-format"]).ok()?;
    let sparse = git_line(root, &["config", "--bool", "core.sparseCheckout"]).ok();
    if format != "sha1" || sparse.as_deref() == Some("true") {
        return None;
    }
    let out = crate::workspace::git(root)
        .args(["ls-files", "--stage", "-z"])
        .output()
        .ok()
        .filter(|out| out.status.success())?;
    let mut entries = Vec::new();
    for record in out.stdout.split(|&b| b == 0).filter(|r| !r.is_empty()) {
        let record = std::str::from_utf8(record).ok()?;
        let (meta, path) = record.split_once('\t')?;
        let mut fields = meta.split(' ');
        let (mode, blob, stage) = (fields.next()?, fields.next()?, fields.next()?);
        if stage != "0" {
            return None;
        }
        entries.push((mode.to_string(), blob.to_string(), path.to_string()));
    }
    let copied = crate::par::map_many(entries, |(mode, blob, path)| {
        let same = matches!(mode.as_str(), "100644" | "100755")
            && copy_if_staged(&root.join(&path), &dir.join(&path), &blob, mode == "100755");
        (!same).then_some(path)
    });
    Some(copied.into_iter().flatten().collect())
}

/// Copies the regular file `from` to `to` and keeps the copy only when it holds the blob `blob`
/// with the executable bit `executable`, as git would write it.
fn copy_if_staged(from: &Path, to: &Path, blob: &str, executable: bool) -> bool {
    let regular = std::fs::symlink_metadata(from).is_ok_and(|m| m.file_type().is_file());
    let copied = regular
        && to
            .parent()
            .is_some_and(|p| std::fs::create_dir_all(p).is_ok())
        && std::fs::copy(from, to).is_ok();
    if !copied {
        return false;
    }
    let held = std::fs::read(to).is_ok_and(|bytes| crate::workspace::blob_id(&bytes) == blob);
    let mode = std::fs::metadata(to).is_ok_and(|m| runs(&m) == executable);
    if held && mode {
        return true;
    }
    let _ = std::fs::remove_file(to);
    false
}

#[cfg(unix)]
fn runs(meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::PermissionsExt;
    meta.permissions().mode() & 0o111 != 0
}

#[cfg(not(unix))]
fn runs(_: &std::fs::Metadata) -> bool {
    false
}

fn git_line(root: &Path, args: &[&str]) -> Result<String> {
    let out = crate::workspace::git(root).args(args).output()?;
    if !out.status.success() {
        bail!(
            "git {}: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn staged_paths(root: &Path) -> Result<Vec<PathBuf>> {
    let out = crate::workspace::git(root)
        .args(["diff", "--cached", "--name-only"])
        .output()?;
    if !out.status.success() {
        return Ok(Vec::new());
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|line| !line.is_empty())
        .map(PathBuf::from)
        .collect())
}

fn restage(root: &Path, paths: &[PathBuf]) -> Result<()> {
    for rel in paths {
        let Some(path) = rel.to_str() else {
            continue;
        };
        let status = crate::workspace::git(root)
            .args(["add", "--", path])
            .status()?;
        if !status.success() {
            bail!("git add failed for {}", rel.display());
        }
    }
    Ok(())
}

fn post_merge(ws: &Workspace) -> Result<()> {
    eprintln!("silcrow: post-merge semantic collision check");
    let mut report = check::validate(ws, &ws.local(), true)?;
    report.errors.extend(stray_markers(ws)?);
    // § dveb6b5vj@et8mm
    let merge_report = crate::merge::parent_conflicts(ws)?;
    report.errors.extend(merge_report.errors);
    report.warnings.extend(merge_report.warnings);
    // § end dveb6b5vj
    // § gyhzk1qye.e@2adk2
    if !check::print_report(&report, false, None, false, &check::Owned::Off) {
        crate::cache::flush();
        std::process::exit(1);
    }
    // § end gyhzk1qye.e
    Ok(())
}

fn post_rewrite(ws: &Workspace, args: &[String]) -> Result<()> {
    // § rwvvdms6f@na3cq
    let before = rewritten_commit(
        &ws.root,
        args.first().map(String::as_str),
        &mut std::io::stdin().lock(),
    )?;
    let mut report = check::validate(ws, &ws.local(), true)?;
    report.errors.extend(stray_markers(ws)?);
    for project in ws.local() {
        let (genealogy_errors, genealogy_warnings) =
            verify_rewrite_genealogy(&project.dir, before.as_deref())?;
        report.errors.extend(genealogy_errors);
        report.warnings.extend(genealogy_warnings);
    }
    // § gyhzk1qye.e@nha2h
    if !check::print_report(&report, false, None, false, &check::Owned::Off) {
        crate::cache::flush();
        std::process::exit(1);
    }
    // § end gyhzk1qye.e
    Ok(())
}

/// The commit a rewrite replaced: the old commit git passes on stdin for an amend, which leaves
/// `ORIG_HEAD` where an earlier command put it, else `ORIG_HEAD`, which a rebase sets.
fn rewritten_commit(
    root: &Path,
    kind: Option<&str>,
    stdin: &mut dyn std::io::BufRead,
) -> Result<Option<String>> {
    // § rwvvdms6f@f88xj
    if kind == Some("amend") {
        let mut line = String::new();
        stdin.read_line(&mut line)?;
        let Some(old) = line.split_whitespace().next() else {
            bail!("post-rewrite after an amend got no `<old> <new>` line on stdin");
        };
        return Ok(Some(old.to_string()));
    }
    let out = crate::workspace::git(root)
        .args(["rev-parse", "--verify", "-q", "ORIG_HEAD"])
        .output()?;
    Ok(out
        .status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()))
}

const GENEALOGY_CAP: usize = 50;

fn verify_rewrite_genealogy(
    root: &Path,
    before: Option<&str>,
) -> Result<(Vec<String>, Vec<String>)> {
    let scan = parse::scan_root(root)?;
    let live: Vec<(String, PathBuf)> = scan
        .laws
        .iter()
        .filter(|law| !hash::is_provisional_id(&law.id))
        .map(|law| (law.id.clone(), law.loc.path.clone()))
        .collect();
    let (changed, existed_before) = match before {
        Some(before) => (
            rewrite_changed_paths(root, before)?,
            pre_rewrite_law_ids(root, before)?,
        ),
        None => (BTreeSet::new(), BTreeSet::new()),
    };
    let (ids, capped) = select_genealogy_ids(&live, &changed, GENEALOGY_CAP);
    let (errors, mut warnings) = if ids.is_empty() {
        (Vec::new(), Vec::new())
    } else {
        log::genealogy_check(root, &ids, &existed_before)
    };
    warnings.extend(capped);
    Ok((errors, warnings))
}

fn rewrite_changed_paths(root: &Path, before: &str) -> Result<BTreeSet<PathBuf>> {
    let out = crate::workspace::git(root)
        .args(["diff", "--relative", "--name-only", before, "HEAD"])
        .output()?;
    if !out.status.success() {
        return Ok(BTreeSet::new());
    }
    Ok(String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|line| !line.is_empty())
        .map(PathBuf::from)
        .collect())
}

fn pre_rewrite_law_ids(root: &Path, before: &str) -> Result<BTreeSet<String>> {
    let mut ids = BTreeSet::new();
    let project = crate::walk::Project::at(root)?;
    let out = crate::workspace::git(root)
        .args(["ls-tree", "-r", "--name-only", before, "--"])
        .args(
            project
                .notes
                .roots()
                .iter()
                .map(|dir| match dir.as_os_str().is_empty() {
                    true => Path::new("."),
                    false => dir.as_path(),
                }),
        )
        .output()?;
    if !out.status.success() {
        return Ok(ids);
    }
    for rel in String::from_utf8_lossy(&out.stdout).lines() {
        if rel.is_empty() || !project.is_note(Path::new(rel)) {
            continue;
        }
        let scan = scan_at_rev(root, before, &PathBuf::from(rel));
        for law in scan.laws {
            if !hash::is_provisional_id(&law.id) {
                ids.insert(law.id);
            }
        }
    }
    Ok(ids)
}

fn scan_at_rev(root: &Path, rev: &str, rel: &Path) -> parse::Scan {
    let spec = format!("{}:./{}", rev, rel.to_string_lossy());
    let out = crate::workspace::git(root)
        .args(["show", &spec])
        .output()
        .ok();
    let Some(out) = out else {
        return parse::Scan::default();
    };
    if !out.status.success() {
        return parse::Scan::default();
    }
    let Ok(text) = String::from_utf8(out.stdout) else {
        return parse::Scan::default();
    };
    parse::scan_text(rel, &text)
}

/// Every live law under the cap, else only the laws of changed notes, with a warning that
/// names the cap and how many laws went unverified.
fn select_genealogy_ids(
    live: &[(String, PathBuf)],
    changed: &BTreeSet<PathBuf>,
    cap: usize,
) -> (Vec<String>, Option<String>) {
    if live.len() < cap {
        return (live.iter().map(|(id, _)| id.clone()).collect(), None);
    }
    let ids: Vec<String> = live
        .iter()
        .filter(|(_, path)| changed.contains(path))
        .map(|(id, _)| id.clone())
        .collect();
    let skipped = live.len() - ids.len();
    let warning = (skipped > 0).then(|| {
        format!(
            "genealogy: {} live laws reach GENEALOGY_CAP ({cap}): verified the {} in changed notes, skipped {skipped}",
            live.len(),
            ids.len()
        )
    });
    (ids, warning)
}

fn commit_msg(root: &Path, args: &[String]) -> Result<()> {
    // § k2xswz12t.a@zk6zb
    let Some(msg_path) = args.first() else {
        return Ok(());
    };
    let path = PathBuf::from(msg_path);
    let mut body = std::fs::read_to_string(&path)?;
    // § k2xswz12t.c@1124d
    let staged = staged_paths(root)?;
    if staged.is_empty() {
        return Ok(());
    }
    // § gyhzk1qye.d@e5by9
    // The commit records the index, so the laws it names are read there, not in the worktree.
    let index = IndexTree::export(root)?;
    let named = staged_law_ids(&index.dir, &staged).and_then(|ids| declared_only(&index.dir, ids));
    index.remove()?;
    // § end gyhzk1qye.d
    if named?.is_empty() {
        return Ok(());
    }
    // § end k2xswz12t.c
    let recorded = recorded_scheme(root)?;
    let current = crate::scheme::BINARY_VERSION;
    // § k2xswz12t.b@xz8xf
    let alone = match recorded {
        Some(scheme) if scheme != current => {
            let alone = only_minted_tokens_staged(root)?;
            if !alone {
                eprintln!(
                    "silcrow: the scheme moves from {scheme} to {current} in a change that moves more than digests, ids and alias anchors. A scheme remint travels alone, so this commit records the scheme without `Silcrow-Op: remint`."
                );
            }
            alone
        }
        _ => false,
    };
    // § end k2xswz12t.b
    let trailers = scheme_trailers(recorded, current, alone, &body);
    if trailers.is_empty() {
        return Ok(());
    }
    if !body.ends_with('\n') {
        body.push('\n');
    }
    body.push_str(&format!("\n{}\n", trailers.join("\n")));
    std::fs::write(path, body)?;
    Ok(())
}

/// The trailers that record the scheme: the scheme whenever it differs from the one git
/// recorded, beside the mark when the change is a remint alone.
fn scheme_trailers(recorded: Option<u32>, current: u32, remint: bool, body: &str) -> Vec<String> {
    // § k2xswz12t.a@p84z0
    if body.contains("Silcrow-Scheme:") || recorded == Some(current) {
        return Vec::new();
    }
    let mut out = Vec::new();
    // § k2xswz12t.b@p88ab
    if recorded.is_some() && remint && !body.contains("Silcrow-Op:") {
        out.push("Silcrow-Op: remint".to_string());
    }
    // § end k2xswz12t.b
    out.push(format!("Silcrow-Scheme: {current}"));
    out
}

/// Whether the staged change moves only minted tokens.
fn only_minted_tokens_staged(root: &Path) -> Result<bool> {
    // § k2xswz12t.b@cvwyj
    let diff = git_line(
        root,
        &["diff", "--cached", "--no-color", "--no-ext-diff", "-U0"],
    )?;
    Ok(only_minted_tokens(&diff))
}

/// Whether the patch `diff` moves only minted tokens: every line it removes reads as a line it
/// adds once digests and ids are blanked and alias anchors dropped.
pub fn only_minted_tokens(diff: &str) -> bool {
    static TOKEN_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(&format!(
            r#"<a id="{id}"></a>|@{digest}(?:{digest})?|\b{id}\b"#,
            id = crate::marker::ID,
            digest = crate::marker::DIGEST
        ))
        .expect("minted token regex")
    });
    let blank = |line: &str| {
        TOKEN_RE
            .replace_all(
                line,
                |caps: &regex::Captures| {
                    if caps[0].starts_with('<') {
                        ""
                    } else {
                        "~"
                    }
                },
            )
            .into_owned()
    };
    let (mut gone, mut came) = (Vec::new(), Vec::new());
    for line in diff.lines() {
        if line.starts_with("---") || line.starts_with("+++") {
            continue;
        }
        if let Some(rest) = line.strip_prefix('-') {
            gone.push(blank(rest));
        } else if let Some(rest) = line.strip_prefix('+') {
            came.push(blank(rest));
        }
    }
    gone.sort();
    came.sort();
    gone == came
}

fn recorded_scheme(root: &Path) -> Result<Option<u32>> {
    recorded_scheme_at(root, "HEAD")
}

/// The scheme of the last commit in the history of `rev` that carries `Silcrow-Scheme`.
pub fn recorded_scheme_at(root: &Path, rev: &str) -> Result<Option<u32>> {
    // § k2xswz12t.a@fvqn4
    let born = crate::workspace::git(root)
        .args(["rev-parse", "--verify", "-q", rev])
        .output()?;
    if !born.status.success() {
        return Ok(None);
    }
    let out = crate::workspace::git(root)
        .args([
            "log",
            "-1",
            "-E",
            "--grep=^Silcrow-Scheme: ",
            "--format=%B",
            rev,
        ])
        .output()?;
    if !out.status.success() {
        bail!("git log failed while reading Silcrow-Scheme");
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let Some(value) = text
        .lines()
        .filter_map(|line| line.strip_prefix("Silcrow-Scheme:"))
        .next_back()
    else {
        return Ok(None);
    };
    let value = value.trim();
    match value.parse() {
        Ok(n) => Ok(Some(n)),
        Err(_) => bail!("Silcrow-Scheme trailer `{value}` is not a scheme number"),
    }
}

/// The ids the staged files name, read from `index`, the index written out.
fn staged_law_ids(index: &Path, staged: &[PathBuf]) -> Result<Vec<String>> {
    let mut ids = Vec::new();
    for rel in staged {
        let Ok(text) = std::fs::read_to_string(index.join(rel)) else {
            continue;
        };
        let mut scan = parse::Scan::default();
        if crate::walk::is_note_in(index, rel)? {
            parse::parse_note_text(rel, &text, &mut scan);
            for law in &scan.laws {
                ids.push(law.id.clone());
            }
        }
        for row in crate::span::marker_rows(rel, &text, None) {
            ids.extend(row.markers.into_iter().map(|marker| marker.id));
        }
    }
    ids.sort();
    ids.dedup();
    Ok(ids)
}

/// The ids the workspace declares, so a staged fixture id in a test points at no law.
fn declared_only(root: &Path, ids: Vec<String>) -> Result<Vec<String>> {
    // § k2xswz12t.c@b715x
    if ids.is_empty() {
        return Ok(ids);
    }
    let mut declared = BTreeSet::new();
    for project in Workspace::discover(root)?.local() {
        for law in parse::scan_root(&project.dir)?.laws {
            declared.extend(law.aliases);
            declared.insert(law.id);
        }
    }
    Ok(ids.into_iter().filter(|id| declared.contains(id)).collect())
}

pub fn script(root: &Path, event: &str) -> String {
    // § gyhzk1qye.c@mha7m
    // Git runs a hook from the root of the worktree that commits, so the script names no
    // path and every linked worktree shares it.
    if is_silcrow_repo(root) {
        // § vz45j4qce@3a4ef
        format!("#!/bin/sh\nset -e\nexec cargo run -q -- hook {event} \"$@\"\n")
    } else {
        format!("#!/bin/sh\nset -e\nexec silcrow hook {} \"$@\"\n", event)
    }
}

/// The hooks directory git runs for the worktree at `root`, `None` when `root` has no `.git` or
/// is the index tree a hook writes inside the git directory. A linked worktree's `.git` is a
/// file, and its hooks are those of the common git directory.
pub fn hooks_dir(root: &Path) -> Result<Option<PathBuf>> {
    // § gyhzk1qye.a@r5d65
    let dot_git = root.join(".git");
    if !dot_git.exists() {
        return Ok(None);
    }
    if dot_git.is_file() {
        let link = std::fs::read_to_string(&dot_git)?;
        // § gyhzk1qye.b@39thf
        let Some(git_dir) = link.trim().strip_prefix("gitdir: ") else {
            bail!(
                "{} is a file that names no `gitdir:`, so its hooks cannot be found",
                dot_git.display()
            );
        };
        // § end gyhzk1qye.b
        if root.starts_with(git_dir) {
            return Ok(None);
        }
        let path = PathBuf::from(git_line(root, &["rev-parse", "--git-path", "hooks"])?);
        return Ok(Some(if path.is_absolute() {
            path
        } else {
            root.join(path)
        }));
    }
    let out = crate::workspace::git(root)
        .args(["config", "--get", "core.hooksPath"])
        .output()?;
    let configured = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if !out.status.success() || configured.is_empty() {
        return Ok(Some(dot_git.join("hooks")));
    }
    let path = PathBuf::from(configured);
    Ok(Some(if path.is_absolute() {
        path
    } else {
        root.join(path)
    }))
}

const EVENTS: [&str; 6] = [
    "pre-commit",
    "post-merge",
    "post-rewrite",
    "commit-msg",
    "pre-merge-commit",
    "pre-push",
];

/// The line a hook of another tool adds to run Silcrow on `event`.
fn call_line(root: &Path, event: &str) -> String {
    let script = script(root, event);
    let exec = script.lines().last().unwrap_or_default();
    exec.replacen("exec ", "", 1)
}

/// Whether `text` is a script some Silcrow writes for `event`, whatever its build and its
/// repository path, so `install` may overwrite it.
fn is_ours(text: &str, event: &str) -> bool {
    let event = regex::escape(event);
    regex::Regex::new(&format!(
        r#"^#!/bin/sh\nset -e\n(?:cd '[^'\n]*' && )?exec (?:silcrow|cargo run -q --) hook {event} "\$@"\n$"#
    ))
    .expect("hook script regex")
    .is_match(text)
}

/// The state of the hook of `event` against what this binary writes.
enum HookState {
    Current,
    Write(Option<String>),
    /// A file Silcrow did not write: it is never read, overwritten or counted as installed.
    Foreign,
}

/// Whether git runs the file at `path`: on Unix, only when it is executable.
fn executable(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        true
    }
}

fn hook_state(root: &Path, path: &Path, event: &str) -> HookState {
    // § hqv22s05t.b@2jqvh
    match std::fs::read(path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => HookState::Write(None),
        Ok(bytes) => match String::from_utf8(bytes) {
            Ok(old) if old == script(root, event) && executable(path) => HookState::Current,
            Ok(old) if is_ours(&old, event) => HookState::Write(Some(old)),
            _ => HookState::Foreign,
        },
        Err(_) => HookState::Foreign,
    }
}

/// Hooks whose script differs from the one this binary writes, each with the line
/// `silcrow hook <event> "$@"` to add to it when another tool wrote it.
pub fn drift(root: &Path) -> Result<Vec<(PathBuf, Option<String>)>> {
    // § gyhzk1qye.a@fde27
    let Some(dir) = hooks_dir(root)? else {
        return Ok(Vec::new());
    };
    Ok(EVENTS
        .iter()
        .filter_map(|event| {
            let path = dir.join(event);
            match hook_state(root, &path, event) {
                HookState::Current => None,
                HookState::Write(_) => Some((path, None)),
                HookState::Foreign => Some((path, Some(call_line(root, event)))),
            }
        })
        .collect())
}

/// Hooks whose script is the one this binary writes, so `eject` may delete them.
pub fn installed(root: &Path) -> Result<Vec<PathBuf>> {
    let Some(dir) = hooks_dir(root)? else {
        return Ok(Vec::new());
    };
    Ok(EVENTS
        .iter()
        .map(|event| (dir.join(event), script(root, event)))
        .filter(|(path, body)| std::fs::read_to_string(path).ok().as_deref() == Some(body.as_str()))
        .map(|(path, _)| path)
        .collect())
}

/// Where a hook Silcrow did not write came from, and what to do with it: the copy of the git
/// template `git init` made, which a person may delete, or the file of a hook manager it knows.
pub fn foreign_origin(root: &Path, path: &Path) -> Option<String> {
    // § hqv22s05t.c@nh2nh
    let text = std::fs::read(path).ok()?;
    let event = path.file_name()?.to_str()?;
    if let Some(dir) = template_dir(root) {
        if std::fs::read(dir.join("hooks").join(event)).ok().as_deref() == Some(text.as_slice()) {
            return Some(format!(
                "it is the copy of `{}` that `git init` made from your git template, not a hook of this repository: delete it and run `silcrow install` again to write Silcrow's, or add the line to keep both",
                dir.join("hooks").join(event).display()
            ));
        }
    }
    let text = String::from_utf8_lossy(&text);
    let tool = [
        ("husky", "husky"),
        ("lefthook", "lefthook"),
        ("pre-commit.com", "pre-commit"),
        ("pre_commit", "pre-commit"),
    ]
    .into_iter()
    .find(|(needle, _)| text.contains(needle))?
    .1;
    Some(format!(
        "{tool} wrote it: add the line where {tool} runs your hooks"
    ))
}

/// The template directory `git init` copies hooks from: `GIT_TEMPLATE_DIR`, else
/// `init.templateDir`, a leading `~/` read from `HOME`.
fn template_dir(root: &Path) -> Option<PathBuf> {
    let dir = match std::env::var("GIT_TEMPLATE_DIR") {
        Ok(dir) if !dir.is_empty() => dir,
        _ => git_line(root, &["config", "--get", "init.templateDir"])
            .ok()
            .filter(|dir| !dir.is_empty())?,
    };
    Some(match dir.strip_prefix("~/") {
        Some(rest) => PathBuf::from(std::env::var_os("HOME")?).join(rest),
        None => PathBuf::from(dir),
    })
}

/// Fails on each hook another tool wrote, naming the line to add to it.
fn refuse_foreign(root: &Path) -> Result<()> {
    // § hqv22s05t.b@phtv9
    let foreign: Vec<String> = drift(root)?
        .into_iter()
        .filter_map(|(path, line)| {
            let line = line?;
            Some(match foreign_origin(root, &path) {
                Some(origin) => format!("  {}: {origin}, `{line}`", path.display()),
                None => format!("  {}: add `{line}` to it", path.display()),
            })
        })
        .collect();
    if !foreign.is_empty() {
        bail!(
            "another tool wrote these git hooks, so `silcrow install` leaves them, writes the others, and does not count them as installed. Silcrow does not read them: add the line to each to run Silcrow there, and let `silcrow check --all` in CI be the gate:\n{}",
            foreign.join("\n")
        );
    }
    Ok(())
}

/// The main checkout of the repository when `root` is a linked worktree, whose git directory is
/// not the common one every worktree shares.
pub fn main_checkout(root: &Path) -> Result<Option<PathBuf>> {
    // § hqv22s05t.e@j0wvm
    if !root.join(".git").is_file() {
        return Ok(None);
    }
    let dirs = git_line(
        root,
        &[
            "rev-parse",
            "--path-format=absolute",
            "--git-dir",
            "--git-common-dir",
        ],
    )?;
    let Some((own, common)) = dirs.split_once('\n') else {
        bail!(
            "git rev-parse names no common git directory for {}",
            root.display()
        );
    };
    if own.trim() == common.trim() {
        return Ok(None);
    }
    let list = git_line(root, &["worktree", "list", "--porcelain"])?;
    let Some(main) = list
        .lines()
        .next()
        .and_then(|line| line.strip_prefix("worktree "))
    else {
        bail!(
            "git worktree list names no main checkout for {}",
            root.display()
        );
    };
    Ok(Some(PathBuf::from(main)))
}

/// Writes each hook that is missing or Silcrow's own, then fails on each hook another tool
/// wrote. A linked worktree leaves the hooks it shares to the main checkout.
pub fn install(root: &Path, dry_run: bool) -> Result<()> {
    // § gyhzk1qye.c@xp76r
    let Some(dir) = hooks_dir(root)? else {
        return Ok(());
    };
    // § hqv22s05t.e@kngep
    if let Some(main) = main_checkout(root)? {
        eprintln!(
            "install writes no git hook here: this is a linked worktree, which runs the hooks of the main checkout {}. Run `silcrow install` there to write them.",
            main.display()
        );
        return Ok(());
    }
    // § end hqv22s05t.e
    for event in EVENTS {
        let path = dir.join(event);
        // § hqv22s05t.a@wq0nf
        let HookState::Write(old) = hook_state(root, &path, event) else {
            continue;
        };
        let body = script(root, event);
        crate::harness::write_file(
            root,
            &path,
            old.as_deref().unwrap_or_default(),
            &body,
            dry_run,
        )?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if !dry_run {
                std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
            }
        }
    }
    refuse_foreign(root)
}

/// The Silcrow repository: a workspace whose root `Cargo.toml` names the package `silcrow`.
pub fn is_silcrow_repo(root: &Path) -> bool {
    // § vz45j4qce.a@y0rmj
    std::fs::read_to_string(root.join("Cargo.toml"))
        .is_ok_and(|t| t.lines().any(|line| line.trim() == "name = \"silcrow\""))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dev_hook_script_uses_cargo_run() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Cargo.toml"), "name = \"silcrow\"\n").unwrap();
        let s = script(dir.path(), "pre-commit");
        assert!(s.contains("cargo run -q -- hook pre-commit"));
    }

    #[test]
    fn a_marker_line_inside_a_string_names_no_staged_id() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(
            dir.path().join("src/a.rs"),
            "fn f() {\n    // § abcdefgh1.a\n    let s = r\"\n// § abcdefgh2.a@aaaaa\n\";\n}\n",
        )
        .unwrap();
        let ids = staged_law_ids(dir.path(), &[PathBuf::from("src/a.rs")]).unwrap();
        assert_eq!(ids, vec!["abcdefgh1"]);
    }

    #[test]
    fn a_pointer_counts_only_for_a_declared_id() {
        let dir = tempfile::tempdir().unwrap();
        assert!(crate::test_git()
            .args(["init", "-q"])
            .current_dir(dir.path())
            .status()
            .unwrap()
            .success());
        std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("docs/decisions/a.md"),
            "**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
        )
        .unwrap();
        let ids = vec!["wxsgf68fh".to_string(), "abcdefgh1".to_string()];
        assert_eq!(declared_only(dir.path(), ids).unwrap(), vec!["wxsgf68fh"]);
    }

    #[test]
    fn remint_trailer_is_not_rewritten_when_already_present() {
        let dir = tempfile::tempdir().unwrap();
        let msg = dir.path().join("COMMIT_EDITMSG");
        std::fs::write(&msg, "upgrade\n\nSilcrow-Op: remint\n").unwrap();
        commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
        let body = std::fs::read_to_string(&msg).unwrap();
        assert_eq!(body.matches("Silcrow-Op: remint").count(), 1);
    }

    #[test]
    fn commit_msg_records_the_scheme_and_no_impact_trailer() {
        let dir = tempfile::tempdir().unwrap();
        let git = |args: &[&str]| {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args(args)
                .current_dir(dir.path())
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        };
        git(&["init", "-q"]);
        std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("docs/decisions/a.md"),
            "**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
        )
        .unwrap();
        git(&["add", "."]);
        let msg = dir.path().join("COMMIT_EDITMSG");
        std::fs::write(&msg, "law\n").unwrap();
        commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
        assert_eq!(
            std::fs::read_to_string(&msg).unwrap(),
            format!("law\n\nSilcrow-Scheme: {}\n", crate::scheme::BINARY_VERSION)
        );
    }

    #[test]
    fn commit_msg_reads_the_index_and_marks_a_remint_only_when_it_travels_alone() {
        let dir = tempfile::tempdir().unwrap();
        let git = |args: &[&str]| {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(args)
                .current_dir(dir.path())
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        };
        let write = |rel: &str, text: &str| {
            let path = dir.path().join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        };
        let trailers = |msg: &str| {
            let path = dir.path().join(".git/COMMIT_EDITMSG");
            std::fs::write(&path, msg).unwrap();
            commit_msg(dir.path(), &[path.to_string_lossy().into_owned()]).unwrap();
            std::fs::read_to_string(&path).unwrap()[msg.len()..].to_string()
        };
        git(&["init", "-q"]);
        write(
            "AGENTS.md",
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        );
        write(
            "docs/decisions/a.md",
            "**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
        );
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "law"]);
        write(
            "src/lib.rs",
            "fn f() {\n    // § wxsgf68fh@aaaaa\n    go();\n}\n",
        );
        git(&["add", "."]);
        write("src/lib.rs", "fn f() {\n    go();\n}\n");
        let current = crate::scheme::BINARY_VERSION;
        assert_eq!(trailers("code\n"), format!("\nSilcrow-Scheme: {current}\n"));
        write(
            "src/lib.rs",
            "fn f() {\n    // § wxsgf68fh@aaaaa\n    go();\n}\n",
        );
        git(&["commit", "-q", "-m", "code\n\nSilcrow-Scheme: 1"]);
        write(
            "src/lib.rs",
            "fn f() {\n    // § wxsgf68fh@bbbbb\n    go();\n}\n",
        );
        git(&["add", "."]);
        assert_eq!(
            trailers("remint\n"),
            format!("\nSilcrow-Op: remint\nSilcrow-Scheme: {current}\n")
        );
        write(
            "src/lib.rs",
            "fn f() {\n    // § wxsgf68fh@bbbbb\n    stop();\n}\n",
        );
        git(&["add", "."]);
        assert_eq!(trailers("edit\n"), format!("\nSilcrow-Scheme: {current}\n"));
    }

    #[test]
    fn a_scheme_that_differs_from_the_record_is_a_remint() {
        assert_eq!(
            scheme_trailers(Some(4), 5, true, "upgrade\n"),
            vec!["Silcrow-Op: remint", "Silcrow-Scheme: 5"]
        );
        assert_eq!(
            scheme_trailers(Some(4), 5, false, "upgrade and edit\n"),
            vec!["Silcrow-Scheme: 5"]
        );
        assert!(scheme_trailers(Some(5), 5, true, "edit\n").is_empty());
        assert_eq!(
            scheme_trailers(None, 5, false, "first\n"),
            vec!["Silcrow-Scheme: 5"]
        );
        assert_eq!(
            scheme_trailers(Some(4), 5, true, "upgrade\n\nSilcrow-Op: remint\n"),
            vec!["Silcrow-Scheme: 5"]
        );
        assert!(scheme_trailers(Some(4), 5, true, "x\n\nSilcrow-Scheme: 4\n").is_empty());
    }

    #[test]
    fn recorded_scheme_is_the_last_trailer_in_history() {
        let dir = tempfile::tempdir().unwrap();
        let git = |args: &[&str]| {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(args)
                .current_dir(dir.path())
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        };
        git(&["init", "-q"]);
        assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
        git(&["commit", "-q", "--allow-empty", "-m", "start"]);
        assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
        git(&[
            "commit",
            "-q",
            "--allow-empty",
            "-m",
            "remint\n\nSilcrow-Op: remint\nSilcrow-Scheme: 4",
        ]);
        git(&["commit", "-q", "--allow-empty", "-m", "edit"]);
        assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(4));
        git(&[
            "commit",
            "-q",
            "--allow-empty",
            "-m",
            "remint\n\nSilcrow-Scheme: 5",
        ]);
        assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(5));
    }

    fn scratch_git(dir: &Path) -> impl Fn(&[&str]) -> String + '_ {
        move |args: &[&str]| {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(args)
                .current_dir(dir)
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        }
    }

    #[test]
    fn commit_msg_writes_nothing_on_a_first_commit_that_names_no_law() {
        let dir = tempfile::tempdir().unwrap();
        let git = scratch_git(dir.path());
        git(&["init", "-q"]);
        std::fs::write(
            dir.path().join("AGENTS.md"),
            "<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
        )
        .unwrap();
        git(&["add", "."]);
        assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
        let msg = dir.path().join("COMMIT_EDITMSG");
        std::fs::write(&msg, "first\n").unwrap();
        commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
        assert_eq!(std::fs::read_to_string(&msg).unwrap(), "first\n");
    }

    #[test]
    fn an_amend_is_compared_against_the_commit_it_replaced_not_a_stale_orig_head() {
        let dir = tempfile::tempdir().unwrap();
        let git = scratch_git(dir.path());
        let write = |rel: &str, text: &str| {
            let path = dir.path().join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        };
        git(&["init", "-q"]);
        write("a.md", "a\n");
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "a"]);
        write("b.md", "b\n");
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "b"]);
        git(&["reset", "-q", "--soft", "HEAD~1"]);
        git(&["commit", "-q", "-m", "b again"]);
        let replaced = git(&["rev-parse", "HEAD"]);
        write("c.md", "c\n");
        git(&["add", "."]);
        git(&["commit", "-q", "--amend", "-m", "b and c"]);
        let stale = git(&["rev-parse", "ORIG_HEAD"]);
        assert_ne!(stale, replaced);
        let new = git(&["rev-parse", "HEAD"]);
        let stdin = format!("{replaced} {new}\n");
        let before = rewritten_commit(dir.path(), Some("amend"), &mut stdin.as_bytes())
            .unwrap()
            .unwrap();
        assert_eq!(before, replaced);
        assert_eq!(
            rewrite_changed_paths(dir.path(), &before).unwrap(),
            BTreeSet::from([PathBuf::from("c.md")])
        );
        assert_eq!(
            rewritten_commit(dir.path(), Some("rebase"), &mut "".as_bytes()).unwrap(),
            Some(stale)
        );
        assert!(rewritten_commit(dir.path(), Some("amend"), &mut "".as_bytes()).is_err());
    }

    #[test]
    fn a_script_silcrow_writes_is_ours_in_every_build_and_path() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let ours = script(root, "pre-commit");
        assert!(is_ours(&ours, "pre-commit"));
        assert!(!is_ours(&ours, "post-merge"));
        assert!(is_ours(
            "#!/bin/sh\nset -e\ncd '/x y' && exec cargo run -q -- hook pre-commit \"$@\"\n",
            "pre-commit"
        ));
        assert!(!is_ours(
            "#!/bin/sh\nset -e\nexec silcrow hook pre-commit \"$@\"\nnpx lint-staged\n",
            "pre-commit"
        ));
    }

    #[test]
    fn select_genealogy_ids_uses_all_when_small() {
        let live = vec![
            ("aaaaaaaab".into(), PathBuf::from("docs/decisions/a.md")),
            ("bbbbbbbbc".into(), PathBuf::from("docs/decisions/b.md")),
        ];
        let changed = BTreeSet::from([PathBuf::from("docs/decisions/a.md")]);
        let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
        assert_eq!(ids.len(), 2);
        assert!(capped.is_none());
    }

    #[test]
    fn select_genealogy_ids_samples_changed_when_large() {
        let mut live = Vec::new();
        for i in 0..60 {
            live.push((
                format!("id{i:07}"),
                PathBuf::from(format!("docs/decisions/f{i}.md")),
            ));
        }
        let changed = BTreeSet::from([
            PathBuf::from("docs/decisions/f0.md"),
            PathBuf::from("docs/decisions/f59.md"),
        ]);
        let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&"id0000000".to_string()));
        assert!(ids.contains(&"id0000059".to_string()));
        let warning = capped.expect("a capped run warns");
        assert!(warning.contains("GENEALOGY_CAP (50)"), "{warning}");
        assert!(warning.contains("skipped 58"), "{warning}");
    }
}