jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! `read --for-edit` (V2-10): the exact working document W that
//! template/apply derive, exposed for inspection.
//!
//! Selection is frozen on the original source S before settlement:
//! printed IDs and literal/regex searches match S's final logical text,
//! `--changed`/`--by` match S's original revision/comment inventory, and
//! `--context` neighbours are read-only original-S observations. The
//! selected decisions (`accept`/`reject`) and the remaining-revision
//! policy then produce W through the same `settle` path apply uses, so
//! the hashes and readiness a caller sees describe the same basis a plan
//! would be checked against. Readiness is operation- and range-specific
//! evidence about the present document, never a promise about an
//! unwritten rewrite: apply recomputes every constraint.

use std::collections::{HashMap, HashSet};

use serde::Serialize;

use crate::changes::ChangeFilter;
use crate::inspect::{Opened, Piece, project_paragraph, source_sha256};
use crate::namespaces::{MC, W, W14};
use crate::xmllinq::{Dom, NodeId};

use super::origin::{Fate, Origin};
use super::{
    EditError, EditPlan, ExistingRevisions, Loaded, ResolveRevisions, Settled, load_stories,
    settle, v2,
};

/// The working-basis inputs `read --for-edit` shares with template and
/// apply: the same settlement produces the same W.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ForEditRequest {
    /// Printed IDs or closed ranges (`p5`, `p4-p7`, `t0`), resolved on S.
    pub select: Option<String>,
    /// Original story ID, or all (the default).
    pub story: Option<String>,
    /// First N body paragraphs.
    pub head: Option<usize>,
    /// Last N body paragraphs.
    pub tail: Option<usize>,
    /// Literal search on S's final logical text.
    pub find: Option<String>,
    /// Regex search on S's final logical text (conflicts with `find`).
    pub regex: Option<String>,
    /// Case-insensitive search.
    pub ignore_case: bool,
    /// Blocks intersecting a revision or comment of S.
    pub changed: bool,
    /// `--changed` author filter (a handle or full name).
    pub by: Option<String>,
    /// Additional author filters, unioned with by for original marks.
    pub by_any: Vec<String>,
    /// Read-only original-S neighbours around matches.
    pub context: usize,
    /// Primary records per page (default 100); ignored under `all`.
    pub limit: Option<usize>,
    /// Character budget across all emitted text (default 24000); ignored
    /// under `all`.
    pub max_chars: Option<usize>,
    /// Disable presentation limits.
    pub all: bool,
    /// Continuation cursor of an earlier bounded query.
    pub cursor: Option<String>,
    /// Selected revisions to accept in the working view (S ids).
    pub accept: Vec<String>,
    /// Selected revisions to reject in the working view (S ids).
    pub reject: Vec<String>,
    /// Remaining-revision policy; default keep, matching new plans.
    pub existing_revisions: ExistingRevisions,
    /// Readiness for tracked new edits (default) or direct ones.
    pub track: bool,
    /// `edit template` (and other plan surfaces) allow only closed ranges
    /// (proposal §2); `read --for-edit` keeps the open-ended `p17-` /
    /// `-p3` spellings its shipped help documents, transitionally.
    pub closed_ranges_only: bool,
}

impl Default for ForEditRequest {
    fn default() -> Self {
        Self {
            select: None,
            story: None,
            head: None,
            tail: None,
            find: None,
            regex: None,
            ignore_case: false,
            changed: false,
            by: None,
            by_any: Vec::new(),
            context: 0,
            limit: None,
            max_chars: None,
            all: false,
            cursor: None,
            accept: Vec::new(),
            reject: Vec::new(),
            existing_revisions: ExistingRevisions::Keep,
            track: true,
            closed_ranges_only: false,
        }
    }
}

/// The established short/long pair of one entity reference.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TargetPair {
    /// Snapshot-relative short ID (`p12`, `r5`, `c3`).
    pub short_id: String,
    /// Four-field long ID (`document.w:p.w14:paraId.3F2A1B7C`,
    /// `document.w:p.j:short.p12` when the source gives no usable key).
    pub long_id: String,
}

/// One text value with its completeness declared. A truncated value puts
/// its bounded piece in `text_preview` and keeps `text` absent, so a
/// preview can never be copied as a complete rewrite payload.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct TextValue {
    /// The complete exact text; absent when `complete` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Bounded piece of the text when `complete` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_preview: Option<String>,
    /// Whether `text` holds the whole value.
    pub complete: bool,
}

impl TextValue {
    fn complete(text: String) -> Self {
        Self {
            text: Some(text),
            text_preview: None,
            complete: true,
        }
    }

    /// The value bounded to `chars` Unicode scalar positions; a preview
    /// keeps `text` absent so it cannot pose as a complete payload.
    fn bounded(text: &str, chars: usize) -> Self {
        let mut preview: String = text.chars().take(chars).collect();
        // A preview never cuts a word in two: a mid-word cut finishes it.
        if preview.len() < text.len()
            && !preview.ends_with(char::is_whitespace)
            && text[preview.len()..]
                .chars()
                .next()
                .is_some_and(|c| !c.is_whitespace())
        {
            preview.extend(
                text[preview.len()..]
                    .chars()
                    .take_while(|c| !c.is_whitespace()),
            );
        }
        if preview.len() == text.len() {
            return Self::complete(text.to_string());
        }
        Self {
            text: None,
            text_preview: Some(preview),
            complete: false,
        }
    }

    /// Unicode scalar count of the emitted text.
    fn chars(&self) -> usize {
        self.text
            .as_deref()
            .or(self.text_preview.as_deref())
            .map_or(0, |t| t.chars().count())
    }
}

/// The working view of one selected paragraph.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct WorkingText {
    /// Exact logical working text and its completeness.
    #[serde(flatten)]
    pub value: TextValue,
    /// SHA-256 of the complete UTF-8 logical working text, shown even
    /// under a bounded preview (a preview is still not a payload).
    /// Absent when the codec cannot represent the text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before_sha256: Option<String>,
}

/// A known blocker: a range of the working text (zero-based Unicode
/// scalar positions, exclusive end; observations, not an address
/// family) an operation cannot assume editable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Blocker {
    /// `[start, end)` in Unicode scalar positions of the working text;
    /// a zero-length range marks a position.
    pub range: [usize; 2],
    /// `tracked_insertion`, `tracked_deletion`, `move`, `hyperlink`,
    /// `field`, `content_control`, `symbol` or `opaque`.
    pub kind: String,
    /// `conditional` when a selected revision decision can free the
    /// range, `unavailable` when the structure itself blocks edits.
    pub decision: String,
    /// The revision this blocker belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revision: Option<TargetPair>,
    /// Human-readable detail.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// Readiness of one operation family on a paragraph: `available`,
/// `conditional`, `unavailable` or `unknown`. Range operations are
/// available on every range the blockers leave free.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Readiness {
    /// Operation family (`replace`, `insert`, `delete`, `rewrite`,
    /// `insert_paragraph`, `delete_paragraph`, `comment`).
    pub operation: String,
    /// `available`, `conditional`, `unavailable` or `unknown`.
    pub status: String,
    /// Indices into the row's `blockers`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub blockers: Vec<usize>,
    /// Why the status is not `available`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// One original revision mark intersecting the paragraph.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct RevisionRef {
    /// The revision's paired identity.
    pub target: TargetPair,
    /// `insertion`, `deletion`, `move`, `paragraph_mark` or `formatting`.
    pub kind: String,
    /// Revision author.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Range of the working text the revision covers, when it has one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<[usize; 2]>,
    /// Whether the reference is an original-S observation (`"original"`)
    /// or a working-view fact (`"working"`).
    pub basis: String,
}

/// One original comment whose range intersects the paragraph.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct CommentRef {
    /// `c{id}`.
    pub short_id: String,
    /// The comment's long ID (`comments.w:comment.w:id.N`).
    pub long_id: String,
    /// `open` or `done`.
    pub status: String,
    /// Why the reference is partial (`cross_story_range`: the range's
    /// endpoints lie in different stories — malformed input a part-based
    /// format cannot carry — so each endpoint names the comment).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limitation: Option<String>,
}

/// Where a source paragraph went under settlement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Correspondence {
    /// The paragraph kept its exact one-to-one working correspondence.
    OneToOne,
    /// Settlement merged it with its neighbours.
    Merged,
    /// Settlement removed it with its text.
    Removed,
}

/// One selected original paragraph, its working text and readiness.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditRow {
    /// Paired identity in the original source.
    pub target: TargetPair,
    /// `body` or the story stem (`header1`, `footnotes`, ...).
    pub story: String,
    /// Selection filters the paragraph matched (`ids`, `find`, `regex`,
    /// `changed`); empty for the unfiltered default.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub matched_by: Vec<String>,
    /// Original-S final logical text (an immutable observation).
    pub original: TextValue,
    /// SHA-256 of the complete original text, when it is representable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_sha256: Option<String>,
    /// Working text and `before_sha256`; absent when settlement merged or
    /// removed the paragraph.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working: Option<WorkingText>,
    /// Original-to-working correspondence.
    pub correspondence: Correspondence,
    /// The working paragraph a merged paragraph's text went to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merged_into: Option<String>,
    /// Whether the exact text codec represents the working text.
    pub text_codec: String,
    /// Original revision marks intersecting the paragraph.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub revisions: Vec<RevisionRef>,
    /// Original comments whose ranges intersect the paragraph.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<CommentRef>,
    /// Ranges no operation may assume editable.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub blockers: Vec<Blocker>,
    /// Per-operation readiness evidence.
    pub readiness: Vec<Readiness>,
    /// Operation families the scan does not assess.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unassessed_operations: Vec<String>,
}

/// A read-only original-S observation; never a rewrite row.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct SourceContextRow {
    /// `paragraph` (or `opaque` for unrepresented regions).
    pub kind: String,
    /// Paired identity in the original source.
    pub target: TargetPair,
    /// Original-S final logical text.
    #[serde(flatten)]
    pub value: TextValue,
    /// `final`, the view `value` was projected under: inserted text in,
    /// deleted text out. The revision marks below say which parts of the
    /// text are pending decisions.
    pub text_view: String,
    /// Whether the exact text codec represents this paragraph
    /// (`supported` / `unsupported`): context is never editable, but an
    /// unrepresentable neighbour must not look like one.
    pub text_codec: String,
    /// Constructs present but not represented in `value` (`sym`,
    /// `field`, `revision`, `drawing`, ...).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub limitations: Vec<String>,
    /// Original revision marks the neighbour holds (`basis` is always
    /// `original`): a pending insertion's text or an emptied paragraph
    /// is labelled, not silent.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub revisions: Vec<RevisionRef>,
    /// Why the record is context (`context`, `unsupported_text_codec`,
    /// `merged`, `removed`).
    pub reason_codes: Vec<String>,
}

/// What the query returned and what it left out.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditCoverage {
    /// Whether the whole frozen selection was returned, complete.
    pub selection_complete: bool,
    /// Frozen selection size.
    pub paragraphs_selected: usize,
    /// Rows returned this page.
    pub paragraphs_returned: usize,
    /// Read-only context records returned this page.
    pub context_paragraphs: usize,
    /// Whether presentation limits cut anything.
    pub truncated: bool,
    /// Known omissions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub omissions: Vec<String>,
}

/// The frozen basis the result and any cursor are bound to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditBasis {
    /// `final`, the only working text view.
    pub text_view: String,
    /// [`v2::TEXT_CODEC_VERSION`].
    pub text_codec_version: u32,
    /// `on` or `off`.
    pub track: String,
    /// The remaining-revision policy.
    pub existing_revisions: String,
    /// Selected revision decisions, sorted (decisions are a set).
    pub accept: Vec<String>,
    /// Selected revision decisions, sorted (decisions are a set).
    pub reject: Vec<String>,
    /// SHA-256 of the bytes W was derived from (S after settlement).
    pub working_sha256: String,
    /// SHA-256 of every input the basis binds (source digest, frozen
    /// selection, filters, codec, policy, decisions); cursor validity.
    pub digest: String,
}

/// What settlement did before the working view was read.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEditSettled {
    /// Selected decisions or the policy rewrote the document.
    pub changed: bool,
    /// Selected revisions accepted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub accepted: Vec<String>,
    /// Selected revisions rejected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rejected: Vec<String>,
}

/// The `read --for-edit` result document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ForEdit {
    /// `jubarte-read-for-edit-v1`.
    pub schema: String,
    /// The bound original source digest.
    pub source_sha256: String,
    /// The working basis the rows describe.
    pub basis: ForEditBasis,
    /// Settlement facts.
    pub settled: ForEditSettled,
    /// The frozen selection, in document order.
    pub paragraphs: Vec<ForEditRow>,
    /// Original comments with no anchor in any story: marks too,
    /// labelled at document level instead of silently dropped.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unanchored_comments: Vec<CommentRef>,
    /// Read-only original-S observations (`--context` neighbours).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_context: Vec<SourceContextRow>,
    /// The original source's comment inventory, so consumers that build on
    /// the same view (template generation) need not reparse the package.
    /// Not part of the wire document.
    #[serde(skip)]
    pub comments: Vec<crate::comments::CommentRecord>,
    /// Completeness and omissions.
    pub coverage: ForEditCoverage,
    /// Continuation token; `null` when the selection is exhausted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    /// The input's validity findings, as `read --json` carries them in
    /// `summary.input_validity`: set only by the CLI, which read the file
    /// (#1340); absent from the library's result.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_validity: Option<crate::validate::InputValidity>,
}

fn existing_revisions_name(policy: ExistingRevisions) -> &'static str {
    match policy {
        ExistingRevisions::Keep => "keep",
        ExistingRevisions::Accept => "accept",
        ExistingRevisions::Reject => "reject",
        ExistingRevisions::Refuse => "refuse",
    }
}

/// Everything a cursor binds: the source digest, the frozen selection,
/// the filters that produced it, the codec, and the working policy.
fn basis_digest(source_digest: &str, request: &ForEditRequest, selection: &Selection) -> String {
    // Decisions are a set: order and repetition are no part of the basis.
    let mut accept = request.accept.clone();
    let mut reject = request.reject.clone();
    accept.sort();
    accept.dedup();
    reject.sort();
    reject.dedup();
    let basis = serde_json::json!({
        "v": 1,
        "source_sha256": source_digest,
        "codec": v2::TEXT_CODEC_VERSION,
        "view": "final",
        "track": request.track,
        "existing_revisions": existing_revisions_name(request.existing_revisions),
        "accept": accept,
        "reject": reject,
        "select": request.select,
        "story": request.story,
        "head": request.head,
        "tail": request.tail,
        "find": request.find,
        "regex": request.regex,
        "ignore_case": request.ignore_case,
        "changed": request.changed,
        "by": request.by,
        "by_any": request.by_any,
        "context": request.context,
        "frozen": selection.selected,
    });
    source_sha256(
        serde_json::to_string(&basis)
            .expect("basis serializes")
            .as_bytes(),
    )
}

/// The cursor token: a version, the bound basis digest and the next
/// index into the frozen selection, base64url-encoded.
fn cursor_token(basis: &str, offset: usize) -> String {
    use base64::Engine;
    let json = serde_json::json!({"v": 1, "basis": basis, "offset": offset});
    base64::engine::general_purpose::URL_SAFE_NO_PAD
        .encode(serde_json::to_string(&json).expect("cursor serializes"))
}

/// The offset a continuation resumes at; its bound basis must still hold.
fn cursor_offset(token: &str, basis: &str) -> Result<usize, EditError> {
    use base64::Engine;
    let decode = || -> Option<serde_json::Value> {
        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(token)
            .ok()?;
        serde_json::from_slice(&bytes).ok()
    };
    let cursor = decode().ok_or_else(|| {
        super::err(
            "USAGE",
            None,
            "the cursor is not a read --for-edit continuation token",
        )
    })?;
    if cursor["v"] != 1 || !cursor["offset"].is_u64() || !cursor["basis"].is_string() {
        return Err(super::err(
            "USAGE",
            None,
            "the cursor is not a read --for-edit continuation token",
        ));
    }
    if cursor["basis"].as_str() != Some(basis) {
        return Err(super::err(
            "CURSOR_BASIS_CHANGED",
            None,
            "the cursor is bound to another source, selection, filter or working basis; start a new query",
        ));
    }
    Ok(cursor["offset"].as_u64().unwrap_or(0) as usize)
}

/// The frozen selection: the paragraphs of S the query names, in
/// document order, and which filters named each of them.
struct Selection {
    /// Global S paragraph indexes, in document order.
    selected: Vec<usize>,
    /// The filter names each selected paragraph matched.
    matched_by: HashMap<usize, Vec<String>>,
    /// Neighbour count for `--context` rows.
    context: usize,
}

impl Selection {
    fn build(
        request: &ForEditRequest,
        s_opened: &Opened,
        s_loaded: &Loaded,
        source: &[u8],
    ) -> Result<Self, EditError> {
        let total = s_loaded.paragraph_nodes.len();
        let mut filters: Vec<(&'static str, HashSet<usize>)> = Vec::new();

        if let Some(story) = request.story.as_deref().filter(|s| *s != "all") {
            let si = s_loaded
                .stories
                .iter()
                .position(|s| s.id == story)
                .ok_or_else(|| {
                    super::err("USAGE", None, format!("unknown source story {story}"))
                })?;
            filters.push((
                "story",
                s_loaded
                    .paragraph_story
                    .iter()
                    .enumerate()
                    .filter(|(_, pair)| pair.0 == si)
                    .map(|(g, _)| g)
                    .collect(),
            ));
        }
        if let Some(spec) = &request.select {
            filters.push((
                "ids",
                id_selection(spec, source, request.closed_ranges_only)?,
            ));
        }
        if let Some(head) = request.head {
            filters.push((
                "ids",
                s_loaded
                    .paragraph_story
                    .iter()
                    .enumerate()
                    .filter(|(_, pair)| pair.0 == 0 && pair.1 < head)
                    .map(|(g, _)| g)
                    .collect(),
            ));
        }
        if let Some(tail) = request.tail {
            let body = s_loaded
                .paragraph_story
                .iter()
                .filter(|pair| pair.0 == 0)
                .count();
            let from = body.saturating_sub(tail);
            filters.push((
                "ids",
                s_loaded
                    .paragraph_story
                    .iter()
                    .enumerate()
                    .filter(|(_, pair)| pair.0 == 0 && pair.1 >= from)
                    .map(|(g, _)| g)
                    .collect(),
            ));
        }
        if request.find.is_some() || request.regex.is_some() {
            filters.push((
                if request.find.is_some() {
                    "find"
                } else {
                    "regex"
                },
                text_selection(request, &s_opened.dom, &s_loaded.paragraph_nodes)?,
            ));
        }
        if request.changed {
            filters.push(("changed", changed_selection(request, s_loaded, source)?));
        }

        let mut matched_by: HashMap<usize, Vec<String>> = HashMap::new();
        let selected: Vec<usize> = if filters.is_empty() {
            (0..total).collect()
        } else {
            let mut it = filters.iter();
            let mut keep: HashSet<usize> = it.next().map_or_else(HashSet::new, |(_, s)| s.clone());
            for (_, set) in it {
                keep.retain(|g| set.contains(g));
            }
            for (name, set) in &filters {
                for &g in &keep {
                    if set.contains(&g) {
                        matched_by.entry(g).or_default().push((*name).to_string());
                    }
                }
            }
            (0..total).filter(|g| keep.contains(g)).collect()
        };
        for names in matched_by.values_mut() {
            names.dedup();
        }
        Ok(Self {
            selected,
            matched_by,
            context: request.context,
        })
    }
}

/// The paragraphs `spec` names: `pN`/`pN-pM` closed ranges and `tN`
/// whole tables, against the body's own numbering on S; the transitional
/// open-ended `pN-` / `-pN` spellings parse unless the caller requires
/// closed ranges.
fn id_selection(spec: &str, source: &[u8], closed_only: bool) -> Result<HashSet<usize>, EditError> {
    super::v2_apply::SourceModel::new(source)?.selected_paragraphs(spec, !closed_only)
}

/// Body paragraph indexes matching the same original final logical text as
/// `read --for-edit`, in document order. The Markdown view's `-p` selectors
/// cannot address other stories yet.
///
/// # Errors
///
/// The package cannot be opened, or the regular expression does not compile.
pub fn matching_body_paragraphs(
    source: &[u8],
    find: Option<&str>,
    regex: Option<&str>,
    ignore_case: bool,
) -> Result<Vec<usize>, EditError> {
    let opened = Opened::open(source).map_err(super::open_error)?;
    let paragraphs = crate::inspect::body_paragraph_nodes(&opened.dom, opened.body);
    let request = ForEditRequest {
        find: find.map(str::to_owned),
        regex: regex.map(str::to_owned),
        ignore_case,
        ..ForEditRequest::default()
    };
    let matches = text_selection(&request, &opened.dom, &paragraphs)?;
    Ok((0..paragraphs.len())
        .filter(|p| matches.contains(p))
        .collect())
}

/// The largest program a `--regex` pattern may compile into: 10 MiB, the
/// regex crate's own default, pinned here so a dependency upgrade cannot
/// loosen it.
const REGEX_SIZE_LIMIT: usize = 10 * (1 << 20);

/// The paragraphs whose original final logical text the search matches.
fn text_selection(
    request: &ForEditRequest,
    dom: &Dom,
    paragraph_nodes: &[NodeId],
) -> Result<HashSet<usize>, EditError> {
    let matcher: Box<dyn Fn(&str) -> bool> = if let Some(find) = &request.find {
        let needle = if request.ignore_case {
            find.to_lowercase()
        } else {
            find.clone()
        };
        let ignore_case = request.ignore_case;
        Box::new(move |text: &str| {
            if ignore_case {
                text.to_lowercase().contains(&needle)
            } else {
                text.contains(&needle)
            }
        })
    } else {
        let pattern = request.regex.as_deref().unwrap_or("");
        let pattern = if request.ignore_case {
            format!("(?i){pattern}")
        } else {
            pattern.to_string()
        };
        // The pattern can come from an untrusted caller (WASM, Python, an
        // agent). The regex crate matches in linear time, so the risk is
        // a short pattern that compiles into a huge program
        // (`a{1000}{1000}`). The size limit refuses that; a cap on the
        // pattern's length would not, and would refuse long alternations
        // of defined terms.
        let compiled = regex::RegexBuilder::new(&pattern)
            .size_limit(REGEX_SIZE_LIMIT)
            .build()
            .map_err(|e| super::err("USAGE", None, format!("--regex does not compile: {e}")))?;
        Box::new(move |text: &str| compiled.is_match(text))
    };
    Ok(paragraph_nodes
        .iter()
        .enumerate()
        .filter(|(_, p)| matcher(&project_paragraph(dom, **p).text))
        .map(|(g, _)| g)
        .collect())
}

/// The paragraphs an original revision or comment intersects; `--by`
/// keeps only marks of that author.
fn changed_selection(
    request: &ForEditRequest,
    s_loaded: &Loaded,
    source: &[u8],
) -> Result<HashSet<usize>, EditError> {
    let story_index: HashMap<String, usize> = s_loaded
        .stories
        .iter()
        .enumerate()
        .map(|(i, s)| (s.id.clone(), i))
        .collect();
    let place = |id: Option<&String>| -> Option<(usize, usize)> {
        let (story, local) = crate::ids::paragraph_place(id?)?;
        Some((*story_index.get(&story)?, local))
    };
    let global = |at: (usize, usize)| -> Option<usize> {
        s_loaded.paragraph_story.iter().position(|&pair| pair == at)
    };
    // `--by` matches an author exactly, or a comment's explicit
    // `w:initials` exactly; it never derives a handle from a name.
    let authors: Vec<&str> = request
        .by
        .iter()
        .chain(&request.by_any)
        .map(|a| {
            let a = a.trim();
            a.strip_prefix('@').unwrap_or(a)
        })
        .collect();
    let by = |name: Option<&str>, initials: Option<&str>| -> bool {
        if authors.is_empty() {
            return true;
        }
        authors
            .iter()
            .any(|want| name.is_some_and(|a| a == *want) || initials.is_some_and(|i| i == *want))
    };
    let mut out = HashSet::new();
    let changes = crate::changes::list_changes(source)
        .map_err(|e| super::err("INVALID_DOCUMENT", None, e.to_string()))?;
    for change in &changes {
        if !by(change.author.as_deref(), None) {
            continue;
        }
        if let Some(g) = place(change.paragraph.as_ref()).and_then(global) {
            out.insert(g);
        }
    }
    let comments = crate::comments::list_comments(source)
        .map_err(|e| super::err(e.code(), None, e.to_string()))?;
    for comment in &comments {
        if !by(Some(&comment.author), comment.initials.as_deref()) {
            continue;
        }
        for at in comment_paragraphs(comment, s_loaded).0 {
            if let Some(g) = global(at) {
                out.insert(g);
            }
        }
    }
    Ok(out)
}

/// The `(story, local)` paragraphs a comment's range covers: min to max
/// of its endpoints inside one story, and each endpoint separately when
/// a malformed range crosses stories (OOXML cannot carry one, so the
/// comment is attached where its markers are instead of dropped).
fn comment_paragraphs(
    comment: &crate::comments::CommentRecord,
    s_loaded: &Loaded,
) -> (Vec<(usize, usize)>, bool) {
    let story_index: HashMap<&str, usize> = s_loaded
        .stories
        .iter()
        .enumerate()
        .map(|(i, s)| (s.id.as_str(), i))
        .collect();
    let place = |id: Option<&String>| -> Option<(usize, usize)> {
        let (story, local) = crate::ids::paragraph_place(id?)?;
        Some((*story_index.get(story.as_str())?, local))
    };
    let Some(first) = place(comment.paragraph.as_ref()) else {
        return (Vec::new(), false);
    };
    match comment.last_paragraph.as_ref() {
        None => (vec![first], false),
        Some(_) => match place(comment.last_paragraph.as_ref()) {
            None => (vec![first], true),
            Some(l) if l.0 == first.0 => {
                let (lo, hi) = (first.1.min(l.1), first.1.max(l.1));
                ((lo..=hi).map(|local| (first.0, local)).collect(), false)
            }
            Some(l) => (vec![first, l], true),
        },
    }
}

/// The comment reference of `comment`.
fn comment_ref(comment: &crate::comments::CommentRecord) -> CommentRef {
    CommentRef {
        short_id: format!("c{}", comment.id),
        long_id: format!("comments.w:comment.w:id.{}", comment.id),
        status: if comment.done {
            "done".to_string()
        } else {
            "open".to_string()
        },
        limitation: None,
    }
}

/// The comments intersecting each global S paragraph index, and the
/// comments no paragraph holds (no anchor in any story).
fn comments_by_paragraph(
    comments: &[crate::comments::CommentRecord],
    s_loaded: &Loaded,
) -> (HashMap<usize, Vec<CommentRef>>, Vec<CommentRef>) {
    let global = |at: (usize, usize)| s_loaded.paragraph_story.iter().position(|&p| p == at);
    let mut out: HashMap<usize, Vec<CommentRef>> = HashMap::new();
    let mut unanchored = Vec::new();
    for comment in comments {
        let (paragraphs, cross_story) = comment_paragraphs(comment, s_loaded);
        if paragraphs.is_empty() {
            unanchored.push(comment_ref(comment));
            continue;
        }
        let mut reference = comment_ref(comment);
        if cross_story {
            reference.limitation = Some("cross_story_range".to_string());
        }
        for at in paragraphs {
            if let Some(g) = global(at) {
                out.entry(g).or_default().push(reference.clone());
            }
        }
    }
    (out, unanchored)
}

/// Per-story usable native `w14:paraId` keys of S, for the long IDs:
/// a value is a key only when lexical (8 hex digits), in Word's range
/// (`1..=0x7FFFFFFF`) and unique in its part.
struct NativeKeys {
    /// Count of each paraId value per story index.
    counts: Vec<HashMap<u32, usize>>,
}

impl NativeKeys {
    fn collect(dom: &Dom, stories: &[super::StoryPart]) -> Self {
        let counts = stories
            .iter()
            .map(|story| {
                let mut counts: HashMap<u32, usize> = HashMap::new();
                for p in dom.descendants(story.root, Some(&W::p())) {
                    if let Some(value) = native_para_id(dom, p) {
                        *counts.entry(value).or_default() += 1;
                    }
                }
                counts
            })
            .collect();
        Self { counts }
    }

    /// The pair `paragraph` gets: its paraId when it is a usable native
    /// key, else the `j:short` long form of its short ID.
    fn pair(
        &self,
        dom: &Dom,
        story: usize,
        part: &str,
        short_id: &str,
        paragraph: NodeId,
    ) -> TargetPair {
        let stem = crate::ids::part_story(part);
        let key = native_para_id(dom, paragraph)
            .filter(|value| self.counts[story].get(value) == Some(&1));
        let long_id = match key.and_then(|_| {
            dom.attribute(paragraph, &W14::name("paraId"))
                .map(str::to_string)
        }) {
            Some(lexical) => format!("{stem}.w:p.w14:paraId.{lexical}"),
            None => format!("{stem}.w:p.j:short.{short_id}"),
        };
        TargetPair {
            short_id: short_id.to_string(),
            long_id,
        }
    }
}

/// The `w14:paraId` of `paragraph` when it is a key Word could have
/// written, under the shared native-key policy: exactly eight ASCII hex
/// digits in `1..=0x7FFFFFFF`.
fn native_para_id(dom: &Dom, paragraph: NodeId) -> Option<u32> {
    super::native_keys::para_id(dom.attribute(paragraph, &W14::name("paraId"))?)
}

/// The long ID of the revision element `el` (a `w:ins`, `w:del`,
/// `w:moveFrom` or `w:moveTo`): its native `w:id` when usable, else the
/// `j:short` form of its printed short ID.
pub(super) fn revision_pair(dom: &Dom, el: NodeId, story: &str, part: &str) -> TargetPair {
    let local = dom
        .name(el)
        .map(|n| n.local_name().to_string())
        .unwrap_or_default();
    let wid = dom.attribute(el, &W::id()).unwrap_or_default();
    let short = crate::ids::ChangeId::new(story, wid).short();
    let stem = crate::ids::part_story(part);
    let usable = super::native_keys::revision_id(wid).is_some();
    let long_id = if usable {
        format!("{stem}.w:{local}.w:id.{}", escape_value(wid))
    } else {
        format!("{stem}.w:{local}.j:short.{short}")
    };
    TargetPair {
        short_id: short,
        long_id,
    }
}

/// The VALUE escaping of the long-ID contract: ASCII letters, digits,
/// dot, underscore and colon stay literal; every other UTF-8 byte is a
/// hyphen and two uppercase hex digits.
fn escape_value(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for &b in text.as_bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':') {
            out.push(char::from(b));
        } else {
            out.push_str(&format!("-{b:02X}"));
        }
    }
    out
}

/// The element a projection segment's text comes from.
fn piece_element(piece: &Piece) -> NodeId {
    match piece {
        Piece::Text { t, .. } => *t,
        Piece::Glyph { element, .. } => *element,
    }
}

/// What an opaque segment sits inside, in order of strictness: a
/// revision first (a decision frees it), then the structure that holds
/// the text (no edit kind may cross it).
fn classify(
    dom: &Dom,
    run: NodeId,
    paragraph: NodeId,
    story: &str,
    part: &str,
) -> (String, String, Option<TargetPair>, Option<String>) {
    for &node in &dom.ancestors(run, None) {
        if node == paragraph {
            break;
        }
        let Some(name) = dom.name(node) else {
            continue;
        };
        if name.namespace_name() == MC::URI {
            return (
                "opaque".to_string(),
                "unavailable".to_string(),
                None,
                Some("alternate content".to_string()),
            );
        }
        if name.namespace_name() != W::URI {
            continue;
        }
        match name.local_name() {
            "ins" | "moveTo" => {
                let kind = if name.local_name() == "ins" {
                    "tracked_insertion"
                } else {
                    "move"
                };
                let revision = revision_pair(dom, node, story, part);
                let author = dom.attribute(node, &W::author());
                return (
                    kind.to_string(),
                    "conditional".to_string(),
                    Some(revision),
                    author.map(|a| format!("a tracked change by {a:?}; a decision frees it")),
                );
            }
            "hyperlink" => {
                return (
                    "hyperlink".to_string(),
                    "unavailable".to_string(),
                    None,
                    Some("edit beside it or comment on it".to_string()),
                );
            }
            "fldSimple" => {
                return (
                    "field".to_string(),
                    "unavailable".to_string(),
                    None,
                    Some("the result of a field".to_string()),
                );
            }
            "sdt" => {
                return (
                    "content_control".to_string(),
                    "unavailable".to_string(),
                    None,
                    Some("a content control; fill it or comment on it".to_string()),
                );
            }
            "smartTag" | "customXml" | "dir" | "bdo" | "del" | "moveFrom" => {
                return (
                    "opaque".to_string(),
                    "unavailable".to_string(),
                    None,
                    Some(format!("inside w:{}", name.local_name())),
                );
            }
            _ => {}
        }
    }
    (
        "field".to_string(),
        "unavailable".to_string(),
        None,
        Some("the result of a field".to_string()),
    )
}

/// Byte offset to Unicode scalar position in `text`.
fn char_pos(text: &str, byte: usize) -> usize {
    text[..byte].chars().count()
}

/// The blockers, revision references and mark revisions of a working
/// paragraph, from its projection and XML.
fn obstacles(
    dom: &Dom,
    paragraph: NodeId,
    story: &str,
    part: &str,
) -> (Vec<Blocker>, Vec<RevisionRef>, Vec<RevisionRef>) {
    let projection = project_paragraph(dom, paragraph);
    let text = projection.text.as_str();
    let order: HashMap<NodeId, usize> = dom
        .descendants(paragraph, None)
        .into_iter()
        .enumerate()
        .map(|(i, n)| (n, i))
        .collect();

    let mut blockers: Vec<Blocker> = Vec::new();
    let mut revisions: Vec<RevisionRef> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    let revision = |dom: &Dom,
                    el: NodeId,
                    kind: &str,
                    range: Option<[usize; 2]>,
                    revisions: &mut Vec<RevisionRef>,
                    seen: &mut HashSet<String>| {
        let pair = revision_pair(dom, el, story, part);
        if seen.insert(pair.short_id.clone()) {
            revisions.push(RevisionRef {
                target: pair,
                kind: kind.to_string(),
                author: dom.attribute(el, &W::author()).map(str::to_string),
                range,
                basis: "working".to_string(),
            });
        }
    };

    // Opaque segments, merged per contiguous run of the same cause.
    /// A blocker in formation: its start, kind, decision, revision and detail.
    type Open = (usize, String, String, Option<TargetPair>, Option<String>);
    let mut open: Option<Open> = None;
    let close = |blockers: &mut Vec<Blocker>, open: &mut Option<Open>, end: usize| {
        if let Some((start, kind, decision, rev, detail)) = open.take() {
            blockers.push(Blocker {
                range: [start, end],
                kind,
                decision,
                revision: rev,
                detail,
            });
        }
    };
    for seg in &projection.segments {
        let el = piece_element(&seg.piece);
        // A symbol is never editable even at a direct position.
        if dom.name_is(el, &W::name("sym")) {
            close(&mut blockers, &mut open, char_pos(text, seg.start));
            blockers.push(Blocker {
                range: [char_pos(text, seg.start), char_pos(text, seg.end)],
                kind: "symbol".to_string(),
                decision: "unavailable".to_string(),
                revision: None,
                detail: Some("a symbol run; its font would draw the text".to_string()),
            });
            continue;
        }
        if seg.direct {
            close(&mut blockers, &mut open, char_pos(text, seg.start));
            continue;
        }
        let run = match &seg.piece {
            Piece::Text { run, .. } | Piece::Glyph { run, .. } => *run,
        };
        let (kind, decision, rev, detail) = classify(dom, run, paragraph, story, part);
        if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
            dom.name(a)
                .is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "ins")
        }) {
            revision(
                dom,
                el,
                "insertion",
                Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
                &mut revisions,
                &mut seen,
            );
        }
        if let Some(el) = dom.ancestors(run, None).into_iter().find(|&a| {
            dom.name(a)
                .is_some_and(|n| n.namespace_name() == W::URI && n.local_name() == "moveTo")
        }) {
            revision(
                dom,
                el,
                "move",
                Some([char_pos(text, seg.start), char_pos(text, seg.end)]),
                &mut revisions,
                &mut seen,
            );
        }
        let start = char_pos(text, seg.start);
        let same = matches!(
          &open,
            Some((_, k, d, r, dt)) if *k == kind && *d == decision && *r == rev && *dt == detail
        );
        if !same {
            close(&mut blockers, &mut open, start);
            open = Some((start, kind, decision, rev, detail));
        }
    }
    close(&mut blockers, &mut open, text.chars().count());

    // Zero-width blockers: complex-field markers and deleted content,
    // which project no text of their own.
    for &mark in &projection.field_marks {
        blockers.push(Blocker {
            range: [char_pos(text, mark), char_pos(text, mark)],
            kind: "field".to_string(),
            decision: "unavailable".to_string(),
            revision: None,
            detail: Some("a field marker; edits may not cross it".to_string()),
        });
    }
    for &el in dom.descendants(paragraph, None).iter() {
        let Some(name) = dom.name(el) else {
            continue;
        };
        if name.namespace_name() != W::URI {
            continue;
        }
        let local = name.local_name();
        // Mark revisions live in w:pPr/w:rPr and are listed separately.
        let in_ppr = dom
            .ancestors(el, None)
            .into_iter()
            .take_while(|&a| a != paragraph)
            .any(|a| dom.name_is(a, &W::p_pr()));
        if in_ppr {
            continue;
        }
        if !matches!(
            local,
            "del" | "moveFrom" | "moveFromRangeStart" | "moveFromRangeEnd"
        ) {
            continue;
        }
        let kind = if local == "del" {
            "tracked_deletion"
        } else {
            "move"
        };
        // The projected position right after everything this element
        // still leaves: the start of the first segment beyond its
        // subtree, or the end of the text.
        let order_of = order.get(&el).copied().unwrap_or(usize::MAX);
        let subtree = dom.descendants_and_self(el, None).len();
        let pos = projection
            .segments
            .iter()
            .filter(|seg| {
                order
                    .get(&piece_element(&seg.piece))
                    .is_some_and(|&o| o >= order_of + subtree)
            })
            .map(|seg| seg.start)
            .min()
            .unwrap_or(text.len());
        blockers.push(Blocker {
            range: [char_pos(text, pos), char_pos(text, pos)],
            kind: kind.to_string(),
            decision: "conditional".to_string(),
            revision: Some(revision_pair(dom, el, story, part)),
            detail: Some("a pending deletion; a decision removes it".to_string()),
        });
        revision(dom, el, "deletion", None, &mut revisions, &mut seen);
    }

    // Paragraph-mark and formatting revisions: they carry no text span
    // but gate whole-paragraph operations.
    let mut mark_revisions: Vec<RevisionRef> = Vec::new();
    if let Some(rpr) = dom
        .element(paragraph, &W::p_pr())
        .and_then(|ppr| dom.element(ppr, &W::r_pr()))
    {
        for el in dom.elements(rpr, None) {
            let Some(name) = dom.name(el) else {
                continue;
            };
            if name.namespace_name() != W::URI {
                continue;
            }
            let kind = match name.local_name() {
                "ins" => "paragraph_mark",
                "del" | "moveFrom" | "moveTo" => "paragraph_mark",
                _ => continue,
            };
            let pair = revision_pair(dom, el, story, part);
            mark_revisions.push(RevisionRef {
                target: pair,
                kind: kind.to_string(),
                author: dom.attribute(el, &W::author()).map(str::to_string),
                range: None,
                basis: "working".to_string(),
            });
        }
    }
    // Recorded formatting changes stay visible as references, not blockers.
    for el in dom.descendants(paragraph, Some(&W::r_pr_change())) {
        let pair = revision_pair(dom, el, story, part);
        revisions.push(RevisionRef {
            target: pair,
            kind: "formatting".to_string(),
            author: dom.attribute(el, &W::author()).map(str::to_string),
            range: None,
            basis: "working".to_string(),
        });
    }
    (blockers, revisions, mark_revisions)
}

/// The characters a row emits, for the text budget.
fn text_chars(row: &ForEditRow) -> usize {
    row.original.chars() + row.working.as_ref().map_or(0, |w| w.value.chars())
}

/// Bound a row's text values to `budget` characters, working first.
fn bound_row(row: &mut ForEditRow, budget: usize) {
    if let Some(working) = &mut row.working
        && let Some(text) = working.value.text.take()
    {
        working.value = TextValue::bounded(&text, budget);
    }
    let remaining = budget.saturating_sub(row.working.as_ref().map_or(0, |w| w.value.chars()));
    if let Some(text) = row.original.text.take() {
        row.original = TextValue::bounded(&text, remaining);
    }
}

/// What `make_row` needs of S, W and the frozen selection.
struct RowCtx<'a> {
    selection: &'a Selection,
    fates: &'a [Fate],
    s_opened: &'a Opened,
    s_loaded: &'a Loaded,
    w_opened: &'a Opened,
    w_stories: &'a [super::StoryPart],
    w_nodes: &'a [NodeId],
    w_story: &'a [(usize, usize)],
    native: &'a NativeKeys,
    comments: &'a HashMap<usize, Vec<CommentRef>>,
}

/// Build one row of the result for original paragraph `g`.
fn make_row(g: usize, ctx: &RowCtx<'_>) -> ForEditRow {
    let selection = ctx.selection;
    let fates = ctx.fates;
    let s_opened = ctx.s_opened;
    let s_loaded = ctx.s_loaded;
    let w_opened = ctx.w_opened;
    let w_stories = ctx.w_stories;
    let w_nodes = ctx.w_nodes;
    let w_story = ctx.w_story;
    let native = ctx.native;
    let comments = ctx.comments;
    let (story, local) = s_loaded.paragraph_story[g];
    let story_id = s_loaded.stories[story].id.as_str();
    let part = s_loaded.stories[story].part.as_str();
    let short_id = crate::ids::paragraph_id(story_id, local);
    let s_node = s_loaded.paragraph_nodes[g];
    let original_text = project_paragraph(&s_opened.dom, s_node).text;
    let original_sha256 = v2::logical_text(&s_opened.dom, s_node)
        .ok()
        .map(|text| source_sha256(text.as_bytes()));

    let (correspondence, w_at) = match fates[g] {
        Fate::Kept(post) => (Correspondence::OneToOne, Some(post)),
        Fate::Merged(post) => (Correspondence::Merged, Some(post)),
        Fate::Gone => (Correspondence::Removed, None),
    };
    let merged_into = match fates[g] {
        Fate::Merged(post) => {
            let (story, local) = w_story[post];
            Some(crate::ids::paragraph_id(
                w_stories[story].id.as_str(),
                local,
            ))
        }
        _ => None,
    };

    let mut blockers = Vec::new();
    let mut revisions = Vec::new();
    let mut mark_revisions = Vec::new();
    let mut text_codec = "supported".to_string();
    let mut working = None;
    if let Some(post) = w_at {
        let w_node = w_nodes[post];
        let w_story_id = w_stories[w_story[post].0].id.as_str();
        let w_part = w_stories[w_story[post].0].part.as_str();
        let w_text = project_paragraph(&w_opened.dom, w_node).text;
        let codec = v2::logical_text(&w_opened.dom, w_node);
        let before_sha256 = codec.ok().map(|text| source_sha256(text.as_bytes()));
        if before_sha256.is_none() {
            text_codec = "unsupported".to_string();
        }
        working = Some(WorkingText {
            value: TextValue::complete(w_text),
            before_sha256,
        });
        if matches!(fates[g], Fate::Kept(_)) {
            let (b, r, m) = obstacles(&w_opened.dom, w_node, w_story_id, w_part);
            blockers = b;
            revisions = r;
            mark_revisions = m;
        }
    }
    if !matches!(fates[g], Fate::Kept(_)) {
        // The working paragraph is not this one: its marks are
        // original-S observations.
        let (_, r, m) = obstacles(&s_opened.dom, s_node, story_id, part);
        for mut reference in r.into_iter().chain(m) {
            reference.basis = "original".to_string();
            revisions.push(reference);
        }
    }
    let readiness = readiness(
        fates[g],
        before_sha256_present(&working),
        &blockers,
        &mark_revisions,
    );
    ForEditRow {
        target: native.pair(&s_opened.dom, story, part, &short_id, s_node),
        story: story_id.to_string(),
        matched_by: selection.matched_by.get(&g).cloned().unwrap_or_default(),
        original: TextValue::complete(original_text),
        original_sha256,
        working,
        correspondence,
        merged_into,
        text_codec,
        revisions,
        comments: comments.get(&g).cloned().unwrap_or_default(),
        blockers,
        readiness,
        unassessed_operations: vec![
            "format".to_string(),
            "fill".to_string(),
            "fields".to_string(),
            "merge".to_string(),
        ],
    }
}

fn before_sha256_present(working: &Option<WorkingText>) -> bool {
    working.as_ref().is_some_and(|w| w.before_sha256.is_some())
}

/// The readiness rows of one paragraph: range operations share the
/// blockers; whole-paragraph operations add the mark revisions.
fn readiness(
    fate: Fate,
    representable: bool,
    blockers: &[Blocker],
    mark_revisions: &[RevisionRef],
) -> Vec<Readiness> {
    let all: Vec<usize> = (0..blockers.len()).collect();
    let gone = matches!(fate, Fate::Gone);
    let merged = matches!(fate, Fate::Merged(_));
    let status = |conditional: bool| -> String {
        if gone {
            "unavailable".to_string()
        } else if conditional {
            "conditional".to_string()
        } else {
            "available".to_string()
        }
    };
    let reason = |text: &str| Some(text.to_string());
    let mut rows = Vec::new();
    // A range operation is gated by a blocker that covers text, or by a
    // structural point no edit may cross. A pending deletion's hidden
    // text is no working range: it blocks nothing and stays a `revisions`
    // entry.
    let gated = blockers
        .iter()
        .any(|b| b.range[0] < b.range[1] || b.decision == "unavailable");
    for operation in ["replace", "insert", "delete"] {
        rows.push(Readiness {
            operation: operation.to_string(),
            status: if gone || merged {
                "unavailable".to_string()
            } else {
                status(gated)
            },
            blockers: all.clone(),
            reason: (gone || merged).then(|| {
                if gone {
                    "the paragraph is gone once revisions settle".to_string()
                } else {
                    "the paragraph merged with its neighbours; name the settled paragraph"
                        .to_string()
                }
            }),
        });
    }
    rows.push(Readiness {
        operation: "rewrite".to_string(),
        status: if gone || merged || !representable {
            "unavailable".to_string()
        } else {
            status(!blockers.is_empty() || !mark_revisions.is_empty())
        },
        blockers: all.clone(),
        reason: if gone {
            reason("the paragraph is gone once revisions settle")
        } else if merged {
            reason("a rewrite needs exact one-to-one working correspondence")
        } else if !representable {
            reason("the exact text codec does not represent this paragraph")
        } else if !blockers.is_empty() || !mark_revisions.is_empty() {
            reason("desired text must not change the blocked ranges")
        } else {
            None
        },
    });
    rows.push(Readiness {
        operation: "insert_paragraph".to_string(),
        status: if gone || merged {
            "unavailable".to_string()
        } else {
            status(!blockers.is_empty() || !mark_revisions.is_empty())
        },
        blockers: all.clone(),
        reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
    });
    rows.push(Readiness {
        operation: "delete_paragraph".to_string(),
        status: if gone || merged {
            "unavailable".to_string()
        } else {
            status(!blockers.is_empty() || !mark_revisions.is_empty())
        },
        blockers: all.clone(),
        reason: if gone {
            reason("the paragraph is gone once revisions settle")
        } else if merged {
            reason("the paragraph merged with its neighbours; name the settled paragraph")
        } else if !blockers.is_empty() || !mark_revisions.is_empty() {
            reason("the paragraph still holds revisions; a decision frees it")
        } else {
            None
        },
    });
    rows.push(Readiness {
        operation: "comment".to_string(),
        status: status(false),
        blockers: Vec::new(),
        reason: gone.then(|| "the paragraph is gone once revisions settle".to_string()),
    });
    rows
}

/// The read-only context neighbours of selected paragraph `g`, charged
/// to `budget`.
fn context_of(
    g: usize,
    selection: &Selection,
    s_opened: &Opened,
    s_loaded: &Loaded,
    native: &NativeKeys,
    budget: &mut usize,
) -> Vec<SourceContextRow> {
    if selection.context == 0 {
        return Vec::new();
    }
    let (story, local) = s_loaded.paragraph_story[g];
    let from = local.saturating_sub(selection.context);
    let to = local.saturating_add(selection.context);
    let mut out = Vec::new();
    for l in from..=to {
        if l == local {
            continue;
        }
        let Some(neighbour) = s_loaded
            .paragraph_story
            .iter()
            .position(|&pair| pair == (story, l))
        else {
            continue;
        };
        // Context never repeats a selected row.
        if selection.selected.contains(&neighbour) {
            continue;
        }
        let node = s_loaded.paragraph_nodes[neighbour];
        let story_id = s_loaded.stories[story].id.as_str();
        let part = s_loaded.stories[story].part.as_str();
        let short_id = crate::ids::paragraph_id(story_id, l);
        let projection = project_paragraph(&s_opened.dom, node);
        let representable = v2::logical_text(&s_opened.dom, node).is_ok();
        let text_codec = if representable {
            "supported"
        } else {
            "unsupported"
        };
        let (_, mut revisions, mark_revisions) = obstacles(&s_opened.dom, node, story_id, part);
        revisions.extend(mark_revisions);
        for reference in &mut revisions {
            reference.basis = "original".to_string();
        }
        let value = TextValue::bounded(&projection.text, *budget);
        *budget = budget.saturating_sub(value.chars());
        out.push(SourceContextRow {
            kind: if representable { "paragraph" } else { "opaque" }.to_string(),
            target: native.pair(&s_opened.dom, story, part, &short_id, node),
            value,
            text_view: "final".to_string(),
            text_codec: text_codec.to_string(),
            limitations: projection.limitations.into_iter().collect(),
            revisions,
            reason_codes: if representable {
                vec!["context".to_string()]
            } else {
                vec!["context".to_string(), "unsupported_text_codec".to_string()]
            },
        });
    }
    out
}

/// Read `source` for editing: selection frozen on S, text and readiness
/// derived from the working document `request` settles S to.
///
/// # Errors
///
/// [`EditError`] codes: `USAGE` for malformed flags, `EXISTING_REVISIONS`
/// when the policy cannot form a working basis (its blockers are the
/// document's remaining revisions), `UNKNOWN_CHANGE`/`AMBIGUOUS_CHANGE`/
/// `REVISION_CONFLICT` for bad decisions, `CURSOR_BASIS_CHANGED` when a
/// cursor's bound basis no longer matches.
pub fn for_edit(source: &[u8], request: &ForEditRequest) -> Result<ForEdit, EditError> {
    for_edit_quoting(source, request, super::PlanSyntax::V1)
}

/// Build the working view with refusals in the caller's syntax.
#[doc(hidden)]
pub fn for_edit_quoting(
    source: &[u8],
    request: &ForEditRequest,
    syntax: super::PlanSyntax,
) -> Result<ForEdit, EditError> {
    if request.find.is_some() && request.regex.is_some() {
        return Err(super::err("USAGE", None, "--find and --regex conflict"));
    }
    if (request.by.is_some() || !request.by_any.is_empty()) && !request.changed {
        return Err(super::err("USAGE", None, "--by needs --changed"));
    }
    let source_digest = source_sha256(source);
    let probe = Opened::open(source).map_err(super::open_error)?;
    let plan = EditPlan {
        schema_version: crate::inspect::SCHEMA_VERSION,
        source_sha256: Some(source_digest.clone()),
        author: "jubarte read --for-edit".to_string(),
        date: None,
        initials: None,
        resolve_revisions: (!request.accept.is_empty() || !request.reject.is_empty()).then(|| {
            ResolveRevisions {
                accept: (!request.accept.is_empty())
                    .then(|| ChangeFilter::ids(request.accept.iter().cloned())),
                reject: (!request.reject.is_empty())
                    .then(|| ChangeFilter::ids(request.reject.iter().cloned())),
                reject_visible: false,
            }
        }),
        removed_anchor_comments: Default::default(),
        existing_revisions: request.existing_revisions,
        operations: Vec::new(),
        update_fields: false,
        rewrite_others_comments: false,
        others: super::Others::Allow,
    };
    let Settled {
        base,
        mut opened,
        resolved_revisions,
        changed,
        ..
    } = settle(source, &plan, probe, syntax)?;
    let Loaded {
        stories,
        paragraph_nodes,
        paragraph_story,
    } = load_stories(&mut opened)?;

    // S, the original snapshot every ID and observation is bound to.
    let mut s_opened = Opened::open(source).map_err(super::open_error)?;
    let s_loaded = load_stories(&mut s_opened)?;

    // Original-to-working correspondence.
    let fates: Vec<Fate> = if changed {
        let ids: Vec<String> = stories.iter().map(|s| s.id.clone()).collect();
        let origin = Origin::build(source, &plan, &ids, &paragraph_story)?;
        (0..s_loaded.paragraph_nodes.len())
            .map(|g| match origin.exact(g) {
                Ok(post) => Fate::Kept(post),
                Err(_) => match origin.fate(g) {
                    Fate::Kept(post) | Fate::Merged(post) => Fate::Merged(post),
                    Fate::Gone => Fate::Gone,
                },
            })
            .collect()
    } else {
        (0..s_loaded.paragraph_nodes.len())
            .map(Fate::Kept)
            .collect()
    };

    // Long IDs need the per-story native-key inventory of S.
    let native = NativeKeys::collect(&s_opened.dom, &s_loaded.stories);

    // The frozen selection, resolved on S before anything settles.
    let selection = Selection::build(request, &s_opened, &s_loaded, source)?;
    let basis_digest = basis_digest(&source_digest, request, &selection);
    let offset = match &request.cursor {
        Some(token) => cursor_offset(token, &basis_digest)?,
        None => 0,
    };
    if offset > selection.selected.len() {
        return Err(super::err(
            "CURSOR_BASIS_CHANGED",
            None,
            "the cursor continues past the frozen selection; start a new query",
        ));
    }

    // Comments of S, for references and the --changed/--by selection.
    let comment_list = crate::comments::list_comments(source)
        .map_err(|e| super::err(e.code(), None, e.to_string()))?;
    let (comments, unanchored_comments) = comments_by_paragraph(&comment_list, &s_loaded);

    // Pagination over the frozen selection.
    let limit = if request.all {
        usize::MAX
    } else {
        request.limit.unwrap_or(100)
    };
    let max_chars = if request.all {
        usize::MAX
    } else {
        request.max_chars.unwrap_or(24_000)
    };
    let mut rows: Vec<ForEditRow> = Vec::new();
    let mut context_rows = Vec::new();
    let mut omissions = Vec::new();
    let mut budget = max_chars;
    let mut next = selection.selected.len();
    let mut truncated = false;
    for (i, &g) in selection.selected.iter().enumerate().skip(offset) {
        if rows.len() >= limit {
            next = i;
            truncated = true;
            break;
        }
        let mut row = make_row(
            g,
            &RowCtx {
                selection: &selection,
                fates: &fates,
                s_opened: &s_opened,
                s_loaded: &s_loaded,
                w_opened: &opened,
                w_stories: &stories,
                w_nodes: &paragraph_nodes,
                w_story: &paragraph_story,
                native: &native,
                comments: &comments,
            },
        );
        bound_row(&mut row, budget);
        let used = text_chars(&row);
        let complete =
            row.original.complete && row.working.as_ref().is_none_or(|w| w.value.complete);
        budget = budget.saturating_sub(used);
        for ctx in context_of(g, &selection, &s_opened, &s_loaded, &native, &mut budget) {
            context_rows.push(ctx);
        }
        let id = row.target.short_id.clone();
        rows.push(row);
        if !complete {
            truncated = true;
            next = i + 1;
            if next < selection.selected.len() {
                omissions.push(format!(
                    "text budget exhausted inside {id}; its previews are not complete text"
                ));
            }
            break;
        }
    }
    if selection.selected.is_empty() {
        let filters: Vec<&str> = [
            request.select.is_some().then_some("ids"),
            request.head.is_some().then_some("ids"),
            request.tail.is_some().then_some("ids"),
            request.find.is_some().then_some("find"),
            request.regex.is_some().then_some("regex"),
            request.changed.then_some("changed"),
            request.by.is_some().then_some("by"),
        ]
        .into_iter()
        .flatten()
        .collect();
        if !filters.is_empty() {
            // Filters narrow to a conjunction: an empty result names
            // them so a miss is not mistaken for a refusal.
            omissions.push(format!(
                "no paragraphs match every filter given: {}",
                filters.join(", ")
            ));
        }
    }
    let next_cursor = (next < selection.selected.len()).then(|| cursor_token(&basis_digest, next));
    if next_cursor.is_some() {
        truncated = true;
        omissions.push(format!(
            "{} of {} selected paragraphs returned; continue with --cursor",
            rows.len(),
            selection.selected.len()
        ));
    }

    let mut accept = request.accept.clone();
    let mut reject = request.reject.clone();
    accept.sort();
    accept.dedup();
    reject.sort();
    reject.dedup();
    Ok(ForEdit {
        schema: "jubarte-read-for-edit-v1".to_string(),
        source_sha256: source_digest,
        basis: ForEditBasis {
            text_view: "final".to_string(),
            text_codec_version: v2::TEXT_CODEC_VERSION,
            track: if request.track {
                "on".to_string()
            } else {
                "off".to_string()
            },
            existing_revisions: existing_revisions_name(request.existing_revisions).to_string(),
            accept,
            reject,
            working_sha256: source_sha256(&base),
            digest: basis_digest,
        },
        settled: ForEditSettled {
            changed,
            accepted: resolved_revisions.accepted,
            rejected: resolved_revisions.rejected,
        },
        coverage: ForEditCoverage {
            selection_complete: next_cursor.is_none(),
            paragraphs_selected: selection.selected.len(),
            paragraphs_returned: rows.len(),
            context_paragraphs: context_rows.len(),
            truncated,
            omissions,
        },
        paragraphs: rows,
        unanchored_comments,
        source_context: context_rows,
        comments: comment_list,
        next_cursor,
        input_validity: None,
    })
}

/// [`for_edit`]'s result as `read --for-edit` prints it: the document
/// carries `validity` (the input's findings, `None` when the caller read
/// none — #1340), serialized to the one JSON line the binary writes to
/// stdout or a `.json` file. The native binary, the Python module and the
/// WASM binding all print this string.
///
/// # Errors
///
/// [`for_edit`]'s.
pub fn for_edit_json(
    source: &[u8],
    request: &ForEditRequest,
    validity: Option<crate::validate::InputValidity>,
) -> Result<String, EditError> {
    let mut result = for_edit(source, request)?;
    result.input_validity = validity;
    let json = serde_json::to_string(&result).expect("ForEdit serializes");
    Ok(format!("{json}\n"))
}

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

    #[test]
    fn cursor_binds_frozen_membership_independently_of_request_filters() {
        let request = ForEditRequest::default();
        let mut selection = Selection {
            selected: vec![0, 1],
            matched_by: HashMap::new(),
            context: 0,
        };
        let source = source_sha256(b"source");
        let basis = basis_digest(&source, &request, &selection);
        let cursor = cursor_token(&basis, 1);
        assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
        selection.selected = vec![1, 2];
        let changed = basis_digest(&source, &request, &selection);
        let error = cursor_offset(&cursor, &changed).unwrap_err();
        assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
    }

    #[test]
    fn cursor_binds_source_digest_independently_of_selection() {
        let request = ForEditRequest::default();
        let selection = Selection {
            selected: vec![0, 1],
            matched_by: HashMap::new(),
            context: 0,
        };
        let source = source_sha256(b"source");
        let basis = basis_digest(&source, &request, &selection);
        let cursor = cursor_token(&basis, 1);
        assert_eq!(cursor_offset(&cursor, &basis).unwrap(), 1);
        let changed = basis_digest(&source_sha256(b"other"), &request, &selection);
        let error = cursor_offset(&cursor, &changed).unwrap_err();
        assert_eq!(error.code, "CURSOR_BASIS_CHANGED");
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod request_branch_tests {
    use super::super::deeper_boundary_fixture::{docx, para};
    use super::*;

    fn source() -> Vec<u8> {
        docx(&format!(
            "{}{}{}",
            para("Alpha one."),
            para("Beta two."),
            para("Gamma three.")
        ))
    }

    fn token(json: &serde_json::Value) -> String {
        use base64::Engine;
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json.to_string())
    }

    #[test]
    fn previews_cut_only_between_words() {
        let at_space = TextValue::bounded("ab cd", 3);
        assert_eq!(at_space.text_preview.as_deref(), Some("ab "));
        let before_space = TextValue::bounded("ab cd", 2);
        assert_eq!(before_space.text_preview.as_deref(), Some("ab"));
        let mid_word = TextValue::bounded("abcd ef", 2);
        assert_eq!(mid_word.text_preview.as_deref(), Some("abcd"));
        assert!(TextValue::bounded("abcd", 2).complete);
    }

    #[test]
    fn requests_refuse_conflicting_or_incomplete_filters() {
        let source = source();
        let both = ForEditRequest {
            find: Some("a".into()),
            regex: Some("b".into()),
            ..ForEditRequest::default()
        };
        assert_eq!(
            for_edit(&source, &both).unwrap_err().message,
            "--find and --regex conflict"
        );
        let by = ForEditRequest {
            by: Some("Bo".into()),
            ..ForEditRequest::default()
        };
        assert_eq!(
            for_edit(&source, &by).unwrap_err().message,
            "--by needs --changed"
        );
        let by_any = ForEditRequest {
            by_any: vec!["Bo".into()],
            ..ForEditRequest::default()
        };
        assert_eq!(
            for_edit(&source, &by_any).unwrap_err().message,
            "--by needs --changed"
        );
    }

    #[test]
    fn cursors_must_be_ours_and_inside_the_selection() {
        let source = source();
        let page = ForEditRequest {
            limit: Some(1),
            ..ForEditRequest::default()
        };
        let first = for_edit(&source, &page).unwrap();
        assert_eq!(first.paragraphs.len(), 1);
        let next = first.next_cursor.clone().expect("more to read");
        let second = for_edit(
            &source,
            &ForEditRequest {
                cursor: Some(next.clone()),
                ..page.clone()
            },
        )
        .unwrap();
        assert_eq!(second.paragraphs.len(), 1);
        assert_ne!(second.paragraphs[0].target, first.paragraphs[0].target);
        let basis = {
            use base64::Engine;
            let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
                .decode(&next)
                .unwrap();
            let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
            v["basis"].as_str().unwrap().to_string()
        };
        for bad in [
            serde_json::json!({"v": 2, "basis": basis, "offset": 1}),
            serde_json::json!({"v": 1, "basis": basis, "offset": "1"}),
            serde_json::json!({"v": 1, "basis": 7, "offset": 1}),
        ] {
            let e = for_edit(
                &source,
                &ForEditRequest {
                    cursor: Some(token(&bad)),
                    ..page.clone()
                },
            )
            .unwrap_err();
            assert_eq!(e.code, "USAGE", "{bad}");
        }
        let past = for_edit(
            &source,
            &ForEditRequest {
                cursor: Some(cursor_token(&basis, 99)),
                ..page.clone()
            },
        )
        .unwrap_err();
        assert_eq!(past.code, "CURSOR_BASIS_CHANGED");
        assert!(
            past.message.contains("past the frozen selection"),
            "{}",
            past.message
        );
    }

    #[test]
    fn head_and_tail_pick_body_paragraphs() {
        let source = source();
        let ids = |request: ForEditRequest| -> Vec<String> {
            for_edit(&source, &request)
                .unwrap()
                .paragraphs
                .into_iter()
                .map(|r| r.original.text.unwrap_or_default())
                .collect()
        };
        let head = ids(ForEditRequest {
            head: Some(1),
            ..ForEditRequest::default()
        });
        assert_eq!(head, ["Alpha one."]);
        let tail = ids(ForEditRequest {
            tail: Some(2),
            ..ForEditRequest::default()
        });
        assert_eq!(tail, ["Beta two.", "Gamma three."]);
        let none = for_edit(
            &source,
            &ForEditRequest {
                find: Some("zzz".into()),
                ..ForEditRequest::default()
            },
        )
        .unwrap();
        assert!(none.paragraphs.is_empty());
        assert!(
            none.coverage
                .omissions
                .iter()
                .any(|o| o.contains("every filter given: find")),
            "{:?}",
            none.coverage.omissions
        );
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod reference_branch_tests {
    use super::*;

    #[test]
    fn values_escape_every_byte_outside_the_literal_set() {
        assert_eq!(escape_value("a.b_c:9"), "a.b_c:9");
        assert_eq!(escape_value("a b/é"), "a-20b-2F-C3-A9");
    }

    #[test]
    fn a_resolved_comment_reads_done() {
        let mut record = crate::comments::CommentRecord {
            id: 4,
            r#ref: "c4".into(),
            author: "Bo".into(),
            initials: None,
            date: None,
            text: "Note".into(),
            parent: None,
            done: true,
            paragraph: None,
            last_paragraph: None,
            anchor_text: String::new(),
            before: String::new(),
            after: String::new(),
        };
        let done = comment_ref(&record);
        assert_eq!(done.short_id, "c4");
        assert_eq!(done.status, "done");
        record.done = false;
        assert_eq!(comment_ref(&record).status, "open");
    }
}