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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
//! The review `diff` prints: one entry per law, each clause under it, under each the places
//! that moved for it, then the changes no law governs. The TTY, the markdown packet and JSON
//! render this one structure.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use super::ungoverned::FileHunks;
use super::{
    byte_line, extract_punched, json_escape, line_span, lost_pin, nest_changes, pair_spans,
    parse_files, pin_lines, punched_in, qualify, BlockRow, CalleeDiff, Callers, Change, FileMap,
    FollowIndex, Kind, ParsedMap, Shown,
};
use crate::span;

/// What happened to a law or to one of its addresses, in the order the review prints them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Status {
    // § x6knpe5fd@ssy8y
    Deleted,
    Retired,
    Removed,
    Drafted,
    /// A public promise made plain, which drops its documentation duty as a `?` drops a duty.
    Plain,
    Accepted,
    New,
    /// A remint, read as a text change.
    Reminted,
    TextChanged,
    /// The prose between a head and its clauses, which binds nothing.
    ContextChanged,
    /// A plain law made a public promise.
    Public,
    Changed,
}

impl Status {
    pub(super) fn status_key(self) -> &'static str {
        match self {
            Status::Deleted => "deleted",
            Status::Retired => "retired",
            Status::Removed => "removed",
            Status::Drafted => "drafted",
            Status::Plain => "plain",
            Status::Accepted => "accepted",
            Status::New => "new",
            Status::Reminted => "reminted",
            Status::TextChanged => "text-changed",
            Status::ContextChanged => "context-changed",
            Status::Public => "public",
            Status::Changed => "changed",
        }
    }

    fn status_label(self) -> &'static str {
        match self {
            Status::Deleted => "deleted without a strike",
            Status::Retired => "retired",
            Status::Removed => "removed after a published strike",
            Status::Drafted => "made a draft",
            Status::Plain => "made plain",
            Status::Accepted => "behaviour change accepted",
            Status::New => "new",
            Status::Reminted => "reminted",
            Status::TextChanged => "text changed",
            Status::ContextChanged => "context changed",
            Status::Public => "made a public promise",
            Status::Changed => "code changed",
        }
    }

    /// What the reviewer judges for a law of this status, its addresses named in `what`.
    fn status_check(self, what: &str) -> String {
        match self {
            Status::Deleted => format!("was {what} meant to go with no strike, and does nothing still rely on it?"),
            Status::Retired | Status::Removed => format!("does nothing still rely on {what}, and does its successor, if any, carry what still holds?"),
            Status::Drafted => format!("was {what} meant to owe no marker until it is implemented, and does nothing still rely on the code its markers covered?"),
            Status::Accepted | Status::Changed => format!("does the code below still do what {what} says?"),
            Status::New => format!("does the code below do what {what} says, and does every place that carries it hold a marker?"),
            Status::Reminted => format!("does the new text of {what} state the same decision, and does the code below still do what it says?"),
            Status::TextChanged => format!("does the code below still do what the new text of {what} says?"),
            Status::ContextChanged => format!("does the new context of {what} leave its text meaning what it says, and does nothing the context adds need a law or a clause?"),
            Status::Plain => format!("was {what} meant to leave the public documentation, and does no public page still promise it?"),
            Status::Public => format!("does the public documentation carry {what}, with a marker in a file the `docs` list matches?"),
        }
    }
}

/// The status one change gives its address, `None` for a change that only recalls context.
fn status_of(change: &Change) -> Option<Status> {
    // § x6knpe5fd@vxhtz
    Some(match change.kind {
        Kind::Deleted => Status::Deleted,
        Kind::Retired => Status::Retired,
        Kind::Reminted => Status::Reminted,
        Kind::Removed => Status::Removed,
        // § x6knpe5fd.a@7zzq2
        Kind::Draft if change.why.as_deref() == Some(super::DRAFT_MADE) => Status::Drafted,
        Kind::Draft if change.why.as_deref() == Some(super::DRAFT_DROPPED) => Status::New,
        Kind::Draft => return None,
        Kind::Public if change.why.as_deref() == Some(super::PUBLIC_DROPPED) => Status::Plain,
        Kind::Public => Status::Public,
        // § end x6knpe5fd.a
        Kind::Accepted => Status::Accepted,
        Kind::Marker if lost_pin(change) => Status::Accepted,
        Kind::Declared | Kind::Reused => Status::New,
        Kind::Clause if change.old_text.is_none() => Status::New,
        Kind::Amended | Kind::Clause => Status::TextChanged,
        Kind::Context => Status::ContextChanged,
        Kind::Recall => return None,
        Kind::Marker if stable(change) => return None,
        Kind::Moved | Kind::Cite | Kind::Marker | Kind::Drift => Status::Changed,
    })
}

/// A marker listed as context beside the changes of its address, which moved nothing itself.
fn stable(change: &Change) -> bool {
    change.lines == [None, None] && change.old_text == change.new_text
}

/// One law and what moved for it.
pub(super) struct Rule {
    /// The id, qualified for a project other than the root.
    pub(super) id: String,
    pub(super) status: Status,
    /// The decision note, from the workspace root.
    pub(super) note: String,
    pub(super) head: Part,
    pub(super) clauses: Vec<Part>,
    /// Some drift of the law moved its own span, not only what the span reads.
    pub(super) span_moved: bool,
    /// The id a remint replaced, qualified as `id` is.
    pub(super) reminted_from: Option<String>,
}

impl Rule {
    /// What the heading says happened to the law: a remint names both ids.
    fn label(&self) -> String {
        match &self.reminted_from {
            Some(was) if self.status == Status::Reminted => {
                format!("reminted from {was} to {}", self.id)
            }
            Some(was) => format!(
                "reminted from {was} to {}, {}",
                self.id,
                self.status.status_label()
            ),
            None => self.status.status_label().to_string(),
        }
    }
}

/// The law's sentence or one of its clauses: its text on both sides and the places that
/// moved for it.
pub(super) struct Part {
    pub(super) address: String,
    pub(super) letter: Option<String>,
    pub(super) status: Option<Status>,
    pub(super) text: [Option<String>; 2],
    /// Whether the address is a draft on each side, as a change of its draft state says.
    pub(super) draft: [bool; 2],
    /// Whether the head is a public promise on each side, as a change of its `!` says.
    pub(super) public: [bool; 2],
    /// Every change of the address but its markers and its recall.
    pub(super) changes: Vec<Change>,
    pub(super) locations: Vec<Location>,
}

/// One file under an address: its pins, then what they read beyond their spans, then the
/// callees they follow, that changed.
pub(super) struct Location {
    pub(super) path: String,
    /// Whether the `docs` list of the project matches the file.
    pub(super) doc: bool,
    /// Whether each side holds the file.
    pub(super) exists: [bool; 2],
    pub(super) pins: Vec<Pin>,
    pub(super) reads: Vec<Body>,
    pub(super) callees: Vec<Body>,
}

pub(super) struct Pin {
    pub(super) kind: &'static str,
    /// The 1-based line of the marker on each side.
    pub(super) lines: [Option<usize>; 2],
    /// The 1-based line each side's text opens on.
    pub(super) starts: [usize; 2],
    pub(super) old: Option<String>,
    pub(super) new: Option<String>,
    pub(super) why: Option<String>,
    pub(super) callers: Vec<String>,
    /// For a pin removed while the code it spanned stands unchanged on the compared side, the
    /// 1-based line that code opens on there.
    pub(super) kept: Option<usize>,
}

impl Pin {
    /// The patch of the pin's code with its marker lines left out: code a removed pin spanned
    /// and the compared side keeps reads as itself, not as deleted.
    fn hunks(&self, exists: [bool; 2], label: &str) -> String {
        let starts = [0, 1].map(|side| self.starts[side] * usize::from(exists[side]));
        match self.kept {
            Some(at) => unmarked_hunks(
                self.old.as_deref(),
                self.old.as_deref(),
                [starts[0], at],
                label,
            ),
            None => unmarked_hunks(self.old.as_deref(), self.new.as_deref(), starts, label),
        }
    }
}

/// A stretch a pin reads, or a callee it follows, with the line each side's text opens on.
pub(super) struct Body {
    pub(super) diff: CalleeDiff,
    pub(super) starts: [usize; 2],
}

/// The whole review of one `diff` run.
pub(super) struct Review {
    pub(super) base: String,
    /// The laws and clauses `--law` keeps, none for every law.
    pub(super) laws: Vec<String>,
    pub(super) folded: usize,
    pub(super) block: Vec<BlockRow>,
    pub(super) rules: Vec<Rule>,
    pub(super) ungoverned: Vec<FileHunks>,
}

impl Review {
    /// The review of `rules`, most at risk first: what retires a rule, then what changes
    /// behaviour, then what is new, then the rest, each by id.
    pub(super) fn gather(
        base: String,
        laws: Vec<String>,
        folded: usize,
        block: Vec<BlockRow>,
        mut rules: Vec<Rule>,
        ungoverned: Vec<FileHunks>,
    ) -> Self {
        // § x6knpe5fd@cx7cv
        rules.sort_by(|a, b| {
            (a.status, !a.span_moved, &a.id).cmp(&(b.status, !b.span_moved, &b.id))
        });
        Self {
            base,
            laws,
            folded,
            block,
            rules,
            ungoverned,
        }
    }

    pub(super) fn holds_nothing(&self) -> bool {
        self.rules.is_empty()
            && self.folded == 0
            && self.block.is_empty()
            && self.ungoverned.is_empty()
    }
}

/// The laws `changes` name, each with its clauses and the places that moved for them, paths
/// and addresses as the workspace root reads them.
pub(super) fn law_entries(
    changes: &[Change],
    files: &FileMap,
    follow: &FollowIndex,
    callers: &Callers,
    shown: &Shown,
) -> Vec<Rule> {
    // § yjrm4q97t@8nw3c
    let parsed = parse_files(files);
    let at = Places {
        files,
        parsed: &parsed,
        follow,
        callers,
        shown,
    };
    let mut out = Vec::new();
    for (id, law) in nest_changes(changes) {
        // § n4fbh9vd4.a@jkphh
        let reminted_from = law
            .changes
            .iter()
            .filter(|c| c.kind == Kind::Reminted)
            .find_map(|c| c.why.as_deref()?.strip_prefix(super::REMINTED_FROM))
            .map(|was| qualify(shown.key, was.trim_end_matches('.')));
        // § end n4fbh9vd4.a
        let reminted = reminted_from.is_some();
        let head = at.place_part(&id, None, &law.changes, &law.markers, reminted);
        let clauses: Vec<Part> = law
            .clauses
            .iter()
            .map(|(letter, clause)| {
                at.place_part(
                    &format!("{id}.{letter}"),
                    Some(letter),
                    &clause.changes,
                    &clause.markers,
                    reminted,
                )
            })
            .filter(|part| part.status.is_some() || !part.locations.is_empty())
            .collect();
        let Some(status) = head
            .status
            .into_iter()
            .chain(clauses.iter().filter_map(|part| part.status))
            .min()
        else {
            continue;
        };
        let note = law
            .changes
            .iter()
            .chain(law.clauses.values().flat_map(|clause| &clause.changes))
            .find_map(|change| change.new_path.as_ref().or(change.old_path.as_ref()))
            .map_or(String::new(), |path| format!("{}{path}", shown.prefix));
        // § x6knpe5fd.b@64w54
        let span_moved = law
            .markers
            .iter()
            .chain(law.clauses.values().flat_map(|clause| &clause.markers))
            .filter(|c| matches!(c.kind, Kind::Drift | Kind::Accepted))
            .any(|c| {
                c.old_text.as_deref().map(super::strip_digests)
                    != c.new_text.as_deref().map(super::strip_digests)
            });
        out.push(Rule {
            id: qualify(shown.key, &id),
            status,
            note,
            head,
            clauses,
            span_moved,
            reminted_from,
        });
    }
    out
}

struct Places<'a> {
    files: &'a FileMap,
    parsed: &'a ParsedMap,
    follow: &'a FollowIndex,
    callers: &'a Callers,
    shown: &'a Shown<'a>,
}

impl Places<'_> {
    fn place_part(
        &self,
        address: &str,
        letter: Option<&String>,
        changes: &[Change],
        markers: &[Change],
        reminted: bool,
    ) -> Part {
        // § x6knpe5fd@4yj4z
        // A remint moves the text every pin of its law hashes, and a pin that moved for that
        // alone is part of the remint, not a behaviour change.
        let status = changes
            .iter()
            .chain(markers)
            .filter_map(|c| match status_of(c) {
                Some(Status::Accepted)
                    if reminted && c.why.as_deref() == Some(super::TEXT_MOVE) =>
                {
                    Some(Status::Reminted)
                }
                status => status,
            })
            .min();
        let recall = changes.iter().find(|c| {
            matches!(
                c.kind,
                Kind::Declared
                    | Kind::Retired
                    | Kind::Reminted
                    | Kind::Removed
                    | Kind::Deleted
                    | Kind::Moved
                    | Kind::Amended
                    | Kind::Clause
                    | Kind::Reused
                    | Kind::Recall
                    | Kind::Draft
                    | Kind::Public
            )
        });
        let mut kept: Vec<Change> = changes
            .iter()
            .filter(|c| c.kind != Kind::Recall)
            .cloned()
            .collect();
        for change in &mut kept {
            change.address = qualify(self.shown.key, &change.address);
            for path in [&mut change.old_path, &mut change.new_path]
                .into_iter()
                .flatten()
            {
                *path = format!("{}{path}", self.shown.prefix);
            }
        }
        Part {
            address: qualify(self.shown.key, address),
            letter: letter.cloned(),
            status,
            text: [
                recall.and_then(|c| c.old_text.clone()),
                recall.and_then(|c| c.new_text.clone()),
            ],
            draft: changes.iter().find(|c| c.kind == Kind::Draft).map_or(
                [false, false],
                |c| match c.why.as_deref() {
                    Some(super::DRAFT_MADE) => [false, true],
                    Some(super::DRAFT_DROPPED) => [true, false],
                    _ => [false, true],
                },
            ),
            public: changes
                .iter()
                .find(|c| c.kind == Kind::Public)
                .map_or([false, false], |c| match c.why.as_deref() {
                    Some(super::PUBLIC_DROPPED) => [true, false],
                    _ => [false, true],
                }),
            changes: kept,
            locations: self.place_locations(address, markers),
        }
    }

    /// The places of `address`, one per file its marker changes name, in path order.
    fn place_locations(&self, address: &str, markers: &[Change]) -> Vec<Location> {
        // § yjrm4q97t.a@ee1ph
        let paths: BTreeSet<&str> = markers.iter().map(change_path).collect();
        let mut out = Vec::new();
        for path in paths {
            let here: Vec<&Change> = markers.iter().filter(|c| change_path(c) == path).collect();
            // § jncrstyg1.b@66wp4
            let callee_moved: BTreeSet<usize> = here
                .iter()
                .filter(|c| !c.callees.is_empty())
                .filter_map(|c| c.lines[1])
                .collect();
            let exists = self
                .files
                .get(path)
                .map_or([true, true], |(old, new)| [old.is_some(), new.is_some()]);
            let spans = match self.files.get(path) {
                Some((old, new)) => span_pins(
                    path,
                    address,
                    [old.as_deref(), new.as_deref()],
                    self.parsed.get(path),
                    (self.follow, &callee_moved),
                ),
                None => Vec::new(),
            };
            let mut pins: Vec<Pin> = if spans.is_empty() {
                here.iter()
                    .map(|change| self.raw_pin(change, address, &callee_moved))
                    .collect()
            } else {
                spans
                    .into_iter()
                    .map(|mut pin| {
                        let change = here.iter().find(|c| {
                            (pin.lines[1].is_some() && c.lines[1] == pin.lines[1])
                                || (pin.lines[0].is_some() && c.lines[0] == pin.lines[0])
                        });
                        pin.kind = pin_kind(change.copied(), &pin.old, &pin.new);
                        pin.why =
                            super::joined_notes(change.and_then(|c| c.why.clone()), pin.why.take());
                        pin
                    })
                    .collect()
            };
            for pin in &mut pins {
                if let Some(line) = pin.lines[1] {
                    pin.callers = self
                        .callers
                        .get(&(path.to_string(), line))
                        .cloned()
                        .unwrap_or_default();
                }
            }
            let bodies: BTreeSet<&CalleeDiff> = here.iter().flat_map(|c| &c.callees).collect();
            let (mut reads, callees): (Vec<&CalleeDiff>, Vec<&CalleeDiff>) =
                bodies.into_iter().partition(|body| body.read.is_some());
            // The set orders by label: the stretches print in the order the law lists their kinds.
            reads.sort_by_key(|body| body.read);
            let body = |diff: &CalleeDiff| {
                let mut diff = diff.clone();
                let starts = [0, 1].map(|side| {
                    let text = self
                        .files
                        .get(&diff.path)
                        .and_then(|t| [&t.0, &t.1][side].as_deref());
                    let shown = [&diff.old, &diff.new][side].as_deref();
                    text.zip(shown)
                        .and_then(|(text, shown)| opening_line(text, shown))
                        .unwrap_or(1)
                });
                diff.path = format!("{}{}", self.shown.prefix, diff.path);
                Body { diff, starts }
            };
            out.push(Location {
                exists,
                doc: self.shown.docs.matches(Path::new(path)),
                path: format!("{}{path}", self.shown.prefix),
                pins,
                reads: reads.into_iter().map(body).collect(),
                callees: callees.into_iter().map(body).collect(),
            });
        }
        out
    }

    /// A pin as its change writes it, for a file whose spans `diff` does not read.
    fn raw_pin(&self, change: &Change, address: &str, callee_moved: &BTreeSet<usize>) -> Pin {
        // § yjrm4q97t.a@055fz
        let notice = change.lines[1]
            .filter(|line| callee_moved.contains(line))
            .and_then(|line| {
                self.follow
                    .drift_notice(Path::new(change_path(change)), line, address)
            });
        Pin {
            kind: pin_kind(Some(change), &change.old_text, &change.new_text),
            lines: change.lines,
            starts: [change.lines[0].unwrap_or(1), change.lines[1].unwrap_or(1)],
            old: change.old_text.clone(),
            new: change.new_text.clone(),
            why: super::joined_notes(change.why.clone(), notice),
            callers: Vec::new(),
            kept: None,
        }
    }
}

fn change_path(change: &Change) -> &str {
    change
        .new_path
        .as_deref()
        .or(change.old_path.as_deref())
        .unwrap_or("?")
}

/// The 1-based line of `text` that the first line of `shown` stands on.
fn opening_line(text: &str, shown: &str) -> Option<usize> {
    if let Some(at) = text.find(shown) {
        return Some(byte_line(text, at));
    }
    let first = shown.lines().next()?;
    text.lines()
        .position(|line| line == first)
        .map(|idx| idx + 1)
}

fn pin_kind(change: Option<&Change>, old: &Option<String>, new: &Option<String>) -> &'static str {
    match change.map(|c| c.kind) {
        Some(Kind::Accepted) => "accepted",
        Some(Kind::Drift) => "drift",
        _ if old.is_none() => "added",
        _ if new.is_none() => "removed",
        Some(_) if change.is_some_and(|c| !stable(c)) => "changed",
        _ => "unchanged",
    }
}

/// Each pin of `address` in `path`, its punched span on each side, paired across the sides.
fn span_pins(
    path: &str,
    address: &str,
    texts: [Option<&str>; 2],
    parsed: Option<&[Option<Vec<span::SpanMarker>>; 2]>,
    (follow, callee_moved): (&FollowIndex, &BTreeSet<usize>),
) -> Vec<Pin> {
    // § yjrm4q97t.a@bfkv3
    let [old, new] = texts;
    let rel = Path::new(path);
    let pins = [
        pin_lines(rel, old.unwrap_or(""), address),
        pin_lines(rel, new.unwrap_or(""), address),
    ];
    if pins.iter().all(Vec::is_empty) {
        return Vec::new();
    }
    let markers = |side: usize| parsed.and_then(|sides| sides[side].as_deref());
    let punched = |side: usize, text: &str, line: usize| match markers(side) {
        Some(markers) => punched_in(text, markers, line).map(|(span, _, _)| span),
        None => extract_punched(rel, text, line),
    };
    let opens = |side: usize, text: &str, line: usize| {
        let start = match markers(side) {
            Some(markers) => markers
                .iter()
                .find(|m| m.line == line)
                .map(|m| byte_line(text, m.start)),
            None => line_span(rel, text, line).map(|(start, _)| start),
        };
        start.map_or(line, |start| start.min(line))
    };
    let bodies = |side: usize| -> Vec<Option<String>> {
        pins[side]
            .iter()
            .map(|line| texts[side].and_then(|text| punched(side, text, *line)))
            .collect()
    };
    let (old_bodies, new_bodies) = (bodies(0), bodies(1));
    let mut out = Vec::new();
    for (i, j) in pair_spans(&old_bodies, &new_bodies) {
        let old_body = i.and_then(|i| old_bodies[i].clone());
        let new_body = j.and_then(|j| new_bodies[j].clone());
        if old_body.is_none() && new_body.is_none() {
            continue;
        }
        let lines = [i.map(|i| pins[0][i]), j.map(|j| pins[1][j])];
        // § jncrstyg1.b@3ebpt
        let why = match (&old_body, &new_body, lines[1]) {
            (Some(o), Some(n), Some(line)) if o != n || callee_moved.contains(&line) => {
                follow.drift_notice(rel, line, address)
            }
            _ => None,
        };
        // § end jncrstyg1.b
        let start = |side: usize| {
            lines[side]
                .zip(texts[side])
                .map_or(1, |(line, text)| opens(side, text, line))
        };
        let kept = match (lines, texts, &new_body) {
            ([Some(line), None], [Some(old), Some(new)], None) => {
                let region = match markers(0) {
                    Some(markers) => markers.iter().find(|m| m.line == line).map(|m| {
                        let end = byte_line(old, m.end.saturating_sub(1).max(m.start));
                        (byte_line(old, m.start).min(line), end)
                    }),
                    None => line_span(rel, old, line).map(|(from, to)| (from.min(line), to)),
                };
                region.and_then(|region| kept_at(old, region, new))
            }
            _ => None,
        };
        out.push(Pin {
            kind: "unchanged",
            lines,
            starts: [start(0), start(1)],
            old: old_body,
            new: new_body,
            why: match kept {
                Some(_) => super::joined_notes(why, Some(KEPT.to_string())),
                None => why,
            },
            callers: Vec::new(),
            kept,
        });
    }
    out
}

const KEPT: &str = "Only its marker went: the code it spanned stands unchanged.";

/// The 1-based line of `new` where the lines `from..=to` of `old` stand unchanged, marker lines
/// left out on both sides.
fn kept_at(old: &str, (from, to): (usize, usize), new: &str) -> Option<usize> {
    let want: Vec<&str> = old
        .lines()
        .skip(from.checked_sub(1)?)
        .take((to + 1).saturating_sub(from))
        .filter(|line| !is_marker_line(line))
        .collect();
    if want.iter().all(|line| line.trim().is_empty()) {
        return None;
    }
    let have: Vec<(usize, &str)> = new
        .lines()
        .enumerate()
        .filter(|(_, line)| !is_marker_line(line))
        .collect();
    have.windows(want.len())
        .find(|window| {
            window
                .iter()
                .map(|(_, line)| *line)
                .eq(want.iter().copied())
        })
        .map(|window| window[0].0 + 1)
}

/// Each law's address list a reviewer judges: the clauses that moved, else the law.
fn judged(rule: &Rule) -> String {
    let moved: Vec<&str> = std::iter::once(&rule.head)
        .chain(&rule.clauses)
        .filter(|part| part.status.is_some())
        .map(|part| part.address.as_str())
        .collect();
    match moved.as_slice() {
        [] => rule.id.clone(),
        [one] => one.to_string(),
        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
    }
}

const HOW: &str = "Each section is one law. Read its text, then each place under it: the spans, the code before them, the followed callees and the doc sections that changed. Judge whether they still do what the text says. Then judge whether a change under no law carries a rule that lacks a law or a marker.";
const UNGOVERNED: &str = "Changes under no law";
const UNGOVERNED_WHY: &str = "No marker covers these lines and no pin reads them. Check: does any of them carry a rule that lacks a law or a marker?";

/// The review as markdown: the TTY pages it through delta, `--md` prints it as is.
pub(super) fn review_markdown(review: &Review) -> String {
    // § pzp9mfhph@0vk28
    let mut out = format!("# Silcrow review against {}\n\n", review.base);
    if review.holds_nothing() {
        match review.laws.is_empty() {
            false => out.push_str(&format!(
                "No updated references for {}.\n",
                review.laws.join(", ")
            )),
            true => out.push_str("No updated references.\n"),
        }
        return out;
    }
    out.push_str(&format!("{}\n\n", summary(review)));
    if review.laws.is_empty() {
        out.push_str(&format!("{HOW}\n\n"));
    }
    if review.folded > 0 {
        out.push_str(&format!("{}\n\n", super::remint_line(review.folded).trim()));
    }
    if !review.block.is_empty() {
        out.push_str(&format!("## {}\n\n", super::BLOCK_HEADING));
        out.push_str(&fence(&block_diff(&review.block)));
    }
    for rule in &review.rules {
        out.push_str(&rule_markdown(rule));
    }
    if !review.ungoverned.is_empty() {
        // § pzp9mfhph.a@kr3r9
        out.push_str(&format!("## {UNGOVERNED}\n\n{UNGOVERNED_WHY}\n\n"));
        // § end pzp9mfhph.a
        for file in &review.ungoverned {
            out.push_str(&format!("* `{}`: {}\n", file.path, file.counts()));
        }
        out.push('\n');
        let patch: String = review.ungoverned.iter().map(FileHunks::patch).collect();
        if !patch.is_empty() {
            out.push_str(&fence(&patch));
        }
    }
    out
}

/// The review a person reads on a TTY: per law, its text as one patch of its note, then the
/// code that moved for it, then the changes under no law, with no prose and no marker.
pub(super) fn review_tty(review: &Review) -> String {
    // § pzp9mfhph@7b0r5
    let mut out = String::new();
    if review.folded > 0 {
        out.push_str(&format!("{}\n\n", super::remint_line(review.folded).trim()));
    }
    if !review.block.is_empty() {
        out.push_str(&block_diff(&review.block));
    }
    for rule in &review.rules {
        out.push_str(&rule_tty(rule));
    }
    for file in &review.ungoverned {
        out.push_str(&file.patch());
    }
    out
}

/// One law: its sentence and the clauses it lists as one hunk of its note, then one patch per
/// file of the spans, the stretches they read and the callees that moved.
fn rule_tty(rule: &Rule) -> String {
    let parts: Vec<&Part> = std::iter::once(&rule.head).chain(&rule.clauses).collect();
    let context = |at: usize| -> String {
        // § n4fbh9vd4.i@zfhzh
        rule.head
            .changes
            .iter()
            .filter(|c| c.kind == Kind::Context)
            .filter_map(|c| [&c.old_text, &c.new_text][at].as_deref())
            .map(|text| format!("\n{text}\n"))
            .collect()
    };
    let side = |at: usize| -> String {
        parts
            .iter()
            .enumerate()
            .map(|(i, part)| {
                let line = part.text[at].as_deref().map(|text| {
                    // § n4fbh9vd4.g@kjx21
                    let draft = part.draft[at];
                    match &part.letter {
                        Some(letter) => format!("({letter}){} {text}\n", crate::list::mark(draft)),
                        // § n4fbh9vd4.h@ka4pj
                        None => match (part.public[at], draft) {
                            (true, true) => format!("§!? {text}\n"),
                            (true, false) => format!("§! {text}\n"),
                            (false, true) => format!("§? {text}\n"),
                            (false, false) => format!("{text}\n"),
                        },
                        // § end n4fbh9vd4.h
                    }
                    // § end n4fbh9vd4.g
                });
                let under = match i {
                    0 => context(at),
                    _ => String::new(),
                };
                line.unwrap_or_default() + &under
            })
            .collect()
    };
    let (old, new) = (side(0), side(1));
    let note = match rule.note.is_empty() {
        true => rule.id.as_str(),
        false => rule.note.as_str(),
    };
    // The note stays on both sides: a law that comes or goes is lines of it, not the file.
    let mut out = match old.is_empty() && new.is_empty() {
        true => String::new(),
        false => file_patch(note, [true, true], &[hunk(&old, &new, [1, 1], &rule.id)]),
    };
    let mut files: Vec<(String, [bool; 2], Vec<String>)> = Vec::new();
    let mut add = |path: &str, exists: [bool; 2], hunks: String| {
        if hunks.is_empty() {
            return;
        }
        match files.iter_mut().find(|(p, _, _)| p == path) {
            Some((_, _, all)) if all.contains(&hunks) => {}
            Some((_, _, all)) => all.push(hunks),
            None => files.push((path.to_string(), exists, vec![hunks])),
        }
    };
    for part in &parts {
        for location in &part.locations {
            for pin in &location.pins {
                let label = part
                    .letter
                    .as_ref()
                    .map_or(String::new(), |letter| format!("({letter})"));
                add(
                    &location.path,
                    location.exists,
                    pin.hunks(location.exists, &label),
                );
            }
            for body in location.reads.iter().chain(&location.callees) {
                let hunks = unmarked_hunks(
                    body.diff.old.as_deref(),
                    body.diff.new.as_deref(),
                    body.starts,
                    &body.diff.name,
                );
                add(&body.diff.path, [true, true], hunks);
            }
        }
    }
    for (path, exists, hunks) in files {
        out.push_str(&file_patch(&path, exists, &hunks));
    }
    out
}

/// One line that counts the laws by status and the files under no law.
fn summary(review: &Review) -> String {
    let mut counts: BTreeMap<Status, usize> = BTreeMap::new();
    for rule in &review.rules {
        *counts.entry(rule.status).or_default() += 1;
    }
    let laws = match review.rules.len() {
        1 => "1 law".to_string(),
        n => format!("{n} laws"),
    };
    let by: Vec<String> = counts
        .iter()
        .map(|(status, n)| format!("{n} {}", status.status_label()))
        .collect();
    let mut line = match by.is_empty() {
        true => format!("{laws}."),
        false => format!("{laws}: {}.", by.join(", ")),
    };
    if review.laws.is_empty() {
        line.push_str(&match review.ungoverned.len() {
            0 => " Nothing changed under no law.".to_string(),
            1 => " 1 file changed under no law.".to_string(),
            n => format!(" {n} files changed under no law."),
        });
    }
    line
}

fn rule_markdown(rule: &Rule) -> String {
    let mut out = format!("## § {}: {}\n\n", rule.id, rule.label());
    if !rule.note.is_empty() {
        out.push_str(&format!("Decision note `{}`.\n\n", rule.note));
    }
    // § pzp9mfhph.a@c38f4
    out.push_str(&format!(
        "Check: {}\n\n",
        rule.status.status_check(&judged(rule))
    ));
    // § end pzp9mfhph.a
    out.push_str(&part_markdown(&rule.head, &rule.note));
    for clause in &rule.clauses {
        let heading = match clause.status {
            Some(status) => format!("### {}: {}\n\n", clause.address, status.status_label()),
            None => format!("### {}\n\n", clause.address),
        };
        out.push_str(&heading);
        out.push_str(&part_markdown(clause, &rule.note));
    }
    out
}

fn part_markdown(part: &Part, note: &str) -> String {
    let mut out = String::new();
    // § pzp9mfhph@e3804
    match &part.text {
        [None, None] => {}
        // § pzp9mfhph.g@zxfgt
        [old, new] if old == new => {
            if let Some(text) = new {
                out.push_str(&quote_lines(&super::structure::plain(text)));
            }
        }
        // § end pzp9mfhph.g
        [old, new] => {
            out.push_str(&super::structure::view(old.as_deref(), new.as_deref()));
            // § pzp9mfhph.f@qxjrm
            let label = format!("text of {}", part.address);
            let hunk = hunk_of(old.as_deref(), new.as_deref(), [1, 1], &label);
            out.push_str(&format!(
                "<details>\n<summary>Patch of {}</summary>\n\n{}</details>\n\n",
                part.address,
                fence(&file_patch(note, [true, true], &[hunk]))
            ));
            // § end pzp9mfhph.f
        }
    }
    for change in part.changes.iter().filter(|c| c.kind == Kind::Context) {
        // § n4fbh9vd4.i@2wj7w
        let (old, new) = (change.old_text.as_deref(), change.new_text.as_deref());
        out.push_str(&format!("{}\n\n", super::CONTEXT_MOVED));
        out.push_str(&super::structure::view(old, new));
        let label = format!("context of {}", part.address);
        out.push_str(&format!(
            "<details>\n<summary>Patch of the context of {}</summary>\n\n{}</details>\n\n",
            part.address,
            fence(&file_patch(
                note,
                [true, true],
                &[hunk_of(old, new, [1, 1], &label)]
            ))
        ));
        // § end n4fbh9vd4.i
    }
    for change in &part.changes {
        if let Some(line) = other_change(change) {
            out.push_str(&format!("* {line}\n"));
        }
    }
    if part.changes.iter().any(|c| other_change(c).is_some()) {
        out.push('\n');
    }
    for location in &part.locations {
        out.push_str(&location_markdown(
            location,
            &part.address,
            part.text[0] == part.text[1],
        ));
    }
    out
}

/// A change of an address that is neither its text nor a marker, as one line.
fn other_change(change: &Change) -> Option<String> {
    let at = |path: &Option<String>| path.clone().unwrap_or_default();
    match change.kind {
        Kind::Moved => Some(format!(
            "Moved from `{}` to `{}`.",
            at(&change.old_path),
            at(&change.new_path)
        )),
        Kind::Cite if change.old_text.is_none() => {
            Some(format!("Cited in `{}`.", at(&change.new_path)))
        }
        Kind::Cite => Some(format!("No longer cited in `{}`.", at(&change.old_path))),
        // § n4fbh9vd4.g@drd47
        Kind::Draft => change.why.clone(),
        // § end n4fbh9vd4.g
        // § n4fbh9vd4.h@7sk9f
        Kind::Public => change.why.clone(),
        // § end n4fbh9vd4.h
        _ => None,
    }
}

/// One place of `address`, its code patched unless both it and the text of the address,
/// `text_kept`, read as they did: then there is nothing under it to judge anew.
fn location_markdown(location: &Location, address: &str, text_kept: bool) -> String {
    let what = match location.doc {
        true => "doc section",
        false => "span",
    };
    let mut said = Vec::new();
    let mut sections: Vec<(&str, String)> = Vec::new();
    for pin in &location.pins {
        let line = pin.lines[1]
            .or(pin.lines[0])
            .map_or(String::new(), |l| format!(":{l}"));
        let pins = [pin.old.as_deref(), pin.new.as_deref()].map(|text| digest_of(text, address));
        let moved = match pins {
            [Some(old), Some(new)] if old != new => format!(" (@{old} → @{new})"),
            _ => String::new(),
        };
        let mut line = format!(
            "`{}{line}`: {what} of {address}, {}{moved}.",
            location.path, pin.kind
        );
        if let Some(why) = &pin.why {
            line.push_str(&format!(" {}", why.replace('\n', " ")));
        }
        if !pin.callers.is_empty() {
            line.push_str(&format!(" Callers carry {}.", pin.callers.join(", ")));
        }
        said.push(line);
        // § pzp9mfhph.h@m0yz2
        if text_kept && pin.old == pin.new {
            continue;
        }
        // § end pzp9mfhph.h
        let label = format!("{what} of {address}, {}", pin.kind);
        sections.push((&location.path, pin.hunks(location.exists, &label)));
    }
    for body in location.reads.iter().chain(&location.callees) {
        let label = match body.diff.read {
            Some(_) => body.diff.name.clone(),
            None => format!("followed callee {}", body.diff.name),
        };
        if let Some(why) = &body.diff.why {
            said.push(format!("`{}`: {label}. {why}", body.diff.path));
        }
        let hunk = unmarked_hunks(
            body.diff.old.as_deref(),
            body.diff.new.as_deref(),
            body.starts,
            &label,
        );
        sections.push((&body.diff.path, hunk));
    }
    let mut out: String = said.iter().map(|line| format!("* {line}\n")).collect();
    out.push('\n');
    let mut patch = String::new();
    let mut at = 0;
    while at < sections.len() {
        let path = sections[at].0;
        let run: Vec<String> = sections[at..]
            .iter()
            .take_while(|(p, _)| *p == path)
            .map(|(_, hunk)| hunk.clone())
            .collect();
        at += run.len();
        let exists = match path == location.path {
            true => location.exists,
            false => [true, true],
        };
        patch.push_str(&file_patch(path, exists, &run));
    }
    if !patch.is_empty() {
        out.push_str(&fence(&patch));
    }
    out
}

/// Whether `line` is a marker or the end of one.
fn is_marker_line(line: &str) -> bool {
    !crate::marker::markers_in_line(line).is_empty() || crate::marker::end_in_line(line).is_some()
}

/// One hunk of `old` against `new` with the marker and end lines left out: those that open or
/// close it are dropped and an inner one reads as an empty line, so every line keeps its
/// number and a re-pin moves none. An inner one only one side writes, with no other there to
/// pair as a re-pin, is dropped too, since an empty line would read as a change.
fn unmarked_hunks(old: Option<&str>, new: Option<&str>, starts: [usize; 2], label: &str) -> String {
    // § pzp9mfhph@nv9fj
    let split = |text: Option<&str>| -> Vec<String> {
        text.map_or_else(Vec::new, |t| t.lines().map(str::to_string).collect())
    };
    let ops = super::aligned_lines(&split(old), &split(new));
    let mut at = starts;
    let mut run_at = None;
    let mut run: [String; 2] = Default::default();
    let mut pending: Vec<[bool; 2]> = Vec::new();
    for op in &ops {
        let (sign, line) = op.split_at(1);
        let sides = match sign {
            "-" => [true, false],
            "+" => [false, true],
            _ => [true, true],
        };
        if is_marker_line(line) {
            if run_at.is_some() {
                pending.push(sides);
            }
        } else {
            run_at.get_or_insert(at);
            let count = |want: [bool; 2]| pending.iter().filter(|s| **s == want).count();
            let both = count([true, true]) + count([true, false]).min(count([false, true]));
            pending.clear();
            for side in [0, 1] {
                run[side].push_str(&"\n".repeat(both));
            }
            for side in [0, 1] {
                if sides[side] {
                    run[side].push_str(line);
                    run[side].push('\n');
                }
            }
        }
        for side in [0, 1] {
            if sides[side] && at[side] > 0 {
                at[side] += 1;
            }
        }
    }
    match run_at {
        Some(run_at) => hunk(&run[0], &run[1], run_at, label),
        None => String::new(),
    }
}

/// The digest of the marker of `address` in `text`, as written.
fn digest_of(text: Option<&str>, address: &str) -> Option<String> {
    text?
        .lines()
        .flat_map(crate::marker::markers_in_line)
        .find(|marker| marker.display() == address)
        .and_then(|marker| marker.digest)
}

fn quote_lines(text: &str) -> String {
    let mut out = String::new();
    for line in text.lines() {
        match line.is_empty() {
            true => out.push_str(">\n"),
            false => out.push_str(&format!("> {line}\n")),
        }
    }
    out.push('\n');
    out
}

/// A git-style patch of `path` holding `hunks`, so delta names the file and paints its language.
pub(super) fn file_patch(path: &str, exists: [bool; 2], hunks: &[String]) -> String {
    let side = |at: usize, name: &str| match exists[at] {
        true => format!("{name}/{path}"),
        false => "/dev/null".to_string(),
    };
    let mut out = format!(
        "diff --git a/{path} b/{path}\n--- {}\n+++ {}\n",
        side(0, "a"),
        side(1, "b")
    );
    for hunk in hunks {
        out.push_str(hunk);
    }
    out
}

fn hunk_of(old: Option<&str>, new: Option<&str>, starts: [usize; 2], label: &str) -> String {
    hunk(old.unwrap_or(""), new.unwrap_or(""), starts, label)
}

/// One hunk of `old` against `new`, each side numbered from its `starts` line, labelled.
pub(super) fn hunk(old: &str, new: &str, starts: [usize; 2], label: &str) -> String {
    let split = |text: &str| -> Vec<String> {
        match text.is_empty() {
            true => Vec::new(),
            false => text.lines().map(str::to_string).collect(),
        }
    };
    let (old, new) = (split(old), split(new));
    let ops = super::aligned_lines(&old, &new);
    let count = |side: char| {
        ops.iter()
            .filter(|l| l.starts_with(side) || l.starts_with(' '))
            .count()
    };
    let (o, n) = (count('-'), count('+'));
    // A side with no line stands where the other side opens, as git writes it, and a side
    // without the file at 0.
    let start = |side: usize, len: usize| match len {
        _ if starts[side] == 0 => 0,
        0 => starts[1 - side].saturating_sub(1),
        _ => starts[side],
    };
    let mut out = format!("@@ -{},{o} +{},{n} @@ {label}\n", start(0, o), start(1, n));
    for line in ops {
        out.push_str(&line);
        out.push('\n');
    }
    out
}

/// The block attributes as one patch per `AGENTS.md`, a line per attribute.
fn block_diff(rows: &[BlockRow]) -> String {
    // § pzp9mfhph@mm5wt
    let mut paths: Vec<&str> = rows.iter().map(|row| row.path.as_str()).collect();
    paths.dedup();
    let mut out = String::new();
    for path in paths {
        let side = |value: fn(&BlockRow) -> &Option<String>| -> String {
            rows.iter()
                .filter(|row| row.path == path)
                .filter_map(|row| {
                    value(row)
                        .as_ref()
                        .map(|v| format!("{}=\"{v}\"\n", row.attr))
                })
                .collect()
        };
        let (old, new) = (side(|row| &row.old), side(|row| &row.new));
        out.push_str(&file_patch(
            path,
            [true, true],
            &[hunk(&old, &new, [1, 1], "block")],
        ));
    }
    out
}

/// `body` in a `diff` fence longer than any backtick run it holds.
pub(super) fn fence(body: &str) -> String {
    let longest = body
        .lines()
        .map(|line| line.trim_start().chars().take_while(|&c| c == '`').count())
        .max()
        .unwrap_or(0);
    let ticks = "`".repeat(longest.max(2) + 1);
    format!("{ticks}diff\n{body}{ticks}\n\n")
}

/// A JSON value, written with its keys in the order given and a list of scalars on one line.
enum J {
    Null,
    Bool(bool),
    Num(usize),
    Str(String),
    Arr(Vec<J>),
    Obj(Vec<(&'static str, J)>),
}

impl J {
    fn maybe(value: Option<&str>) -> J {
        value.map_or(J::Null, |v| J::Str(v.to_string()))
    }

    fn sides(value: &[Option<String>; 2]) -> J {
        J::Obj(vec![
            ("old", J::maybe(value[0].as_deref())),
            ("new", J::maybe(value[1].as_deref())),
        ])
    }

    fn is_scalar(&self) -> bool {
        !matches!(self, J::Arr(_) | J::Obj(_))
    }

    fn render(&self, indent: usize, out: &mut String) {
        let pad = "  ".repeat(indent + 1);
        match self {
            J::Null => out.push_str("null"),
            J::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            J::Num(n) => out.push_str(&n.to_string()),
            J::Str(s) => out.push_str(&json_escape(s)),
            J::Arr(items) if items.iter().all(J::is_scalar) => {
                let items: Vec<String> = items
                    .iter()
                    .map(|item| {
                        let mut one = String::new();
                        item.render(indent, &mut one);
                        one
                    })
                    .collect();
                out.push_str(&format!("[{}]", items.join(", ")));
            }
            J::Arr(items) => {
                out.push_str("[\n");
                for (i, item) in items.iter().enumerate() {
                    out.push_str(&pad);
                    item.render(indent + 1, out);
                    out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
                }
                out.push_str(&"  ".repeat(indent));
                out.push(']');
            }
            J::Obj(fields) => {
                out.push_str("{\n");
                for (i, (key, value)) in fields.iter().enumerate() {
                    out.push_str(&format!("{pad}{}: ", json_escape(key)));
                    value.render(indent + 1, out);
                    out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
                }
                out.push_str(&"  ".repeat(indent));
                out.push('}');
            }
        }
    }
}

/// The review as JSON, the piped default.
pub(super) fn review_json(
    review: &Review,
    declared: &BTreeMap<String, crate::meta::Declared>,
) -> String {
    // § pzp9mfhph@05scj
    // § n4fbh9vd4.d@6agas
    let mut fields = vec![("base", J::Str(review.base.clone()))];
    if review.folded > 0 {
        fields.push(("remint", J::Bool(true)));
        fields.push(("pinned", J::Num(review.folded)));
    }
    // § end n4fbh9vd4.d
    let block = review
        .block
        .iter()
        .map(|row| {
            J::Obj(vec![
                ("path", J::Str(row.path.clone())),
                ("attribute", J::Str(row.attr.to_string())),
                ("old", J::maybe(row.old.as_deref())),
                ("new", J::maybe(row.new.as_deref())),
            ])
        })
        .collect();
    fields.push(("block", J::Arr(block)));
    let laws = review
        .rules
        .iter()
        .map(|rule| {
            let mut law = vec![
                ("id", J::Str(rule.id.clone())),
                ("status", J::Str(rule.status.status_key().to_string())),
                ("note", J::Str(rule.note.clone())),
            ];
            if let Some(was) = &rule.reminted_from {
                law.push(("reminted_from", J::Str(was.clone())));
            }
            if let Some((Some(date), _)) = declared.get(super::local_id(&rule.id)) {
                law.push(("declared_on", J::Str(date.clone())));
            }
            law.push(("check", J::Str(rule.status.status_check(&judged(rule)))));
            law.push(("sentence", J::Obj(part_json(&rule.head))));
            law.push((
                "clauses",
                J::Arr(rule.clauses.iter().map(|c| J::Obj(part_json(c))).collect()),
            ));
            J::Obj(law)
        })
        .collect();
    fields.push(("laws", J::Arr(laws)));
    let ungoverned = review
        .ungoverned
        .iter()
        .map(FileHunks::hunks_json)
        .collect();
    fields.push(("ungoverned", J::Arr(ungoverned)));
    let mut out = String::new();
    J::Obj(fields).render(0, &mut out);
    out.push('\n');
    out
}

fn part_json(part: &Part) -> Vec<(&'static str, J)> {
    let mut out = vec![("address", J::Str(part.address.clone()))];
    if let Some(letter) = &part.letter {
        out.push(("letter", J::Str(letter.clone())));
    }
    out.push(("status", J::maybe(part.status.map(Status::status_key))));
    out.push(("text", J::sides(&part.text)));
    let changes = part
        .changes
        .iter()
        .map(|change| {
            let mut fields = vec![
                ("kind", J::Str(change.kind_name().to_string())),
                ("path", J::Str(change_path(change).to_string())),
                ("address", J::Str(change.address.clone())),
                ("old", J::maybe(change.old_text.as_deref())),
                ("new", J::maybe(change.new_text.as_deref())),
            ];
            if let Some(why) = &change.why {
                fields.push(("why", J::Str(why.clone())));
            }
            J::Obj(fields)
        })
        .collect();
    out.push(("changes", J::Arr(changes)));
    let locations = part
        .locations
        .iter()
        .map(|location| {
            let pins = location
                .pins
                .iter()
                .map(|pin| {
                    let mut fields = vec![
                        ("kind", J::Str(pin.kind.to_string())),
                        (
                            "lines",
                            J::Arr(
                                pin.lines
                                    .iter()
                                    .map(|l| l.map_or(J::Null, J::Num))
                                    .collect(),
                            ),
                        ),
                        ("old", J::maybe(pin.old.as_deref())),
                        ("new", J::maybe(pin.new.as_deref())),
                    ];
                    if let Some(why) = &pin.why {
                        fields.push(("why", J::Str(why.clone())));
                    }
                    if !pin.callers.is_empty() {
                        fields.push((
                            "callers",
                            J::Arr(pin.callers.iter().map(|c| J::Str(c.clone())).collect()),
                        ));
                    }
                    J::Obj(fields)
                })
                .collect();
            let body = |body: &Body| {
                let mut fields = Vec::new();
                if let Some(read) = body.diff.read {
                    fields.push(("read", J::Str(super::read_key(read).to_string())));
                }
                fields.push(("name", J::Str(body.diff.name.clone())));
                fields.push(("path", J::Str(body.diff.path.clone())));
                fields.push(("old", J::maybe(body.diff.old.as_deref())));
                fields.push(("new", J::maybe(body.diff.new.as_deref())));
                if let Some(why) = &body.diff.why {
                    fields.push(("why", J::Str(why.clone())));
                }
                J::Obj(fields)
            };
            J::Obj(vec![
                ("path", J::Str(location.path.clone())),
                ("doc", J::Bool(location.doc)),
                ("pins", J::Arr(pins)),
                ("reads", J::Arr(location.reads.iter().map(body).collect())),
                (
                    "callees",
                    J::Arr(location.callees.iter().map(body).collect()),
                ),
            ])
        })
        .collect();
    out.push(("locations", J::Arr(locations)));
    out
}

/// The JSON of one file under no law.
impl FileHunks {
    fn hunks_json(&self) -> J {
        let hunks = self
            .hunks
            .iter()
            .map(|h| {
                J::Obj(vec![
                    ("old", J::Arr(vec![J::Num(h.old.0), J::Num(h.old.1)])),
                    ("new", J::Arr(vec![J::Num(h.new.0), J::Num(h.new.1)])),
                    (
                        "lines",
                        J::Arr(h.lines.iter().map(|l| J::Str(l.clone())).collect()),
                    ),
                ])
            })
            .collect();
        let mut fields = vec![("path", J::Str(self.path.clone()))];
        if self.old_path.as_ref() != Some(&self.path) {
            fields.push(("old_path", J::maybe(self.old_path.as_deref())));
        }
        fields.push(("added", J::Num(self.added())));
        fields.push(("removed", J::Num(self.removed())));
        fields.push(("binary", J::Bool(self.binary)));
        fields.push(("hunks", J::Arr(hunks)));
        J::Obj(fields)
    }
}

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

    #[test]
    fn a_side_without_the_file_reads_as_dev_null_at_line_zero() {
        let doc = hunk("", "## Title\nBody.", [0, 3], "doc section of x, added");
        let patch = file_patch("docs/guide.md", [false, true], &[doc]);
        assert_eq!(
            patch,
            "diff --git a/docs/guide.md b/docs/guide.md\n--- /dev/null\n+++ b/docs/guide.md\n\
             @@ -0,0 +3,2 @@ doc section of x, added\n+## Title\n+Body.\n"
        );
        let added = hunk("", "fn f() {}", [7, 7], "span of x, added");
        assert!(added.starts_with("@@ -6,0 +7,1 @@"), "{added}");
    }

    #[test]
    fn a_patch_holds_no_marker_and_numbers_each_line_where_it_stands() {
        let old =
            "fn f() {\n  // § c09206qct.a@cnxg2\n  run();\n  // § end c09206qct.a\n  done();\n}\n";
        let new = old.replace("cnxg2", "ghxv4").replace("done", "stop");
        let patch = unmarked_hunks(Some(old), Some(&new), [10, 10], "x");
        assert!(!patch.contains('§'), "{patch}");
        assert_eq!(
            patch,
            "@@ -10,6 +10,6 @@ x\n fn f() {\n \n   run();\n \n-  done();\n+  stop();\n }\n"
        );
        let repinned = old.replace("cnxg2", "ghxv4");
        let patch = unmarked_hunks(Some(old), Some(&repinned), [1, 1], "x");
        assert!(!patch.lines().any(|l| l.starts_with(['-', '+'])), "{patch}");
        assert_eq!(
            digest_of(Some(old), "c09206qct.a").as_deref(),
            Some("cnxg2")
        );
        assert_eq!(digest_of(Some(old), "c09206qct"), None);
    }

    #[test]
    fn a_marker_line_one_side_drops_shows_as_no_line() {
        let old = "fn f() {\n  // § c09206qct@w1wb7\n  run();\n}\n";
        let new = "fn f() {\n  run();\n}\n";
        let patch = unmarked_hunks(Some(old), Some(new), [1, 1], "x");
        assert!(!patch.lines().any(|l| l.starts_with(['-', '+'])), "{patch}");
        assert!(!patch.contains('§'), "{patch}");
    }

    #[test]
    fn code_a_removed_pin_spanned_is_kept_only_when_it_stands_unchanged() {
        let old = "a\nfn f() {\n  // § c09206qct@w1wb7\n  run();\n}\n";
        assert_eq!(
            kept_at(old, (2, 5), "a\nb\nfn f() {\n  run();\n}\n"),
            Some(3)
        );
        assert_eq!(kept_at(old, (2, 5), "a\nfn f() {\n  stop();\n}\n"), None);
        assert_eq!(kept_at(old, (3, 3), "a\n"), None);
    }
}