silcrow 0.1.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
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@h0rn5
    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),
        other => bail!("unknown hook event `{other}`"),
    }
}

fn pre_commit(ws: &Workspace) -> Result<()> {
    // § gyhzk1qye.c@mrqk8
    let staged = staged_paths(&ws.root)?;
    let index = IndexTree::export(&ws.root)?;
    let outcome = fix_and_check_index(ws, &index, &staged);
    index.remove()?;
    if !outcome? {
        std::process::exit(1);
    }
    Ok(())
}

/// Fixes the index copy, carries each rewrite into the index and the worktree, then checks
/// the copy: the tree the commit records. Whether the check passed.
fn fix_and_check_index(ws: &Workspace, index: &IndexTree, staged: &[PathBuf]) -> Result<bool> {
    // § gyhzk1qye.d@ad5ft
    let copy = index_workspace(ws, index)?;
    let unstaged = unstaged_projects(ws, &copy);
    if !unstaged.is_empty() {
        println!(
            "  ERR {} 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(false);
    }
    let mut rewritten = Vec::new();
    // § ave4h4m3g.c@rx2et
    for project in copy.local() {
        // § j3m715h92.f@pkcar
        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();
        if let Some(paths) = resolve::resolve_staged(&copy, project, &mine, false)? {
            rewritten.extend(paths.into_iter().map(|path| rel.join(path)));
        }
    }
    // § end ave4h4m3g.c
    rewritten.sort();
    rewritten.dedup();
    // § gx7m90jhm.b@m4ran
    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() {
        println!(
            "  ERR {} 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(false);
    }
    // § end gx7m90jhm.b
    let mut report = check::validate(&copy, &copy.local(), true)?;
    report.harness = staged_harness(ws, &copy)?;
    report.errors.extend(stray_markers(&copy)?);
    if !check::print_report(&report, false) {
        // § gx7m90jhm.a@3czg9
        // A refused commit 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.
        return Ok(false);
    }
    for rel in &rewritten {
        std::fs::copy(index.dir.join(rel), ws.root.join(rel))?;
    }
    restage(&ws.root, &rewritten)?;
    Ok(true)
}

/// 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@v3zhs
    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> {
    // § gx7m90jhm.c@f2zdh
    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@dj4h0
    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@2hxe1
    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");
        if dir.exists() {
            std::fs::remove_dir_all(&dir)?;
        }
        std::fs::create_dir_all(&dir)?;
        let prefix = format!("{}/", dir.display());
        let status = crate::workspace::git(root)
            .args(["checkout-index", "--all", "--force"])
            .arg(format!("--prefix={prefix}"))
            .status()?;
        if !status.success() {
            bail!(
                "git checkout-index could not write the index to {}",
                dir.display()
            );
        }
        std::fs::write(dir.join(".git"), format!("gitdir: {git_dir}\n"))?;
        Ok(Self { dir })
    }

    fn remove(&self) -> Result<()> {
        Ok(std::fs::remove_dir_all(&self.dir)?)
    }
}

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@wkcjq
    let merge_report = crate::merge::parent_conflicts(ws)?;
    report.errors.extend(merge_report.errors);
    report.warnings.extend(merge_report.warnings);
    // § end dveb6b5vj
    // § gyhzk1qye.e@fdxvf
    if !check::print_report(&report, false) {
        std::process::exit(1);
    }
    // § end gyhzk1qye.e
    Ok(())
}

fn post_rewrite(ws: &Workspace, args: &[String]) -> Result<()> {
    // § rwvvdms6f@ykh1h
    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@tsfyz
    if !check::print_report(&report, false) {
        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@qwwyh
    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@fj5sd
    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@wygwp
    let staged = staged_paths(root)?;
    if staged.is_empty() {
        return Ok(());
    }
    // § gyhzk1qye.d@6r1pn
    // 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@a71zq
    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@wtfse
    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@yh11t
    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@3eawt
    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@pj99k
    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; 4] = ["pre-commit", "post-merge", "post-rewrite", "commit-msg"];

/// 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@cz0gd
    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@xycz7
    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@rw468
    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(())
}

/// Writes each hook that is missing or Silcrow's own, then fails on each hook another tool
/// wrote.
pub fn install(root: &Path, dry_run: bool) -> Result<()> {
    // § gyhzk1qye.c@2rnr0
    let Some(dir) = hooks_dir(root)? else {
        return Ok(());
    };
    for event in EVENTS {
        let path = dir.join(event);
        // § hqv22s05t.a@cx1w7
        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@g53j6
    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}");
    }
}