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
use anyhow::{bail, Result};
use regex::Regex;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::LazyLock;

use crate::parse;

static ID_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"\b({})\b", crate::marker::ID)).expect("id regex"));

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StepKind {
    Declare,
    Accept,
    Remint,
    Retire,
}

struct Step {
    commit: String,
    id: String,
    old: Option<String>,
    new: Option<String>,
    kind: StepKind,
    author: String,
    date: String,
    time: i64,
}

pub fn run(root: &Path, id: &str, verbose: bool) -> Result<()> {
    // § s4rc762ft.a@xnnbm
    if id.len() != 9 {
        bail!("log expects a 9-character law id");
    }
    // § n71fgy5xw.a@95dnq
    let id = &crate::hash::normalise_id(id);
    // § end n71fgy5xw.a
    ensure_git(root)?;
    let scan = parse::scan_root(root)?;
    // § s4rc762ft.b@0bvx2
    // An alias anchor names the law that keeps it, so its log is that law's.
    let current_law = scan
        .laws
        .iter()
        .find(|law| law.id == *id || law.aliases.iter().any(|alias| alias == id));
    let id = current_law.map_or(id.as_str(), |law| law.id.as_str());
    // § end s4rc762ft.b
    let git = History::new(root);
    let family = expand_family(&git, id)?;
    let steps = collect_steps(&git, &family, verbose)?;
    if current_law.is_none() && steps.is_empty() {
        bail!("no law `{id}` in the tree or in its git history: check the id with `silcrow list`");
    }
    let current = current_law
        .map(|law| law.name.as_str())
        .unwrap_or("(unknown law)");
    println!("[{id}] {current}");
    if let Some(law) = current_law {
        // § pxmeee9ra.e@0x441
        let drafts: Vec<String> =
            std::iter::once((law.draft, law.id.clone()))
                .chain(law.clauses.iter().filter(|c| !c.struck).filter_map(|c| {
                    Some((c.draft, format!("{}.{}", law.id, c.letter.as_deref()?)))
                }))
                .filter_map(|(draft, address)| draft.then_some(address))
                .collect();
        if !drafts.is_empty() {
            println!(
                "  draft  {}  (not implemented, not pinned)",
                drafts.join(", ")
            );
        }
        // § end pxmeee9ra.e
        if law.public {
            println!("  public  a promise of the public docs, owes a documentation marker");
        }
    }
    // Each reads a different walk of the history, so they wait on git side by side.
    let (meta, rewrites) = std::thread::scope(|s| {
        let meta = s.spawn(|| crate::meta::for_id(root, &scan, id, false));
        let rewrites = rewrites_in(&git, id);
        let meta = meta
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
        (meta, rewrites)
    });
    if let Some(date) = &meta.declared_on {
        match &meta.age {
            Some(age) => println!("  declared  {date}  ({age})"),
            None => println!("  declared  {date}"),
        }
    }
    let rewrites = rewrites?;
    println!(
        "  markers  code {}  doc {}  remint {}  accept {}  re-pin {}",
        meta.markers.code,
        meta.markers.doc,
        rewrites.remints,
        rewrites.accepts,
        rewrites.repins.len()
    );
    if verbose {
        for repin in &rewrites.repins {
            print!("{}", render_repin(repin));
        }
    }

    if steps.is_empty() {
        println!("  (no commits touching § {id})");
        return Ok(());
    }

    for step in steps {
        print!("{}", render_step(&step));
    }
    Ok(())
}

fn render_step(step: &Step) -> String {
    // § s4rc762ft@9sysz
    let kind = match step.kind {
        StepKind::Declare => "declare",
        StepKind::Accept => "accept",
        StepKind::Remint => "remint",
        StepKind::Retire => "retire",
    };
    let mut out = format!("[{}] {kind}, {}, {}\n", step.id, step.author, step.date);
    if let Some(old) = &step.old {
        out.push_str(&format!("  - {old}\n"));
    }
    if let Some(new) = &step.new {
        out.push_str(&format!("  + {new}\n"));
    }
    out
}

pub struct Rewrites {
    pub remints: usize,
    pub accepts: usize,
    pub repins: Vec<Repin>,
}

fn render_repin(repin: &Repin) -> String {
    // § s4rc762ft.b@tcq4b
    format!(
        "  re-pin  {}  {}, {}  {}\n",
        repin.sha,
        repin.author,
        repin.date,
        repin.addresses.join(", ")
    )
}

pub fn rewrite_counts(root: &Path, id: &str) -> Result<Rewrites> {
    rewrites_in(&History::new(root), id)
}

fn rewrites_in(git: &History<'_>, id: &str) -> Result<Rewrites> {
    // § s4rc762ft.a@c1d25
    let family = expand_family(git, id)?;
    let (steps, digests) = std::thread::scope(|s| {
        let digests = crate::par::spawn(s, || digest_changes(git.root, &family));
        let steps = collect_steps(git, &family, true);
        let digests = digests
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
        (steps, digests)
    });
    let steps = steps?;
    let (repins, digest_remints) = digests?;
    let remints: BTreeSet<&str> = steps
        .iter()
        .filter(|step| step.kind == StepKind::Remint)
        .map(|step| step.commit.as_str())
        .chain(digest_remints.iter().map(String::as_str))
        .collect();
    let accepts = steps
        .iter()
        .filter(|step| step.kind == StepKind::Accept)
        .count();
    Ok(Rewrites {
        remints: remints.len(),
        accepts,
        repins,
    })
}

/// A commit that changed the digest of a marker of the law while the scheme stayed.
#[derive(Clone)]
pub struct Repin {
    pub sha: String,
    pub author: String,
    pub date: String,
    pub addresses: Vec<String>,
}

/// The commits that changed a marker digest of any id of the law's lineage `family`, at any
/// grain: the re-pins, oldest first, and the full hashes of those where the scheme changed,
/// which are remints.
fn digest_changes(root: &Path, family: &BTreeSet<String>) -> Result<(Vec<Repin>, Vec<String>)> {
    // § s4rc762ft.b@m6r1f
    let mut repins: BTreeMap<String, (i64, Repin)> = BTreeMap::new();
    let mut remints = BTreeSet::new();
    for id in family {
        let (found, reminted) = id_digest_changes(root, id)?;
        remints.extend(reminted);
        for (time, full, repin) in found {
            let entry = repins.entry(full).or_insert((
                time,
                Repin {
                    addresses: Vec::new(),
                    ..repin.clone()
                },
            ));
            entry.1.addresses.extend(repin.addresses);
            entry.1.addresses.sort();
            entry.1.addresses.dedup();
        }
    }
    let mut repins: Vec<(i64, Repin)> = repins.into_values().collect();
    repins.sort_by_key(|(time, _)| *time);
    Ok((
        repins.into_iter().map(|(_, repin)| repin).collect(),
        remints.into_iter().collect(),
    ))
}

/// A re-pin with its commit time and full hash.
type TimedRepin = (i64, String, Repin);

/// The re-pins of the markers of one id, each with its commit time and full hash, and the
/// full hashes of the remints.
fn id_digest_changes(root: &Path, id: &str) -> Result<(Vec<TimedRepin>, Vec<String>)> {
    let out = crate::workspace::git(root)
        .args([
            "-c",
            "core.quotePath=false",
            "log",
            "-G",
            id,
            "--format=%x01%H%x00%h%x00%an%x00%ad%x00%at%x00%(trailers:key=Silcrow-Op,valueonly,separator=%x20)%x00%(trailers:key=Silcrow-Scheme,valueonly,separator=%x20)",
            "--date=format:%-d %b %Y",
            "-p",
            "-U0",
            "--no-color",
            "--no-ext-diff",
            "--no-renames",
            "--src-prefix=a/",
            "--dst-prefix=b/",
        ])
        .output()?;
    if !out.status.success() {
        bail!(
            "git log -G {id} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let mut repins = Vec::new();
    let mut remints = Vec::new();
    for record in stdout.split('\u{1}').filter(|r| !r.is_empty()) {
        let (head, patch) = record.split_once('\n').unwrap_or((record, ""));
        let fields: Vec<&str> = head.split('\0').collect();
        let [full, sha, author, date, time, op, scheme] = fields[..] else {
            bail!("git log -G {id}: unexpected header `{head}`");
        };
        let addresses = repinned_addresses(patch, id, &|new, path| {
            let rev = if new {
                full.to_string()
            } else {
                format!("{full}^")
            };
            show(root, &rev, path)
        })?;
        if addresses.is_empty() {
            continue;
        }
        if scheme_changed(root, full, op, scheme)? {
            remints.push(full.to_string());
            continue;
        }
        repins.push((
            time.parse()?,
            full.to_string(),
            Repin {
                sha: sha.to_string(),
                author: author.to_string(),
                date: date.to_string(),
                addresses,
            },
        ));
    }
    Ok((repins, remints))
}

/// The addresses of `id` whose markers gained a digest the commit did not remove. A marker
/// pinned for the first time removed no digest, so it is not a re-pin. `file` reads a path of
/// the patch on its new side or its old one, so a changed line counts only where that file
/// holds a marker on it.
fn repinned_addresses(
    patch: &str,
    id: &str,
    file: &dyn Fn(bool, &str) -> Result<String>,
) -> Result<Vec<String>> {
    let mut removed: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut added: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut rows: HashMap<(bool, String), BTreeSet<usize>> = HashMap::new();
    let mut paths: [Option<String>; 2] = [None, None];
    let mut at = [0usize; 2];
    // A removed `-- §` line reads `--- §`, so a header line is read only before the first hunk.
    let mut header = false;
    for line in patch.lines() {
        if line.starts_with("diff --git ") {
            header = true;
            paths = [None, None];
            continue;
        }
        if header {
            if let Some(path) = line.strip_prefix("--- ") {
                paths[0] = patch_path(path, "a/")?;
            } else if let Some(path) = line.strip_prefix("+++ ") {
                paths[1] = patch_path(path, "b/")?;
            } else if let Some(range) = line.strip_prefix("@@ ") {
                header = false;
                at = hunk_starts(range)?;
            }
            continue;
        }
        if let Some(range) = line.strip_prefix("@@ ") {
            at = hunk_starts(range)?;
            continue;
        }
        let new = match line.as_bytes().first() {
            Some(b'-') => false,
            Some(b'+') => true,
            _ => continue,
        };
        let side = usize::from(new);
        let lineno = at[side];
        at[side] += 1;
        let markers: Vec<_> = crate::marker::markers_in_line(&line[1..])
            .into_iter()
            .filter(|m| m.id == id && m.digest.is_some())
            .collect();
        if markers.is_empty() {
            continue;
        }
        let Some(path) = &paths[side] else {
            bail!("git log -G {id}: a changed line outside any file: {line}");
        };
        let key = (new, path.clone());
        if !rows.contains_key(&key) {
            let text = file(new, path)?;
            let lines = crate::span::marker_rows(Path::new(path), &text, None)
                .into_iter()
                .map(|row| row.idx + 1)
                .collect();
            rows.insert(key.clone(), lines);
        }
        if !rows[&key].contains(&lineno) {
            continue;
        }
        let side = if new { &mut added } else { &mut removed };
        for marker in markers {
            let digest = marker.digest.clone().unwrap_or_default();
            side.entry(marker.display()).or_default().insert(digest);
        }
    }
    Ok(added
        .into_iter()
        .filter(|(addr, new)| {
            removed
                .get(addr)
                .is_some_and(|old| new.iter().any(|digest| !old.contains(digest)))
        })
        .map(|(addr, _)| addr)
        .collect())
}

/// The path a `---` or `+++` line of a patch names under `prefix`, `None` for `/dev/null`.
pub fn patch_path(field: &str, prefix: &str) -> Result<Option<String>> {
    if field == "/dev/null" {
        return Ok(None);
    }
    // Git closes a name that holds a space with a tab.
    match field
        .strip_suffix('\t')
        .unwrap_or(field)
        .strip_prefix(prefix)
    {
        Some(path) => Ok(Some(path.to_string())),
        None => bail!("git log: a patch names `{field}`, not a path under `{prefix}`"),
    }
}

/// The first 1-based line of each side of a hunk, read from `-a[,b] +c[,d] @@`.
pub fn hunk_starts(range: &str) -> Result<[usize; 2]> {
    let mut parts = range.split_whitespace();
    let mut start = |sign: char| -> Result<usize> {
        let part = parts.next().and_then(|p| p.strip_prefix(sign));
        let first = part.and_then(|p| p.split(',').next());
        match first.map(str::parse::<usize>) {
            Some(Ok(n)) => Ok(n),
            _ => bail!("git log: unreadable hunk header `@@ {range}`"),
        }
    };
    Ok([start('-')?, start('+')?])
}

/// The text of `path` at `rev`, the path read from the top of the repository.
fn show(root: &Path, rev: &str, path: &str) -> Result<String> {
    let out = crate::workspace::git(root)
        .args(["cat-file", "blob", &format!("{rev}:{path}")])
        .output()?;
    if !out.status.success() {
        bail!(
            "git cat-file {rev}:{path} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// A commit changes the scheme when it carries the remint mark, or records a scheme that
/// differs from the one its parent recorded, and changes nothing but minted tokens.
pub fn scheme_changed(root: &Path, commit: &str, op: &str, scheme: &str) -> Result<bool> {
    if is_scheme_remint(root, commit, op)? {
        return Ok(true);
    }
    let Some(recorded) = scheme.split_whitespace().next_back() else {
        return Ok(false);
    };
    let recorded: u32 = recorded.parse().map_err(|_| {
        anyhow::anyhow!("Silcrow-Scheme trailer `{recorded}` is not a scheme number")
    })?;
    let parent = crate::hook::recorded_scheme_at(root, &format!("{commit}^"))?;
    Ok(parent.is_some_and(|before| before != recorded) && moves_only_tokens(root, commit)?)
}

/// Whether `commit` changes nothing against its first parent but digests, ids and alias
/// anchors, as a scheme remint does. A trailer can be written by hand, the patch cannot lie.
fn moves_only_tokens(root: &Path, commit: &str) -> Result<bool> {
    // § s4rc762ft.b@v6qp2
    let parent = format!("{commit}^1");
    let born = crate::workspace::git(root)
        .args(["rev-parse", "--verify", "--quiet", &parent])
        .output()?;
    if !born.status.success() {
        return Ok(false);
    }
    let out = crate::workspace::git(root)
        .args([
            "diff",
            "--no-color",
            "--no-ext-diff",
            "--no-renames",
            "-U0",
            &parent,
            commit,
        ])
        .output()?;
    if !out.status.success() {
        bail!(
            "git diff {parent} {commit} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(crate::hook::only_minted_tokens(&String::from_utf8_lossy(
        &out.stdout,
    )))
}

/// Lightweight pickaxe probe: true when `git log -S` finds any commit (including scheme remints).
pub fn can_trace(root: &Path, id: &str) -> Result<bool> {
    let out = crate::workspace::git(root)
        .args(["log", "-S", id, "--format=%H", "-1", "--", "."])
        .output()?;
    if !out.status.success() {
        bail!("git log -S failed");
    }
    Ok(!String::from_utf8_lossy(&out.stdout).trim().is_empty())
}

/// Verify pickaxe history for laws that existed before a rewrite. Returns (errors, warnings).
pub fn genealogy_check(
    root: &Path,
    ids: &[String],
    existed_before: &BTreeSet<String>,
) -> (Vec<String>, Vec<String>) {
    // § s4rc762ft.d@jmmxx
    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    for id in ids {
        if !existed_before.contains(id) {
            continue;
        }
        match can_trace(root, id) {
            Ok(true) => {}
            Ok(false) => errors.push(format!(
                "genealogy: § {id} has no pickaxe history; post-rewrite may have broken `silcrow log`"
            )),
            Err(e) => warnings.push(format!("genealogy: § {id}: {e}")),
        }
    }
    (errors, warnings)
}

fn expand_family(git: &History<'_>, start: &str) -> Result<BTreeSet<String>> {
    // § s4rc762ft.a@j02ay
    let mut family = BTreeSet::from([start.to_string()]);
    let mut changed = true;
    while changed {
        changed = false;
        for id in family.clone() {
            for (old, new) in accept_pairs(git, &id)? {
                if family.insert(old) {
                    changed = true;
                }
                if family.insert(new) {
                    changed = true;
                }
            }
        }
    }
    Ok(family)
}

fn accept_pairs(git: &History<'_>, id: &str) -> Result<Vec<(String, String)>> {
    let mut pairs = Vec::new();
    // § s4rc762ft.a@fc300
    for hit in pickaxe_commits(git, id, true)? {
        let commit = hit.hash;
        let diff = git_show_decisions(git, &commit)?;
        for (old, new) in pairs_in_diff(&diff) {
            if old == *id || new == *id {
                pairs.push((old, new));
            }
        }
    }
    pairs.sort();
    pairs.dedup();
    Ok(pairs)
}

fn collect_steps(git: &History<'_>, family: &BTreeSet<String>, verbose: bool) -> Result<Vec<Step>> {
    let mut by_commit: BTreeMap<String, PickaxeHit> = BTreeMap::new();
    for id in family {
        for hit in pickaxe_commits(git, id, verbose)? {
            by_commit.entry(hit.hash.clone()).or_insert(hit);
        }
    }

    let mut steps = Vec::new();
    for (hash, hit) in by_commit {
        let diff = git_show_decisions(git, &hash)?;
        // § s4rc762ft.c@gnk5m
        let step = if hit.remint {
            remint_step_from_diff(&diff, family, &hit.author, &hit.date)
        } else {
            step_from_diff(&diff, family, &hit.author, &hit.date)
        };
        if let Some(step) = step {
            steps.push(Step {
                commit: hash,
                time: hit.time,
                ..step
            });
        }
    }
    steps.sort_by(|a, b| b.time.cmp(&a.time).then_with(|| b.id.cmp(&a.id)));
    steps.dedup_by(|a, b| a.id == b.id && a.date == b.date && a.kind == b.kind);
    Ok(steps)
}

fn remint_step_from_diff(
    diff: &str,
    family: &BTreeSet<String>,
    author: &str,
    date: &str,
) -> Option<Step> {
    for (old, new) in pairs_in_diff(diff) {
        if family.contains(&new) && family.contains(&old) {
            return Some(Step {
                commit: String::new(),
                old: carrying_in(diff, '-', &old),
                new: carrying_in(diff, '+', &new),
                id: new,
                kind: StepKind::Remint,
                author: author.to_string(),
                date: date.to_string(),
                time: 0,
            });
        }
    }
    None
}

fn step_from_diff(diff: &str, family: &BTreeSet<String>, author: &str, date: &str) -> Option<Step> {
    // § s4rc762ft@gqm9g
    for id in family {
        if struck_in(diff, '+', id) && !struck_in(diff, '-', id) {
            return Some(Step {
                commit: String::new(),
                id: id.clone(),
                old: carrying_in(diff, '-', id),
                new: None,
                kind: StepKind::Retire,
                author: author.to_string(),
                date: date.to_string(),
                time: 0,
            });
        }
    }
    if diff.contains("**Retire §") {
        for id in family {
            if diff.contains(&format!("**Retire § {id}")) {
                return Some(Step {
                    commit: String::new(),
                    id: id.clone(),
                    old: carrying_in(diff, '-', id),
                    new: None,
                    kind: StepKind::Retire,
                    author: author.to_string(),
                    date: date.to_string(),
                    time: 0,
                });
            }
        }
    }

    for (old, new) in pairs_in_diff(diff) {
        if family.contains(&new) && family.contains(&old) {
            return Some(Step {
                commit: String::new(),
                old: carrying_in(diff, '-', &old),
                new: carrying_in(diff, '+', &new),
                id: new,
                kind: StepKind::Accept,
                author: author.to_string(),
                date: date.to_string(),
                time: 0,
            });
        }
    }

    for id in family {
        let added = carrying_in(diff, '+', id);
        let declared = diff.contains(&format!("+§ {id}"))
            || (added.is_some() && carrying_in(diff, '-', id).is_none());
        if declared {
            return Some(Step {
                commit: String::new(),
                id: id.clone(),
                old: None,
                new: added,
                kind: StepKind::Declare,
                author: author.to_string(),
                date: date.to_string(),
                time: 0,
            });
        }
    }
    None
}

/// Whether the first `sign` line of a diff that carries the head of `id` strikes its sentence.
fn struck_in(diff: &str, sign: char, id: &str) -> bool {
    let anchored = format!("§ <a id=\"{id}\">{id}</a>");
    diff.lines()
        .filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
        .find_map(|line| line.find(&anchored).map(|at| &line[at + anchored.len()..]))
        .is_some_and(|after| crate::hash::strip_aliases(after).trim().starts_with("~~"))
}

/// The carrying sentence of `id` on the first `sign` line of a diff that carries it.
fn carrying_in(diff: &str, sign: char, id: &str) -> Option<String> {
    diff.lines()
        .filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
        .filter(|line| line.contains(id))
        .find_map(|line| declare_sentence(line[1..].trim(), id))
}

fn declare_sentence(line: &str, id: &str) -> Option<String> {
    let anchored = format!("§ <a id=\"{id}\">{id}</a>");
    let bare = format!("§ {id}");
    let (idx, len) = line
        .find(&anchored)
        .map(|i| (i, anchored.len()))
        .or_else(|| line.find(&bare).map(|i| (i, bare.len())))?;
    let before = line[..idx].trim();
    let after = crate::hash::strip_aliases(&line[idx + len..]);
    let after = after.trim();
    let mut text = before.to_string();
    if !after.is_empty() {
        if !text.is_empty() {
            text.push(' ');
        }
        text.push_str(after);
    }
    let text = text
        .trim_matches(|c: char| c == '~' || c == '*' || c == '_' || c == '`')
        .trim();
    if text.is_empty() {
        return None;
    }
    Some(text.to_string())
}

/// The pairs of an old law head removed and a new one added in the same hunk of `diff`, where
/// no added line keeps the old id but as an alias anchor and no removed line held the new one.
/// Only a head that carries its sentence unstruck counts, so a cite, a prose mention, or a
/// strike beside its successor is never a rename.
pub fn pairs_in_diff(diff: &str) -> Vec<(String, String)> {
    let ids_on = |sign: char| -> BTreeSet<String> {
        diff.lines()
            .filter(|line| line.starts_with(sign) && !line.starts_with(&sign.to_string().repeat(3)))
            .flat_map(|line| ids_in_line(&crate::hash::strip_aliases(&line[1..])))
            .collect()
    };
    let (removed, added) = (ids_on('-'), ids_on('+'));
    let mut pairs = Vec::new();
    let mut hunk_minus: Vec<(String, String)> = Vec::new();
    let mut hunk_plus: Vec<(String, String)> = Vec::new();
    let mut flush = |minus: &mut Vec<(String, String)>, plus: &mut Vec<(String, String)>| {
        pairs.extend(pairs_in_hunk(minus, plus));
        minus.clear();
        plus.clear();
    };
    for line in diff.lines() {
        if line.starts_with("@@") {
            flush(&mut hunk_minus, &mut hunk_plus);
            continue;
        }
        if line.starts_with("---") || line.starts_with("+++") {
            continue;
        }
        let sign = match line.chars().next() {
            Some(sign @ ('-' | '+')) => sign,
            _ => continue,
        };
        let Some((id, sentence)) = head_in(line[1..].trim()) else {
            continue;
        };
        if sign == '-' {
            hunk_minus.push((id, sentence));
        } else {
            hunk_plus.push((id, sentence));
        }
    }
    flush(&mut hunk_minus, &mut hunk_plus);
    pairs.retain(|(old, new)| !added.contains(old) && !removed.contains(new));
    pairs
}

/// The id and the carrying sentence of a law head, `**§ <id> sentence**` with or without its
/// anchor wrap, unless the sentence is struck.
fn head_in(line: &str) -> Option<(String, String)> {
    let rest = line.trim_start_matches('*').strip_prefix("§ ")?;
    let id = ids_in_line(rest).into_iter().next()?;
    let opens = rest.starts_with(&format!("<a id=\"{id}\">{id}</a>")) || rest.starts_with(&id);
    if !opens || struck_after(rest, &id) {
        return None;
    }
    Some((id.clone(), declare_sentence(line, &id)?))
}

fn struck_after(rest: &str, id: &str) -> bool {
    let anchored = format!("<a id=\"{id}\">{id}</a>");
    let after = rest
        .strip_prefix(&anchored)
        .or_else(|| rest.strip_prefix(id));
    after.is_some_and(|after| crate::hash::strip_aliases(after).trim().starts_with("~~"))
}

fn pairs_in_hunk(minus: &[(String, String)], plus: &[(String, String)]) -> Vec<(String, String)> {
    if minus.len() == 1 && plus.len() == 1 && minus[0].0 != plus[0].0 {
        return vec![(minus[0].0.clone(), plus[0].0.clone())];
    }
    let mut pairs = Vec::new();
    for (old, old_sent) in minus {
        for (new, new_sent) in plus {
            if old != new && old_sent == new_sent && !old_sent.is_empty() {
                pairs.push((old.clone(), new.clone()));
            }
        }
    }
    pairs
}

fn ids_in_line(line: &str) -> Vec<String> {
    ID_RE
        .captures_iter(line)
        .map(|c| c[1].to_string())
        .collect()
}

struct PickaxeHit {
    hash: String,
    author: String,
    date: String,
    time: i64,
    remint: bool,
}

/// The commits that change the count of `id` in the project, and those that edit a line of
/// its decision notes holding it, which a strike does without changing the count.
fn pickaxe_commits(git: &History<'_>, id: &str, verbose: bool) -> Result<Vec<PickaxeHit>> {
    // § s4rc762ft@fgxe5
    let decisions = decisions_paths(git.root)?.join("\n");
    let mut entries = Vec::new();
    for (pickaxe, paths) in [("-S", "."), ("-G", decisions.as_str())] {
        let out = git.read((pickaxe, id, paths), |root| {
            let out = crate::workspace::git(root)
                .args([
                    "log",
                    pickaxe,
                    id,
                    "--format=%H\t%an\t%ad\t%at\t%s\t%(trailers:key=Silcrow-Op,valueonly)",
                    "--date=format:%-d %b %Y",
                    "--",
                ])
                .args(paths.lines())
                .output()?;
            if !out.status.success() {
                bail!(
                    "git log {pickaxe} {id} failed: {}",
                    String::from_utf8_lossy(&out.stderr).trim()
                );
            }
            Ok(String::from_utf8_lossy(&out.stdout).into_owned())
        })?;
        for line in out.lines() {
            if line.is_empty() {
                continue;
            }
            let parts: Vec<_> = line.split('\t').collect();
            if parts.len() < 5 {
                continue;
            }
            let op = parts.get(5).copied().unwrap_or("");
            // § d1bc2zca5.f@qy3s4
            // § s4rc762ft.c@bfqx9
            let remint = is_scheme_remint(git.root, parts[0], op)?;
            if !verbose && remint {
                continue;
            }
            // § end s4rc762ft.c
            entries.push(PickaxeHit {
                hash: parts[0].to_string(),
                author: parts[1].to_string(),
                date: parts[2].to_string(),
                time: parts[3].parse()?,
                remint,
            });
        }
    }
    entries.sort_by_key(|hit| hit.time);
    entries.dedup_by(|a, b| a.hash == b.hash);
    Ok(entries)
}

/// The directories under which the decision notes of the project at `root` lie, relative to
/// it, as pathspecs.
fn decisions_paths(root: &Path) -> Result<Vec<String>> {
    let project = crate::walk::Project::at(root)?;
    Ok(project
        .notes
        .roots()
        .iter()
        .map(|dir| match dir.to_string_lossy().replace('\\', "/") {
            dir if dir.is_empty() => ".".to_string(),
            dir => dir,
        })
        .collect())
}

/// The patch `commit` makes to the decision notes of the project, a file the `notes` list
/// does not match left out.
fn git_show_decisions(git: &History<'_>, commit: &str) -> Result<String> {
    git.read(("show", commit, ""), |root| {
        let project = crate::walk::Project::at(root)?;
        let out = crate::workspace::git(root)
            .args(["show", "--relative", commit, "-U0", "--"])
            .args(decisions_paths(root)?)
            .output()?;
        if !out.status.success() {
            return Ok(String::new());
        }
        // A marked head reads as its law: adding or dropping a `?` or a `!` is no step of the lineage.
        let patch = notes_patch(&project, &String::from_utf8_lossy(&out.stdout));
        Ok(parse::plain_heads(&patch))
    })
}

/// The file sections of `patch` whose old or new path is a decision note of `project`.
fn notes_patch(project: &crate::walk::Project, patch: &str) -> String {
    let mut out = String::new();
    // The commit header before the first file section is kept.
    let mut keep = true;
    for line in patch.split_inclusive('\n') {
        if let Some(paths) = line.strip_prefix("diff --git ") {
            keep = paths
                .split_whitespace()
                .filter_map(|p| p.strip_prefix("a/").or_else(|| p.strip_prefix("b/")))
                .any(|rel| project.is_note(Path::new(rel)));
        }
        if keep {
            out.push_str(line);
        }
    }
    out
}

/// The git reads of one walk of a law's history, each made once: widening the family and
/// collecting its steps ask again for the same pickaxe and the same commit.
struct History<'a> {
    root: &'a Path,
    read: RefCell<HashMap<(String, String, String), String>>,
}

impl<'a> History<'a> {
    fn new(root: &'a Path) -> Self {
        Self {
            root,
            read: RefCell::default(),
        }
    }

    fn read(
        &self,
        (verb, arg, path): (&str, &str, &str),
        run: impl FnOnce(&Path) -> Result<String>,
    ) -> Result<String> {
        let key = (verb.to_string(), arg.to_string(), path.to_string());
        if let Some(out) = self.read.borrow().get(&key) {
            return Ok(out.clone());
        }
        let out = run(self.root)?;
        self.read.borrow_mut().insert(key, out.clone());
        Ok(out)
    }
}

/// Whether `commit` is a scheme remint: it carries the mark and changes nothing else.
fn is_scheme_remint(root: &Path, commit: &str, op: &str) -> Result<bool> {
    // § d1bc2zca5.f@q1e4n
    Ok(op.trim().eq_ignore_ascii_case("remint") && moves_only_tokens(root, commit)?)
}

fn ensure_git(root: &Path) -> Result<()> {
    let out = crate::workspace::git(root)
        .args(["rev-parse", "--is-inside-work-tree"])
        .output()?;
    if !out.status.success() {
        bail!("silcrow log needs a git repository");
    }
    crate::published::require_history(root)
}

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

    #[test]
    fn pairs_in_diff_finds_accept() {
        let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
-§ k7m2x9p4a The old sentence.
+§ s4w9k2nab The new sentence.
";
        let pairs = pairs_in_diff(diff);
        assert!(pairs.contains(&("k7m2x9p4a".into(), "s4w9k2nab".into())));
    }

    #[test]
    fn pairs_in_diff_pairs_remint_by_sentence() {
        let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
@@ -1,2 +1,2 @@
-§ aaaaaaaa1 Same carrying sentence.
-§ bbbbbbbb2 Other carrying sentence.
+§ cccccccc3 Same carrying sentence.
+§ dddddddd4 Other carrying sentence.
";
        let pairs = pairs_in_diff(diff);
        assert!(pairs.contains(&("aaaaaaaa1".into(), "cccccccc3".into())));
        assert!(pairs.contains(&("bbbbbbbb2".into(), "dddddddd4".into())));
        assert!(!pairs.contains(&("aaaaaaaa1".into(), "dddddddd4".into())));
    }

    #[test]
    fn only_a_head_that_leaves_for_another_is_a_rename() {
        let cite = "\
@@ -3 +3 @@
-See [aaaaaaaa1](x.md#aaaaaaaa1).
+See [cccccccc3](x.md#cccccccc3).
";
        assert!(pairs_in_diff(cite).is_empty());
        let successor = "\
@@ -1 +1,3 @@
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fails open.**
+**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> ~~The graph fails open.~~**
+**§ <a id=\"cccccccc3\">cccccccc3</a> The graph fails closed.**
";
        assert!(pairs_in_diff(successor).is_empty());
        let accept = "\
@@ -1 +1 @@
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fail open.**
+**§ <a id=\"cccccccc3\">cccccccc3</a><a id=\"aaaaaaaa1\"></a> The graph fails open.**
";
        assert_eq!(
            pairs_in_diff(accept),
            vec![("aaaaaaaa1".to_string(), "cccccccc3".to_string())]
        );
    }

    #[test]
    fn remint_mark_is_the_trailer_not_the_subject() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        std::fs::write(root.join("a.rs"), "// § abcdefgh1@aaaaa\nfn f() {}\n").unwrap();
        commit_all(root, 1, "pin");
        std::fs::write(root.join("a.rs"), "// § abcdefgh1@bbbbb\nfn f() {}\n").unwrap();
        commit_all(root, 2, "scheme remint of digests");
        assert!(!is_scheme_remint(root, "HEAD", "").unwrap());
        assert!(is_scheme_remint(root, "HEAD", "remint").unwrap());
        assert!(!is_scheme_remint(root, "HEAD^", "remint").unwrap());
    }

    #[test]
    fn declare_sentence_strips_marker() {
        let s = declare_sentence("§ k7m2x9p4a The graph fails open.", "k7m2x9p4a").unwrap();
        assert_eq!(s, "The graph fails open.");
    }

    #[test]
    fn remint_step_is_not_accept() {
        let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
@@ -1 +1 @@
-§ aaaaaaaa1 Same carrying sentence.
+§ cccccccc3 Same carrying sentence.
";
        let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
        let remint = remint_step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
        assert_eq!(remint.kind, StepKind::Remint);
        assert_eq!(remint.id, "cccccccc3");
        let force = step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
        assert_eq!(force.kind, StepKind::Accept);
    }

    #[test]
    fn accept_step_is_not_a_remint() {
        let diff = "\
--- a/docs/decisions/x.md
+++ b/docs/decisions/x.md
-§ aaaaaaaa1 The graph fails open.
+§ cccccccc3 The graph fails closed.
";
        let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
        let step = step_from_diff(diff, &family, "Ada", "6 Sep 2026").unwrap();
        assert_eq!(step.kind, StepKind::Accept);
        assert_eq!(step.id, "cccccccc3");
    }

    #[test]
    fn a_step_prints_the_old_and_new_sentence_in_full() {
        let old = "Le système doit bloqué les accès hors des heures ouvrées, sauf pour les comptes de service.";
        let new = "Le système doit bloquer les accès hors des heures ouvrées, sauf pour les comptes de service.";
        let diff = format!(
            "--- a/docs/decisions/x.md\n+++ b/docs/decisions/x.md\n@@ -1 +1 @@\n\
-**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> {old}**\n\
+**§ <a id=\"cccccccc3\">cccccccc3</a><a id=\"aaaaaaaa1\"></a> {new}**\n"
        );
        let family = BTreeSet::from(["aaaaaaaa1".into(), "cccccccc3".into()]);
        let step = step_from_diff(&diff, &family, "Alice", "2 Sep 2026").unwrap();
        assert_eq!(step.kind, StepKind::Accept);
        assert_eq!(
            render_step(&step),
            format!("[cccccccc3] accept, Alice, 2 Sep 2026\n  - {old}\n  + {new}\n")
        );
    }

    #[test]
    fn a_declaration_prints_only_the_new_sentence() {
        let diff = "--- a/docs/decisions/x.md\n+++ b/docs/decisions/x.md\n@@ -0,0 +1 @@\n\
+**§ <a id=\"aaaaaaaa1\">aaaaaaaa1</a> The graph fails closed.**\n";
        let family = BTreeSet::from(["aaaaaaaa1".into()]);
        let step = step_from_diff(diff, &family, "Bob", "14 May 2026").unwrap();
        assert_eq!(
            render_step(&step),
            "[aaaaaaaa1] declare, Bob, 14 May 2026\n  + The graph fails closed.\n"
        );
    }

    #[test]
    fn can_trace_finds_id_after_commit() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
        std::fs::write(
            root.join("docs/decisions/x.md"),
            "**§ k7m2x9p4a The graph fails open.**\n",
        )
        .unwrap();
        commit_all(root, 1, "declare");
        assert!(can_trace(root, "k7m2x9p4a").unwrap());
        assert!(!can_trace(root, &unhistoried_id()).unwrap());
    }

    #[test]
    fn the_walk_reads_the_docs_base_and_code_outside_src() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        crate::meta::tests::notes_tree(root, id);
        assert!(can_trace(root, id).unwrap());
        let steps = collect_steps(
            &History::new(root),
            &BTreeSet::from([id.to_string()]),
            false,
        )
        .unwrap();
        let kinds: Vec<_> = steps.iter().map(|s| s.kind).collect();
        assert_eq!(kinds, [StepKind::Declare]);
    }

    #[test]
    fn a_strike_is_a_retire_step() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        crate::meta::tests::notes_tree(root, id);
        let note = root.join(crate::meta::tests::NOTE);
        let sentence = crate::meta::tests::SENTENCE;
        let text = std::fs::read_to_string(&note).unwrap();
        std::fs::write(&note, text.replace(sentence, &format!("~~{sentence}~~"))).unwrap();
        crate::meta::tests::commit(root, "2026-01-14T12:00:00Z", "strike");
        let steps = collect_steps(
            &History::new(root),
            &BTreeSet::from([id.to_string()]),
            false,
        )
        .unwrap();
        let rendered: String = steps.iter().map(render_step).collect();
        assert_eq!(
            rendered,
            format!(
                "[{id}] retire, t, 14 Jan 2026\n  - {sentence}\n[{id}] declare, t, 2 Jan 2026\n  + {sentence}\n"
            )
        );
    }

    #[test]
    fn genealogy_check_flags_missing_history() {
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let id = unhistoried_id();
        let ids = vec![id.clone()];
        let existed = BTreeSet::from([id.clone()]);
        let (errors, warnings) = genealogy_check(&root, &ids, &existed);
        assert!(warnings.is_empty());
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains(&id));
    }

    #[test]
    fn genealogy_check_skips_new_laws() {
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let ids = vec![unhistoried_id()];
        let (errors, warnings) = genealogy_check(&root, &ids, &BTreeSet::new());
        assert!(errors.is_empty());
        assert!(warnings.is_empty());
    }

    fn commit_all(dir: &Path, day: u32, msg: &str) {
        let date = format!("2026-01-{day:02}T12:00:00Z");
        for args in [
            vec!["add", "-A"],
            vec!["commit", "-q", "--no-verify", "-m", msg],
        ] {
            // The identity is set through the environment: an ambient `GIT_AUTHOR_NAME`
            // would override a `-c user.name`, and the test reads the author back.
            let out = crate::test_git()
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(&args)
                .env("GIT_AUTHOR_NAME", "Ada")
                .env("GIT_AUTHOR_EMAIL", "a@a")
                .env("GIT_COMMITTER_NAME", "Ada")
                .env("GIT_COMMITTER_EMAIL", "a@a")
                .env("GIT_AUTHOR_DATE", &date)
                .env("GIT_COMMITTER_DATE", &date)
                .current_dir(dir)
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        }
    }

    #[test]
    fn a_digest_change_is_a_repin_unless_the_scheme_changed() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        std::fs::create_dir_all(root.join("src")).unwrap();
        let write = |law: &str, a: &str, extra: &str| {
            std::fs::write(
                root.join("src/lib.rs"),
                format!(
                    "fn run() {{\n    // § abcdefgh1@{law}\n    // § abcdefgh1.a@{a}\n{extra}    // § zyxwvtsr1@{a}\n}}\n"
                ),
            )
            .unwrap();
        };
        write("bbbbb", "aaaaa", "");
        commit_all(root, 1, "pin\n\nSilcrow-Scheme: 4");
        write("bbbbb", "ccccc", "");
        commit_all(root, 2, "re-pin a letter");
        write("eeeee", "fffff", "");
        commit_all(root, 3, "scheme\n\nSilcrow-Op: remint\nSilcrow-Scheme: 5");
        write("ggggg", "fffff", "");
        commit_all(root, 4, "re-pin the law\n\nSilcrow-Scheme: 5");
        write("hhhhh", "fffff", "");
        commit_all(root, 5, "scheme\n\nSilcrow-Scheme: 6");
        write("hhhhh", "fffff", "    // § abcdefgh1.b@ddddd\n");
        commit_all(root, 6, "first pin of a new letter");
        // Trailers written by hand on a commit that changes code beside the digest.
        write("iiiii", "fffff", "    // § abcdefgh1.b@ddddd\n    go();\n");
        commit_all(root, 7, "code\n\nSilcrow-Op: remint\nSilcrow-Scheme: 7");

        let family = BTreeSet::from(["abcdefgh1".to_string()]);
        let (repins, remints) = digest_changes(root, &family).unwrap();
        let seen: Vec<_> = repins
            .iter()
            .map(|r| (r.date.as_str(), r.addresses.join(",")))
            .collect();
        assert_eq!(
            seen,
            vec![
                ("2 Jan 2026", "abcdefgh1.a".to_string()),
                ("4 Jan 2026", "abcdefgh1".to_string()),
                ("7 Jan 2026", "abcdefgh1".to_string())
            ]
        );
        assert_eq!(remints.len(), 2);
        let counts = rewrite_counts(root, "abcdefgh1").unwrap();
        assert_eq!((counts.remints, counts.repins.len()), (2, 3));
        let line = render_repin(&repins[0]);
        assert!(
            line.starts_with(&format!(
                "  re-pin  {}  Ada, 2 Jan 2026  abcdefgh1.a",
                repins[0].sha
            )),
            "{line}"
        );
        assert_eq!(repins[0].sha.len(), 7);
    }

    #[test]
    fn a_repin_counts_only_a_line_its_file_reads_as_a_marker() {
        let patch = "\ndiff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -3 +3 @@\n-// § abcdefgh1.a@aaaaa\n+// § abcdefgh1.a@bbbbb\ndiff --git a/q.sql b/q.sql\n--- a/q.sql\n+++ b/q.sql\n@@ -1 +1 @@\n--- § abcdefgh1.b@ccccc\n+-- § abcdefgh1.b@ddddd\n";
        let files = |new: bool, path: &str| -> Result<String> {
            Ok(match (path, new) {
                ("src/lib.rs", false) => "fn f() {\n    r\"\n// § abcdefgh1.a@aaaaa\n\";\n}\n",
                ("src/lib.rs", true) => "fn f() {\n    r\"\n// § abcdefgh1.a@bbbbb\n\";\n}\n",
                ("q.sql", false) => "-- § abcdefgh1.b@ccccc\nselect 1;\n",
                ("q.sql", true) => "-- § abcdefgh1.b@ddddd\nselect 1;\n",
                _ => unreachable!("{path}"),
            }
            .to_string())
        };
        assert_eq!(
            repinned_addresses(patch, "abcdefgh1", &files).unwrap(),
            vec!["abcdefgh1.b"]
        );
    }

    /// Built at runtime: a literal id in this file would enter the pickaxe
    /// history on the commit that adds it, and the test would fail from then on.
    fn unhistoried_id() -> String {
        "vv3".repeat(3)
    }
}