aozora 0.5.0

Aozora Bunko notation parser with incremental document snapshots
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
//! Source-region ownership and minimal-diff source splicing.
//!
//! The **minimal-diff edit splice** (issue #202) — the last pillar of the
//! coremodel-purification epic (#189). An editor surface that "adds ruby to
//! this word" or "changes this heading level" wants the resulting source to
//! differ from the original by the smallest possible diff; it must *not*
//! reflow the whole document to canonical form ([`Snapshot::to_source`]), which
//! would rewrite the author's verbatim formatting everywhere.
//!
//! This layer answers, for every byte of the sanitized source, two questions:
//!
//! 1. **Who owns each source byte?** [`Snapshot::regions`] projects the
//!    source-node table into a *total, non-overlapping, ordered* tiling: one
//!    [`Region`] per classified node plus the interstitial plain runs
//!    between them. Concatenating every region's bytes reproduces
//!    [`Snapshot::to_source_verbatim`] exactly.
//!
//! 2. **How is this region edited coherently?** Each region carries a
//!    terminal [`SpliceSafety`]:
//!    - [`Direct`](SpliceSafety::Direct) — the region fully owns its rendered
//!      content (a self-contained node, or plain interstitial text), so
//!      replacing its bytes is a complete edit.
//!    - [`Coupled`](SpliceSafety::Coupled) — a coherent edit spans a *derived
//!      partner*: the upstream literal of a non-adjacent forward reference
//!      ([`ForwardOrigin::Referenced`]), a heading hint, a margin note, or the
//!      paired marker of a container. The partner is recovered on demand
//!      ([`Snapshot::coupling`]) and the edit is checked by re-parse.
//!
//! [`Snapshot::splice`] performs the edit and returns the minimal-diff source —
//! every byte outside the affected region(s) stays identical, unlike the
//! whole-document reflow of [`Snapshot::to_source`]. A coupled edit *derives* the
//! partner change, re-parses the candidate, and **verifies** the construct
//! re-formed; it returns [`SpliceError`] rather than emit a byte-valid but
//! semantically desynced edit. The parser is the single source of truth for
//! "what couples to what" — this layer proposes, the parser confirms.
//!
//! # Why this shape
//!
//! Nothing is stored on the AST to support the splice. The coupling of a
//! forward reference is exactly the irreducible [`ForwardOrigin`] provenance
//! the epic already materialized; a container's pairing is the structural
//! nesting already present in [`Snapshot::source_nodes`]. The splice model is the
//! dual of the parser's classification, derived entirely on demand from data
//! that already exists. See ADR-0018 (foundation) and ADR-0019 (coupled /
//! container splice).
//!
//! Incremental *re-parse* (reusing the unaffected tree across an edit) is a
//! separate performance concern, not part of this model: the parser is
//! single-digit milliseconds on real corpus documents, so the verify re-parse
//! is cheap and there is no current pressure to reuse subtrees.

use core::error::Error;
use core::fmt;

use crate::render::spelling::source::container_close_source;
use crate::spec::{SourceOffset, Span};
use crate::syntax::{ForwardOrigin, RegionClose, RegionFormat};

use crate::syntax::ast::{Node, NodeRef};
use crate::{Document, Snapshot};

/// What a single source region represents.
///
/// Informational — tooling renders it to explain a region — while the
/// actionable bit is the region's [`SpliceSafety`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum RegionRole {
    /// Plain text between classified constructs. Not a node; carried so the
    /// tiling is complete. Directly editable as bytes.
    Interstitial,
    /// Ruby (furigana). Self-contained: the base run is included in the region
    /// (the explicit `|` or the implicit trailing-kanji pull-back).
    Ruby,
    /// Forward emphasis whose target literal the classifier pulled into the
    /// node from the immediately-preceding source
    /// ([`ForwardOrigin::Reclaimed`]). The literal lives inside the region, so
    /// it is self-contained.
    ForwardReclaimed,
    /// Forward emphasis whose target literal stays in a separate upstream run
    /// ([`ForwardOrigin::Referenced`]). Ownership is split across two regions
    /// — the bracket here and the upstream literal — so a coherent target
    /// edit is a [`Coupled`](SpliceSafety::Coupled) splice.
    ForwardReferenced,
    /// Forward emphasis whose quoted target is absent from the preceding source
    /// ([`ForwardOrigin::SelfContained`]). The target literal lives wholly
    /// inside the region — there is no upstream copy — so it is self-contained
    /// and a coherent target edit is a [`Direct`](SpliceSafety::Direct) splice,
    /// like [`ForwardReclaimed`](Self::ForwardReclaimed) but with no reclaimed
    /// prefix.
    ForwardSelfContained,
    /// The styled-literal half of a **non-adjacent** forward-reference split
    /// ([`ForwardOrigin::Detached`]) — a decoration leaf materialised at an
    /// interior occurrence of the target run (#333). The literal lives wholly
    /// inside the region, so editing it is a [`Direct`](SpliceSafety::Direct)
    /// splice; the directive bracket is the coupled
    /// [`ForwardReferenced`](Self::ForwardReferenced) partner, derived on demand.
    ForwardDetached,
    /// Out-of-character-range glyph (外字).
    Gaiji,
    /// Single-line layout directive (字下げ / 地付き / 中央 / 罫囲み).
    Line,
    /// Page break (`[#改ページ]`).
    PageBreak,
    /// Section break (`[#改丁/改段/改見開き]`).
    SectionBreak,
    /// Body-end marker (`[#本文終わり]`) — a self-contained structural leaf.
    BodyEnd,
    /// Forced line break (`[#改行]`) — a self-contained inline marker.
    ForcedBreak,
    /// Heading promoted from a bare line above its directive — the referent
    /// line is reclaimed into the region, so it is self-contained.
    Heading,
    /// Forward heading hint whose referent is *not* the bare line above it, so
    /// the referent lives elsewhere. A coherent target edit is coupled.
    HeadingHint,
    /// Forward heading hint whose quoted target is absent from the preceding
    /// source — a no-referent heading whose target run is itself the heading
    /// text. There is no upstream copy, so it is self-contained and a coherent
    /// target edit is a [`Direct`](SpliceSafety::Direct) splice — the
    /// [`HeadingHint`](Self::HeadingHint) analogue of
    /// [`ForwardSelfContained`](Self::ForwardSelfContained).
    HeadingSelfContained,
    /// Illustration (`[#挿絵]`).
    Illustration,
    /// Chinese-reading-order mark (返り点).
    Kaeriten,
    /// Generic annotation (`[#ママ]`, an unresolved `[#…]`, …). The
    /// directive bracket is self-contained.
    Directive,
    /// `≪…≫` double-angle quotation.
    AngleQuote,
    /// Left-side note (注記 / 傍記) attached to a preceding base run. A
    /// coherent target edit is coupled with that base run.
    MarginNote,
    /// A paired-container open marker (`[#ここから…]`). Coupled with its
    /// matching close.
    ContainerOpen,
    /// A paired-container close marker (`[#ここで…終わり]`). Coupled with its
    /// matching open.
    ContainerClose,
}

/// The kind of two-region coupling a region participates in — the payload of a
/// coupled splice classification.
///
/// Distinct from [`RegionRole`], which names a single tile: this names the
/// *relationship* between the region and its derived partner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum CoupledKind {
    /// A non-adjacent forward reference ([`ForwardOrigin::Referenced`]): the
    /// directive bracket plus its upstream target literal.
    ForwardReference,
    /// A forward heading hint plus its upstream referent run.
    HeadingHint,
    /// A margin note (注記 / 傍記) plus the upstream base run it annotates.
    MarginNote,
    /// A paired container: the `[#ここから…]` open plus the `[#ここで…終わり]`
    /// close.
    Container,
}

/// How a region is edited as a coherent minimal-diff splice. Terminal: every
/// classified region is exactly one of these — there is no "deferred to a
/// later phase" state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum SpliceSafety {
    /// The region fully owns its rendered content (a self-contained node, or
    /// plain interstitial text). Replacing its bytes is a complete edit;
    /// neighbouring regions stay byte-identical.
    Direct,
    /// A coherent edit spans a *derived partner* region (an upstream literal,
    /// or a paired container marker). [`Snapshot::splice`] derives the partner
    /// change and verifies it by re-parse; [`Snapshot::coupling`] exposes the
    /// partner span.
    Coupled(CoupledKind),
}

/// A contiguous run of source bytes and what it owns.
///
/// Yielded by [`Snapshot::regions`] / [`Snapshot::region_at`]. The
/// [`span`](Self::span) indexes the **sanitized** source — the same coordinate
/// space as [`Snapshot::to_source_verbatim`] and every `source_span` on
/// [`Snapshot::source_nodes`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) struct Region {
    /// Half-open byte range in sanitized-source coordinates.
    pub span: Span,
    /// What the region represents.
    pub role: RegionRole,
    /// How the region is edited coherently.
    pub safety: SpliceSafety,
}

/// The two source regions a coupled edit touches.
///
/// Recovered on demand by [`Snapshot::coupling`] from the source-node table — no
/// link is stored on the AST. Both spans are in sanitized-source coordinates;
/// `primary` and `partner` are *not* ordered relative to each other (a forward
/// reference's literal precedes its bracket; a container's open precedes its
/// close).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) struct Coupling {
    /// The relationship between the two regions.
    pub kind: CoupledKind,
    /// The queried region (the directive bracket, or the queried container
    /// marker).
    pub primary: Span,
    /// The derived partner: the upstream target literal (forward / heading
    /// hint / margin note), or the matching container marker.
    pub partner: Span,
}

/// Error returned by [`Snapshot::splice`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum SpliceError {
    /// A [`Coupled`](SpliceSafety::Coupled) edit could not be carried out
    /// coherently: the candidate source did not re-parse to the intended
    /// construct, so applying it would silently desync the reference. The
    /// honest terminal outcome for the corpus-attested hard cases — an
    /// ambiguous forward referent, a ruby-base target literal, or a
    /// 、-joined multi-target. The source is left unchanged.
    Unverifiable {
        /// The edited region's role, for diagnostics.
        role: RegionRole,
        /// The coupling that could not be completed.
        kind: CoupledKind,
    },
}

impl fmt::Display for SpliceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unverifiable { role, kind } => write!(
                f,
                "coupled {kind:?} edit of region {role:?} could not be verified \
                 (the candidate did not re-parse to the intended construct)"
            ),
        }
    }
}

impl Error for SpliceError {}

/// Classify a node region's role and splice safety. Pure: a function of the
/// [`NodeRef`] variant and (for a forward leaf) its [`ForwardOrigin`] alone.
///
/// `pub(crate)` so the incremental splice
/// Incremental document editing shares this single source of truth for the
/// text-coupling check (a forward reference / heading hint / margin note
/// resolves by whole-document text search, so a region re-lex cannot localise
/// it).
pub(crate) fn classify_node_ref(node: NodeRef) -> (RegionRole, SpliceSafety) {
    use SpliceSafety::{Coupled, Direct};

    match node {
        NodeRef::BlockOpen(_) => (RegionRole::ContainerOpen, Coupled(CoupledKind::Container)),
        NodeRef::BlockClose(_) => (RegionRole::ContainerClose, Coupled(CoupledKind::Container)),
        NodeRef::Inline(n) | NodeRef::BlockLeaf(n) => match n {
            Node::Format(f) => match f.origin {
                ForwardOrigin::Reclaimed => (RegionRole::ForwardReclaimed, Direct),
                ForwardOrigin::Referenced => (
                    RegionRole::ForwardReferenced,
                    Coupled(CoupledKind::ForwardReference),
                ),
                ForwardOrigin::SelfContained => (RegionRole::ForwardSelfContained, Direct),
                // The styled-literal half of a non-adjacent split (#333): its
                // literal lives wholly inside the region, so a byte-replace is a
                // complete local edit — `Direct`, exactly like the interstitial
                // plain run it was carved out of. (It must NOT be `Coupled`: the
                // identity-splice gate would call `first_quoted` on the raw
                // literal and decline.)
                ForwardOrigin::Detached => (RegionRole::ForwardDetached, Direct),
            },
            Node::HeadingHint(h) => {
                if h.self_contained {
                    // No upstream referent — the bracket owns its target bytes,
                    // so editing it is a Direct splice (cf. ForwardSelfContained).
                    (RegionRole::HeadingSelfContained, Direct)
                } else {
                    (RegionRole::HeadingHint, Coupled(CoupledKind::HeadingHint))
                }
            }
            Node::MarginNote(_) => (RegionRole::MarginNote, Coupled(CoupledKind::MarginNote)),
            Node::Ruby(_) => (RegionRole::Ruby, Direct),
            Node::Heading(_) => (RegionRole::Heading, Direct),
            Node::Gaiji(_) => (RegionRole::Gaiji, Direct),
            Node::AngleQuote(_) => (RegionRole::AngleQuote, Direct),
            Node::Kaeriten(_) => (RegionRole::Kaeriten, Direct),
            Node::Illustration(_) => (RegionRole::Illustration, Direct),
            Node::Line(_) => (RegionRole::Line, Direct),
            Node::PageBreak => (RegionRole::PageBreak, Direct),
            Node::SectionBreak(_) => (RegionRole::SectionBreak, Direct),
            // Self-contained structural-marker leaves (#78) — they fully own
            // their rendered bytes, so editing the bracket is a Direct splice.
            Node::BodyEnd => (RegionRole::BodyEnd, Direct),
            Node::ForcedBreak => (RegionRole::ForcedBreak, Direct),
            Node::Directive(_) => (RegionRole::Directive, Direct),
        },
    }
}

/// Interstitial plain text: not a node, but the most directly editable region
/// of all — replacing the bytes is a complete edit.
const INTERSTITIAL: (RegionRole, SpliceSafety) = (RegionRole::Interstitial, SpliceSafety::Direct);

/// Whether `node` belongs to the same construct family as a coupled `kind` —
/// the verify predicate for a re-parsed single-region edit.
///
/// A coupled forward reference re-forms only as a *referent-bearing* forward
/// (`Reclaimed` or `Referenced`). A [`SelfContained`](ForwardOrigin::SelfContained)
/// re-parse is **not** a re-formation: it owns its target with no upstream copy,
/// so accepting it would let a target *change* masquerade as a coherent
/// single-region edit and silently skip the upstream rewrite. Excluding it makes
/// the single-region attempt fail so the coupled two-region path rewrites (or
/// honestly declines) the edit. A heading hint re-forms as a referent-bearing
/// hint *or* a promoted heading, but a `self_contained` re-parse is excluded for
/// the same reason as `SelfContained` above; a container marker re-forms as an
/// open or close.
fn reparsed_in_family(node: NodeRef, kind: CoupledKind) -> bool {
    let leaf = match node {
        NodeRef::Inline(n) | NodeRef::BlockLeaf(n) => Some(n),
        _ => None,
    };
    match kind {
        CoupledKind::ForwardReference => {
            matches!(leaf, Some(Node::Format(f)) if f.origin != ForwardOrigin::SelfContained)
        }
        CoupledKind::HeadingHint => {
            matches!(leaf, Some(Node::HeadingHint(h)) if !h.self_contained)
                || matches!(leaf, Some(Node::Heading(_)))
        }
        CoupledKind::MarginNote => matches!(leaf, Some(Node::MarginNote(_))),
        CoupledKind::Container => {
            matches!(node, NodeRef::BlockOpen(_) | NodeRef::BlockClose(_))
        }
    }
}

impl Snapshot {
    /// Project the source-node table into a complete tiling of the sanitized
    /// source: one [`Region`] per classified node plus the interstitial
    /// plain runs between (and around) them.
    ///
    /// The regions are contiguous, non-overlapping, and ordered by start
    /// offset; the first starts at `0`, the last ends at the sanitized length,
    /// and concatenating each region's bytes reproduces
    /// [`Snapshot::to_source_verbatim`] exactly. A truly empty source yields no
    /// regions.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn regions(&self) -> Vec<Region> {
        let nodes = self.source_nodes();
        // The sanitized length fits u32 — every offset in the tree is a u32
        // `Span` — so the saturating fallback is never taken.
        let src_len = u32::try_from(self.normalized_source().len()).unwrap_or(u32::MAX);
        let mut out: Vec<Region> = Vec::with_capacity(nodes.len() * 2 + 1);
        let mut cursor: u32 = 0;
        for sn in nodes {
            let start = sn.source_span.start;
            if start > cursor {
                out.push(Region {
                    span: Span::new(cursor, start),
                    role: INTERSTITIAL.0,
                    safety: INTERSTITIAL.1,
                });
            }
            let (role, safety) = classify_node_ref(sn.node);
            out.push(Region {
                span: sn.source_span,
                role,
                safety,
            });
            cursor = sn.source_span.end;
        }
        if cursor < src_len {
            out.push(Region {
                span: Span::new(cursor, src_len),
                role: INTERSTITIAL.0,
                safety: INTERSTITIAL.1,
            });
        }
        out
    }

    /// The [`Region`] covering `off`, a sanitized-source byte offset.
    ///
    /// Returns the classified node region when `off` lands on a construct
    /// ([`O(log n)`](Snapshot::node_at_source)), or the surrounding interstitial
    /// run otherwise. Returns `None` only when `off` is past the end of the
    /// sanitized source.
    #[must_use]
    pub(crate) fn region_at(&self, off: SourceOffset) -> Option<Region> {
        let src_len = u32::try_from(self.normalized_source().len()).unwrap_or(u32::MAX);
        if off.get() >= src_len {
            return None;
        }
        if let Some(sn) = self.node_at_source(off) {
            let (role, safety) = classify_node_ref(sn.node);
            return Some(Region {
                span: sn.source_span,
                role,
                safety,
            });
        }
        // `off` falls in an interstitial gap, bounded by the end of the last
        // node starting at/before `off` and the start of the next node.
        let nodes = self.source_nodes();
        let raw = off.get();
        let next_idx = nodes.partition_point(|n| n.source_span.start <= raw);
        let gap_start = if next_idx == 0 {
            0
        } else {
            nodes[next_idx - 1].source_span.end
        };
        let gap_end = nodes.get(next_idx).map_or(src_len, |n| n.source_span.start);
        Some(Region {
            span: Span::new(gap_start, gap_end),
            role: INTERSTITIAL.0,
            safety: INTERSTITIAL.1,
        })
    }

    /// Recover the two regions a [`Coupled`](SpliceSafety::Coupled) edit
    /// touches, or `None` for a direct region or when the partner cannot be
    /// located.
    ///
    /// For a container marker the partner is its matching open/close, paired
    /// directly in source coordinates by a depth-stack walk over
    /// [`Snapshot::source_nodes`] — no normalized-coordinate detour. For a forward
    /// reference / heading hint / margin note the partner is the upstream
    /// target literal.
    ///
    /// This is read-only introspection (e.g. for an editor to highlight both
    /// sites). [`Snapshot::splice`] performs the actual coherent edit.
    #[must_use]
    pub(crate) fn coupling(&self, region: Region) -> Option<Coupling> {
        match region.safety {
            SpliceSafety::Coupled(CoupledKind::Container) => self.container_coupling(region.span),
            SpliceSafety::Coupled(CoupledKind::MarginNote) => {
                self.margin_note_coupling(region.span)
            }
            SpliceSafety::Coupled(kind) => {
                // Forward reference / heading hint / margin note: the partner is
                // the unique upstream plain occurrence of the node's target.
                // `None` for the irreducible cases (ambiguous referent, a
                // ruby-base literal, a multi-segment target).
                let target = self.coupled_target_text(region.span)?;
                let partner = self.unique_upstream_plain(region.span.start, &target)?;
                Some(Coupling {
                    kind,
                    primary: region.span,
                    partner,
                })
            }
            _ => None,
        }
    }

    fn margin_note_coupling(&self, span: Span) -> Option<Coupling> {
        let source = self.normalized_source();
        let text = source.get(span.start as usize..span.end as usize)?;
        let marker = text.rfind("[#")?;
        let (NodeRef::Inline(Node::MarginNote(note)) | NodeRef::BlockLeaf(Node::MarginNote(note))) =
            self.node_at_source(SourceOffset::new(span.start))?.node
        else {
            return None;
        };
        let base = self.node_store().content_range_as_plain(note.base)?;
        let base_start = marker.checked_sub(base.len())?;
        if text.get(base_start..marker) != Some(base) {
            return None;
        }
        let span_start = span.start as usize;
        let partner_start = span_start.checked_add(base_start)?;
        let marker_start = span_start.checked_add(marker)?;
        Some(Coupling {
            kind: CoupledKind::MarginNote,
            primary: Span::new(u32::try_from(marker_start).ok()?, span.end),
            partner: Span::new(
                u32::try_from(partner_start).ok()?,
                u32::try_from(marker_start).ok()?,
            ),
        })
    }

    /// Produce minimal-diff source by editing `region` to `replacement`.
    ///
    /// `replacement` is the new source for the region's own bytes (the new
    /// directive bracket, the new container open marker, the new self-contained
    /// node text, or `""` to delete). The result preserves every byte outside
    /// the affected region(s) exactly, unlike the whole-document
    /// canonicalisation of [`Snapshot::to_source`].
    ///
    /// - A [`Direct`](SpliceSafety::Direct) region is a single-region byte
    ///   replacement.
    /// - A [`Coupled`](SpliceSafety::Coupled) region derives its partner change
    ///   (the matching container close for a new open; the upstream literal for
    ///   a forward-reference target change) and **verifies** the candidate by
    ///   re-parse before returning it.
    ///
    /// The caller re-parses the result through [`crate::Parser`].
    ///
    /// # Errors
    ///
    /// Returns [`SpliceError::Unverifiable`] when a coupled edit cannot be
    /// made coherent because the candidate did not re-parse to the intended
    /// construct.
    ///
    /// # Panics
    ///
    /// Panics if `region` did not come from this tree (its span is out of
    /// bounds for the sanitized source, or not on a UTF-8 codepoint boundary).
    /// Regions from this tree's [`Snapshot::regions`] /
    /// [`Snapshot::region_at`] always satisfy the precondition.
    pub(crate) fn splice(&self, region: Region, replacement: &str) -> Result<String, SpliceError> {
        match region.safety {
            SpliceSafety::Direct => Ok(splice_one(
                self.normalized_source(),
                region.span,
                replacement,
            )),
            SpliceSafety::Coupled(CoupledKind::Container) => {
                self.splice_container(region, replacement)
            }
            SpliceSafety::Coupled(CoupledKind::MarginNote) => {
                self.splice_margin_note(region, replacement)
            }
            SpliceSafety::Coupled(kind) => self.splice_split(region, kind, replacement),
        }
    }

    fn splice_margin_note(&self, region: Region, replacement: &str) -> Result<String, SpliceError> {
        let src = self.normalized_source();
        if replacement.is_empty() {
            return Ok(splice_one(src, region.span, replacement));
        }
        let unverifiable = SpliceError::Unverifiable {
            role: region.role,
            kind: CoupledKind::MarginNote,
        };
        let marker = replacement.rfind("[#").ok_or(unverifiable)?;
        let base = replacement.get(..marker).ok_or(unverifiable)?;
        let directive = replacement.get(marker..).ok_or(unverifiable)?;
        let target = first_quoted(directive).ok_or(unverifiable)?;
        if base != target {
            return Err(unverifiable);
        }
        if !window_reforms_coupled(replacement, CoupledKind::MarginNote, target) {
            return Err(unverifiable);
        }
        Ok(splice_one(src, region.span, replacement))
    }

    /// Pair a container marker at `span` with its partner, directly in source
    /// coordinates, via a depth-stack walk over the source-node table (the
    /// same LIFO the normalizer itself uses). Returns the coupling, or `None`
    /// for an unmatched stray marker.
    fn container_coupling(&self, span: Span) -> Option<Coupling> {
        let (open, close) = self.container_pair_for(span)?;
        let primary = if span == open { open } else { close };
        let partner = if span == open { close } else { open };
        Some(Coupling {
            kind: CoupledKind::Container,
            primary,
            partner,
        })
    }

    /// The `(open_span, close_span)` of the balanced container pair whose open
    /// or close is `span`. `None` if `span` is not a paired container marker.
    fn container_pair_for(&self, span: Span) -> Option<(Span, Span)> {
        let mut stack: Vec<Span> = Vec::new();
        for sn in self.source_nodes() {
            match sn.node {
                NodeRef::BlockOpen(_) => stack.push(sn.source_span),
                NodeRef::BlockClose(_) => {
                    if let Some(open_span) = stack.pop() {
                        let close_span = sn.source_span;
                        if span == open_span || span == close_span {
                            return Some((open_span, close_span));
                        }
                    }
                }
                _ => {}
            }
        }
        None
    }

    /// Container edit: rewrite the open marker (and, when its family changes,
    /// the matching close) or delete the pair.
    ///
    /// Verification is **scoped** — the replacement *marker* is parsed in
    /// isolation (a `[#…]` bracket is self-delimiting, so it parses
    /// identically in or out of context), never the whole document. The
    /// matching close is then a pure function of that open
    /// ([`RegionClose::of`]), and the 1:1 marker replacement preserves the
    /// document's nesting, so the edit is correct by construction — `O(marker)`,
    /// not `O(document)`.
    fn splice_container(&self, region: Region, replacement: &str) -> Result<String, SpliceError> {
        let unverifiable = SpliceError::Unverifiable {
            role: region.role,
            kind: CoupledKind::Container,
        };
        let src = self.normalized_source();
        let pair = self.container_pair_for(region.span);

        // Delete: drop the marker(s), keeping the body. A structural unwrap is
        // always byte-valid; there is no reference to desync.
        if replacement.is_empty() {
            return Ok(match pair {
                Some((open_span, close_span)) => splice_two(src, (open_span, ""), (close_span, "")),
                None => splice_one(src, region.span, ""),
            });
        }

        // Only an *open* that is part of a pair drives the coupled
        // close-derivation. A close marker, an unmatched stray marker, or a
        // leaf container is a single-region edit — accept it only if the
        // replacement is itself a container marker (so we never "fix" a
        // pre-existing mismatch or silently change the construct).
        let Some((open_span, close_span)) = pair.filter(|(open, _)| *open == region.span) else {
            return if marker_in_family(replacement, CoupledKind::Container) {
                Ok(splice_one(src, region.span, replacement))
            } else {
                Err(unverifiable)
            };
        };

        // Recover the new open's format from the replacement marker alone
        // (O(marker)); the existing open's format is a lookup on the already-
        // parsed tree (no re-parse).
        let new_format = lone_open_format(replacement).ok_or(unverifiable)?;
        let old_format = block_open_format_at(self, open_span.start);

        // Same close family (identity, amount change): keep the existing close
        // verbatim — replacing the open alone is the true minimal diff, and it
        // preserves a pre-existing mismatch rather than "fixing" it.
        if old_format.is_some_and(|old| RegionClose::of(old) == RegionClose::of(new_format)) {
            return Ok(splice_one(src, open_span, replacement));
        }

        // The close family changed: derive the canonical matching close and
        // rewrite both markers. Correct by construction — `new_format` parsed
        // cleanly, the close is its canonical partner, and the markers replace
        // 1:1 so the document's nesting is unchanged.
        let new_close = container_close_source(new_format);
        Ok(splice_two(
            src,
            (open_span, replacement),
            (close_span, &new_close),
        ))
    }

    /// Split-ownership edit (forward reference / heading hint / margin note).
    ///
    /// Removing the directive (`""`) is coherent — the upstream literal simply
    /// becomes plain. An identity or attribute-only change is a single-region
    /// edit, **verified in a scoped context**: the new bracket parsed against
    /// the node's own target (`<target><replacement>`, the minimal window that
    /// re-forms the reference), never the whole document.
    ///
    /// A target-text change is a **coupled two-region edit**: the new target is
    /// recovered from the replacement and the *unique* upstream plain
    /// occurrence of the old target; both are rewritten and the reference is
    /// re-verified in a window bounded by their distance. The irreducible cases
    /// — an ambiguous referent (the target occurs more than once), a ruby-base
    /// literal (the occurrence is not a lone plain run), or a multi-segment
    /// target — are declined as [`SpliceError::Unverifiable`] rather than
    /// silently desynced.
    fn splice_split(
        &self,
        region: Region,
        kind: CoupledKind,
        replacement: &str,
    ) -> Result<String, SpliceError> {
        let src = self.normalized_source();
        if replacement.is_empty() {
            return Ok(splice_one(src, region.span, replacement));
        }
        let unverifiable = SpliceError::Unverifiable {
            role: region.role,
            kind,
        };
        // The node's own target text. `None` for a multi-segment target (the
        // 、-joined case), which is declined.
        let old_target = self.coupled_target_text(region.span).ok_or(unverifiable)?;

        // Single-region attempt: with the node's own target byte-adjacent to the
        // new bracket (`<target><replacement>`, the minimal context that
        // re-forms the reference), an identity or attribute-only change keeps
        // the construct in its family.
        let bracket_at = u32::try_from(old_target.len()).map_err(|_| unverifiable)?;
        let ctx = format!("{old_target}{replacement}");
        if reparsed_family_at(&ctx, bracket_at, kind) {
            return Ok(splice_one(src, region.span, replacement));
        }

        // Coupled two-region attempt: the bracket's target changed, so the
        // upstream literal must change with it. Recover the new target from the
        // replacement and the *unique* upstream plain occurrence of the old
        // target, rewrite both, and verify the reference re-forms — declining
        // the irreducible cases (ambiguous referent, ruby-base literal) where
        // the occurrence is not a lone plain run.
        let new_target = first_quoted(replacement).ok_or(unverifiable)?;
        let occ = self
            .unique_upstream_plain(region.span.start, &old_target)
            .ok_or(unverifiable)?;
        let candidate = splice_two(src, (occ, new_target), (region.span, replacement));

        // Scoped verify: a window from the rewritten literal to the new
        // directive's end (bounded by the reference distance, not the document
        // size) must re-parse to a `kind` node referencing `new_target`. The
        // occurrence precedes the directive, so every offset is non-negative.
        let win_start = occ.start as usize;
        let interstice = region.span.start as usize - occ.end as usize;
        let new_directive_start = win_start + new_target.len() + interstice;
        let win_end = new_directive_start + replacement.len();
        let reformed = candidate
            .get(win_start..win_end)
            .is_some_and(|w| window_reforms_coupled(w, kind, new_target));
        if reformed {
            Ok(candidate)
        } else {
            Err(unverifiable)
        }
    }

    /// The target text of a split-ownership node (a forward reference's target
    /// or a heading hint's target) as a plain string.
    /// `None` when the node is not a split-ownership leaf, or its target is not
    /// a single plain run (a 、-joined multi-target).
    fn coupled_target_text(&self, span: Span) -> Option<String> {
        let store = &self.node_store();
        let (NodeRef::Inline(leaf) | NodeRef::BlockLeaf(leaf)) =
            self.node_at_source(SourceOffset::new(span.start))?.node
        else {
            return None;
        };
        match leaf {
            Node::Format(f) => store.content_range_as_plain(f.target).map(str::to_owned),
            Node::HeadingHint(h) => Some(store.resolve_str(h.target).to_owned()),
            _ => None,
        }
    }

    /// The span of the **unique** occurrence of `target` in the sanitized
    /// source before `before`, but only when it lies wholly within a single
    /// plain interstitial run — or a [`ForwardDetached`](RegionRole::ForwardDetached)
    /// decoration tile, whose bytes *are* the literal (#333). `None` if the
    /// target is absent, appears more than once (an ambiguous referent), or its
    /// occurrence falls inside another classified construct (e.g. a ruby base) —
    /// the irreducible cases a coupled edit must decline rather than guess.
    fn unique_upstream_plain(&self, before: u32, target: &str) -> Option<Span> {
        let prefix = self.normalized_source().get(..before as usize)?;
        let mut hit: Option<usize> = None;
        let mut from = 0usize;
        while let Some(rel) = prefix.get(from..)?.find(target) {
            let at = from + rel;
            if hit.is_some() {
                return None; // more than one occurrence — ambiguous
            }
            hit = Some(at);
            from = at + target.len();
        }
        let start = u32::try_from(hit?).ok()?;
        let span = Span::new(start, start + u32::try_from(target.len()).ok()?);
        let region = self.region_at(SourceOffset::new(span.start))?;
        let carries_literal = matches!(
            region.role,
            RegionRole::Interstitial | RegionRole::ForwardDetached
        );
        if !carries_literal {
            return None;
        }
        (span.end <= region.span.end).then_some(span)
    }
}

/// The `RegionFormat` of a `BlockOpen` node starting at sanitized offset
/// `start`, if any.
fn block_open_format_at(tree: &Snapshot, start: u32) -> Option<RegionFormat> {
    tree.node_at_source(SourceOffset::new(start))
        .and_then(|sn| match sn.node {
            NodeRef::BlockOpen(f) if sn.source_span.start == start => Some(f),
            _ => None,
        })
}

/// The `RegionFormat` of `marker` parsed *in isolation* as a single container
/// open. A `[#…]` bracket is self-delimiting, so its standalone parse equals
/// its in-context parse; this recovers the new open's format in `O(marker)`
/// without re-parsing the document. `None` if `marker` is not a clean lone open
/// marker.
fn lone_open_format(marker: &str) -> Option<RegionFormat> {
    let doc = Document::new(marker);
    match doc.snapshot().source_nodes().first() {
        Some(sn) if sn.source_span.start == 0 => match sn.node {
            NodeRef::BlockOpen(f) => Some(f),
            _ => None,
        },
        _ => None,
    }
}

/// Whether `marker`, parsed in isolation, leads with a node in `kind`'s
/// construct family (a self-delimiting `[#…]` marker). Used to accept a
/// single-region container-marker edit without re-parsing the document.
fn marker_in_family(marker: &str, kind: CoupledKind) -> bool {
    let doc = Document::new(marker);
    doc.snapshot()
        .source_nodes()
        .first()
        .is_some_and(|sn| sn.source_span.start == 0 && reparsed_in_family(sn.node, kind))
}

/// Parse `ctx` and report whether the node covering sanitized offset `off` is
/// in `kind`'s construct family. The single-region split-edit verify, in a
/// minimal `<target><replacement>` context.
fn reparsed_family_at(ctx: &str, off: u32, kind: CoupledKind) -> bool {
    let doc = Document::new(ctx);
    doc.snapshot()
        .node_at_source(SourceOffset::new(off))
        .is_some_and(|sn| reparsed_in_family(sn.node, kind))
}

/// The text inside the first `「…」` of a directive (the quoted target / base of
/// a forward reference, heading hint, or margin note). `None` if absent.
fn first_quoted(directive: &str) -> Option<&str> {
    let after_open = directive.split_once('')?.1;
    Some(after_open.split_once('')?.0)
}

/// Parse `window` and report whether it re-forms a `kind` construct whose
/// target / base text equals `new_target`. The coupled split-edit verify, in a
/// window bounded by the reference distance rather than the whole document.
fn window_reforms_coupled(window: &str, kind: CoupledKind, new_target: &str) -> bool {
    let doc = Document::new(window);
    let tree = doc.snapshot();
    let store = &tree.node_store();
    tree.source_nodes().iter().any(|sn| {
        let (NodeRef::Inline(leaf) | NodeRef::BlockLeaf(leaf)) = sn.node else {
            return false;
        };
        let text = match (kind, leaf) {
            // A `SelfContained` re-parse is not a coupled re-formation (it owns
            // its target), so it must not satisfy the windowed verify either.
            (CoupledKind::ForwardReference, Node::Format(f))
                if f.origin != ForwardOrigin::SelfContained =>
            {
                store.content_range_as_plain(f.target)
            }
            // A `self_contained` re-parse owns its target (no upstream copy), so
            // like the forward case above it is not a coupled re-formation.
            (CoupledKind::HeadingHint, Node::HeadingHint(h)) if !h.self_contained => {
                Some(store.resolve_str(h.target))
            }
            // A promoted heading is an equally valid re-formation of the hint.
            (CoupledKind::HeadingHint, Node::Heading(h)) => store.content_range_as_plain(h.text),
            (CoupledKind::MarginNote, Node::MarginNote(m)) => store.content_range_as_plain(m.base),
            _ => None,
        };
        text == Some(new_target)
    })
}

/// Replace `span`'s bytes in `src` with `replacement`. Panics (via slicing) if
/// `span` is out of bounds or off a codepoint boundary.
fn splice_one(src: &str, span: Span, replacement: &str) -> String {
    let start = span.start as usize;
    let end = span.end as usize;
    let prefix = &src[..start];
    let suffix = &src[end..];
    let mut out = String::with_capacity(
        prefix
            .len()
            .saturating_add(replacement.len())
            .saturating_add(suffix.len()),
    );
    out.push_str(prefix);
    out.push_str(replacement);
    out.push_str(suffix);
    out
}

/// Replace two non-overlapping regions (`first` before `second`) in one pass.
/// Each is a `(span, replacement)` pair.
fn splice_two(src: &str, first: (Span, &str), second: (Span, &str)) -> String {
    let (a, repl_a) = first;
    let (b, repl_b) = second;
    debug_assert!(
        a.end <= b.start,
        "splice_two: regions must be ordered and disjoint"
    );
    let (a_start, a_end) = (a.start as usize, a.end as usize);
    let (b_start, b_end) = (b.start as usize, b.end as usize);
    let mut out = String::with_capacity(src.len() + repl_a.len() + repl_b.len());
    out.push_str(&src[..a_start]);
    out.push_str(repl_a);
    out.push_str(&src[a_end..b_start]);
    out.push_str(repl_b);
    out.push_str(&src[b_end..]);
    out
}

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

    /// Concatenating every owned region's bytes reproduces the verbatim
    /// (sanitized) source, and the regions form a gap-free, ordered,
    /// non-overlapping cover.
    fn assert_tiling(src: &str) {
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let verbatim = tree.to_source_verbatim();
        let regions = tree.regions();

        if verbatim.is_empty() {
            assert!(regions.is_empty(), "empty source must yield no regions");
            return;
        }

        assert_eq!(regions[0].span.start, 0, "tiling must start at 0");
        assert_eq!(
            regions.last().unwrap().span.end as usize,
            verbatim.len(),
            "tiling must end at the source length",
        );
        for pair in regions.windows(2) {
            assert_eq!(
                pair[0].span.end, pair[1].span.start,
                "regions must be contiguous with no gap/overlap",
            );
            assert!(
                pair[0].span.start < pair[0].span.end,
                "regions must be non-empty",
            );
        }
        let rebuilt: String = regions
            .iter()
            .map(|r| &verbatim[r.span.start as usize..r.span.end as usize])
            .collect();
        assert_eq!(
            rebuilt, verbatim,
            "region concatenation must equal verbatim"
        );

        // Identity splice of every region reproduces the verbatim source.
        for r in &regions {
            let same = &verbatim[r.span.start as usize..r.span.end as usize];
            assert_eq!(
                tree.splice(*r, same).unwrap(),
                verbatim,
                "identity splice of {:?} must be the verbatim source",
                r.role,
            );
        }
    }

    /// Find the first region with the given role.
    fn role_of(src: &str, role: RegionRole) -> Region {
        let doc = Document::new(src);
        let tree = doc.snapshot();
        tree.regions()
            .into_iter()
            .find(|r| r.role == role)
            .unwrap_or_else(|| panic!("no {role:?} region in {src:?}"))
    }

    #[test]
    fn empty_source_has_no_regions() {
        assert_tiling("");
    }

    #[test]
    fn plain_text_is_one_direct_interstitial() {
        assert_tiling("ただの本文です。");
        let doc = Document::new("ただの本文です。");
        let tree = doc.snapshot();
        let regions = tree.regions();
        assert_eq!(regions.len(), 1);
        assert_eq!(regions[0].role, RegionRole::Interstitial);
        assert_eq!(regions[0].safety, SpliceSafety::Direct);
    }

    #[test]
    fn ruby_is_direct_and_self_contained() {
        assert_tiling("|青梅《おうめ》の実");
        let r = role_of("|青梅《おうめ》の実", RegionRole::Ruby);
        assert_eq!(r.safety, SpliceSafety::Direct);
    }

    #[test]
    fn reclaimed_forward_is_direct() {
        assert_tiling("青空[#「青空」に傍点]の下");
        let r = role_of("青空[#「青空」に傍点]の下", RegionRole::ForwardReclaimed);
        assert_eq!(r.safety, SpliceSafety::Direct);
    }

    #[test]
    fn referenced_forward_is_coupled() {
        let src = "青空がひろがる、その[#「青空」に傍点]";
        assert_tiling(src);
        let r = role_of(src, RegionRole::ForwardReferenced);
        assert_eq!(
            r.safety,
            SpliceSafety::Coupled(CoupledKind::ForwardReference)
        );
    }

    /// E1-1: a no-referent forward ([`ForwardOrigin::SelfContained`]) lives
    /// wholly inside its region (no upstream copy), so it classifies `Direct` —
    /// like `ForwardReclaimed` but with no reclaimed prefix. Constructed
    /// directly because no source produces this origin until E1-2/E1-3.
    #[test]
    fn self_contained_forward_is_direct() {
        use crate::syntax::ForwardAttr;
        use crate::syntax::alloc::Allocator;

        let mut a = Allocator::new();
        let t = a.content_plain("X");
        let node = a.forward_format(ForwardAttr::Bold, t, ForwardOrigin::SelfContained);
        assert_eq!(
            classify_node_ref(NodeRef::Inline(node)),
            (RegionRole::ForwardSelfContained, SpliceSafety::Direct),
        );
    }

    /// E1-4: a no-referent forward heading (`[#「序章」は中見出し]` with no
    /// earlier 序章) owns its target bytes, so it classifies `Direct` — the
    /// heading analogue of `self_contained_forward_is_direct`. `assert_tiling`
    /// confirms its identity splice round-trips through the Direct path.
    #[test]
    fn self_contained_heading_is_direct() {
        let src = "本文[#「序章」は中見出し]";
        assert_tiling(src);
        let r = role_of(src, RegionRole::HeadingSelfContained);
        assert_eq!(r.safety, SpliceSafety::Direct);
    }

    #[test]
    fn container_markers_are_coupled() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        assert_tiling(src);
        let open = role_of(src, RegionRole::ContainerOpen);
        assert_eq!(open.safety, SpliceSafety::Coupled(CoupledKind::Container));
        let close = role_of(src, RegionRole::ContainerClose);
        assert_eq!(close.safety, SpliceSafety::Coupled(CoupledKind::Container));
    }

    #[test]
    fn gaiji_is_direct() {
        assert_tiling("※[#「さんずい+垂」、第3水準1-86-69]");
        let r = role_of("※[#「さんずい+垂」、第3水準1-86-69]", RegionRole::Gaiji);
        assert_eq!(r.safety, SpliceSafety::Direct);
    }

    #[test]
    fn direct_splice_replaces_only_the_region() {
        // A real non-identity minimal-diff edit on a Direct (Reclaimed) node.
        let src = "青空[#「青空」に傍点]の下を歩く";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let region = role_of(src, RegionRole::ForwardReclaimed);
        let spliced = tree
            .splice(region, "海[#「海」に傍点]")
            .expect("Reclaimed forward is Direct");
        assert_eq!(spliced, "海[#「海」に傍点]の下を歩く");
    }

    #[test]
    fn coupling_pairs_container_markers() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let open = role_of(src, RegionRole::ContainerOpen);
        let c = tree.coupling(open).expect("container open is coupled");
        assert_eq!(c.kind, CoupledKind::Container);
        assert_eq!(c.primary, open.span);
        // The partner is the close marker; it sits after the open.
        assert!(c.partner.start > c.primary.start);
        let close = role_of(src, RegionRole::ContainerClose);
        assert_eq!(c.partner, close.span);
    }

    #[test]
    fn container_kind_change_rewrites_both_markers() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let open = role_of(src, RegionRole::ContainerOpen);
        let spliced = tree
            .splice(open, "[#ここから罫囲み]")
            .expect("kind change is verifiable");
        assert!(spliced.contains("[#ここから罫囲み]"));
        assert!(spliced.contains("[#罫囲み終わり]"));
        assert!(!spliced.contains("字下げ"));
        // Body is preserved verbatim.
        assert!(spliced.contains("本文"));
        // And it re-parses to a balanced 罫囲み container.
        let rt = Document::new(spliced.as_str());
        let rtree = rt.snapshot();
        assert!(
            rtree
                .regions()
                .iter()
                .any(|r| r.role == RegionRole::ContainerOpen)
        );
    }

    #[test]
    fn container_amount_change_touches_only_the_open() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let open = role_of(src, RegionRole::ContainerOpen);
        let spliced = tree
            .splice(open, "[#ここから4字下げ]")
            .expect("amount change is verifiable");
        assert!(spliced.contains("[#ここから4字下げ]"));
        // The close keyword is unchanged (字下げ終わり carries no amount).
        assert!(spliced.contains("[#ここで字下げ終わり]"));
    }

    #[test]
    fn mismatched_container_pair_identity_is_verbatim() {
        // A pre-existing family mismatch (open 字下げ, close 地付き) must survive
        // an identity splice of either marker unchanged — the splice must not
        // "fix" the mismatch by rewriting the close to the open's family.
        assert_tiling("\n[#ここから2字下げ]\n本文\n[#ここで地付き終わり]\n");
    }

    #[test]
    fn container_delete_drops_both_markers() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let open = role_of(src, RegionRole::ContainerOpen);
        let spliced = tree.splice(open, "").expect("delete is coherent");
        assert!(!spliced.contains("字下げ"));
        assert!(spliced.contains("本文"));
        assert!(spliced.contains(""));
        assert!(spliced.contains(""));
    }

    #[test]
    fn referenced_forward_attribute_change_is_coherent() {
        // Changing 傍点 → 傍線 keeps the same target, so the forward re-forms.
        let src = "青空がひろがる、その[#「青空」に傍点]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        let spliced = tree
            .splice(r, "[#「青空」に傍線]")
            .expect("attribute-only change keeps the forward");
        assert!(spliced.starts_with("青空がひろがる、その"));
        assert!(spliced.ends_with("[#「青空」に傍線]"));
    }

    #[test]
    fn referenced_forward_target_change_is_coupled() {
        // Changing the target rewrites BOTH the bracket and the unique upstream
        // literal so the reference stays in sync.
        let src = "青空がひろがる、その[#「青空」に傍点]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        let spliced = tree
            .splice(r, "[#「海」に傍点]")
            .expect("target change is a coupled edit");
        assert_eq!(spliced, "海がひろがる、その[#「海」に傍点]");
        // It re-parses to a forward reference again (now to 海).
        let rt = Document::new(spliced.as_str());
        assert!(
            rt.snapshot()
                .regions()
                .iter()
                .any(|r| r.role == RegionRole::ForwardReferenced)
        );
    }

    #[test]
    fn referenced_forward_emphasis_target_change_is_coupled() {
        // Emphasis forward references take the same coupled path as bouten.
        // Regression: changing the target must rewrite BOTH the bracket and the
        // unique upstream literal. The minimal single-region verify context
        // (`<old_target><new bracket>`) re-parses the new target with no
        // referent — a `SelfContained` forward — which must NOT be accepted as a
        // re-formation, or the upstream rewrite is silently skipped.
        let src = "青空がひろがる、その[#「青空」は太字]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        let spliced = tree
            .splice(r, "[#「海」は太字]")
            .expect("emphasis target change is a coupled edit");
        assert_eq!(spliced, "海がひろがる、その[#「海」は太字]");
    }

    #[test]
    fn heading_hint_target_change_is_coupled() {
        // E1-4 regression (the heading analogue of the emphasis case above): a
        // referent-present heading hint's target change must rewrite BOTH the
        // bracket and the unique upstream referent. The minimal single-region
        // verify context re-parses the new target with no referent — a
        // self-contained `HeadingHint` — which must NOT be accepted as a
        // re-formation, or the upstream rewrite is silently skipped.
        let src = "序章、その[#「序章」は中見出し]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::HeadingHint);
        assert_eq!(r.safety, SpliceSafety::Coupled(CoupledKind::HeadingHint));
        let spliced = tree
            .splice(r, "[#「海」は中見出し]")
            .expect("heading target change is a coupled edit");
        assert_eq!(spliced, "海、その[#「海」は中見出し]");
    }

    #[test]
    fn ambiguous_referent_target_change_declines() {
        // 青空 appears twice upstream — no unique referent, so a target change
        // is honestly declined rather than guessing which copy to rewrite.
        let src = "青空と青空、その[#「青空」に傍点]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        let err = tree
            .splice(r, "[#「海」に傍点]")
            .expect_err("ambiguous referent declines");
        assert!(matches!(err, SpliceError::Unverifiable { .. }));
    }

    #[test]
    fn unique_upstream_plain_requires_one_literal_region() {
        let plain_source = "青空、その";
        let plain = Document::new(plain_source).snapshot();
        assert_eq!(
            plain.unique_upstream_plain(
                u32::try_from(plain_source.len()).expect("test source length fits u32"),
                "青空"
            ),
            Some(Span::new(
                0,
                u32::try_from("青空".len()).expect("test target length fits u32")
            ))
        );

        let ruby_source = "|青空《あおぞら》その";
        let ruby = Document::new(ruby_source).snapshot();
        assert_eq!(
            ruby.unique_upstream_plain(
                u32::try_from(ruby_source.len()).expect("test source length fits u32"),
                "青空"
            ),
            None
        );

        let crossing_source = "青|空《そら》後";
        let crossing = Document::new(crossing_source).snapshot();
        assert_eq!(
            crossing.unique_upstream_plain(
                u32::try_from(crossing_source.len()).expect("test source length fits u32"),
                "青|"
            ),
            None
        );
    }

    #[test]
    fn multi_target_forward_identity_is_a_noop() {
        // A 、-joined multi-target forward (`「A」「B」`) is `Referenced`; its
        // canonical target lowers to a single plain run ("A、B"), so its
        // identity splice re-forms through the scoped single-region verify and
        // is a no-op. `assert_tiling` runs the real splice machinery on every
        // region, pinning the identity invariant for this trickiest shape.
        assert_tiling("AとB[#「A」「B」に傍点]");
    }

    #[test]
    fn multi_target_forward_target_change_declines() {
        // Changing the target of a multi-target forward is genuinely
        // irreducible: the canonical "A、B" is not a contiguous source substring
        // (the source reads "AとB"), so the upstream literal cannot be located
        // and the edit is honestly declined rather than guessed.
        let src = "AとB[#「A」「B」に傍点]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        assert_eq!(
            r.safety,
            SpliceSafety::Coupled(CoupledKind::ForwardReference)
        );
        let err = tree
            .splice(r, "[#「海」に傍点]")
            .expect_err("a multi-segment target change is irreducible");
        assert!(matches!(err, SpliceError::Unverifiable { .. }));
    }

    #[test]
    fn region_at_finds_node_and_gap() {
        let src = "あ|青梅《おうめ》い";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let head = tree.region_at(SourceOffset::new(0)).unwrap();
        assert_eq!(head.role, RegionRole::Interstitial);
        assert_eq!(head.span.start, 0);
        let ruby_off = SourceOffset::new(tree.regions()[1].span.start);
        let mid = tree.region_at(ruby_off).unwrap();
        assert_eq!(mid.role, RegionRole::Ruby);
        assert!(
            tree.region_at(SourceOffset::new(
                u32::try_from(tree.normalized_source().len()).unwrap()
            ))
            .is_none(),
        );
    }

    /// The `Display` impl must emit a specific, non-empty diagnostic for each
    /// variant — pins the whole `fmt` body against a `Ok(Default::default())`
    /// (empty-string) replacement.
    #[test]
    fn splice_error_display_is_specific_and_nonempty() {
        let unverifiable = SpliceError::Unverifiable {
            role: RegionRole::ForwardReferenced,
            kind: CoupledKind::ForwardReference,
        };
        let s = unverifiable.to_string();
        assert!(s.contains("ForwardReferenced"), "got {s:?}");
        assert!(s.contains("ForwardReference"), "got {s:?}");
        assert!(s.contains("could not be verified"), "got {s:?}");
    }

    /// Pin the `(RegionRole, SpliceSafety)` `classify_node_ref` assigns to every
    /// leaf variant.
    #[test]
    fn classify_pins_every_leaf_variant() {
        use crate::syntax::alloc::Allocator;
        use crate::syntax::{DirectiveKind, HeadingKind, HeadingStyle, LineFormat, SectionKind};

        let mut a = Allocator::new();
        let heading_text = a.content_plain("");
        let heading = a.aozora_heading(HeadingKind::Large, HeadingStyle::Standard, heading_text);
        let aq = a.content_plain("重要");
        let angle_quote = a.angle_quote(aq);
        let kaeriten = a.kaeriten("(レ)");
        let illustration = a.sashie_general("fig.png", "", None);
        let directive_payload = a.make_directive("[#ママ]", DirectiveKind::Sic);
        let directive = a.annotation(directive_payload);
        let line = a.line(LineFormat::Indent {
            amount: 2,
            end_offset: None,
        });
        let section_break = a.section_break(SectionKind::Kaicho);
        let page_break = a.page_break();
        let body_end = a.body_end();
        let forced_break = a.forced_break();
        let cases: [(Node, RegionRole, SpliceSafety); 10] = [
            (heading, RegionRole::Heading, SpliceSafety::Direct),
            (angle_quote, RegionRole::AngleQuote, SpliceSafety::Direct),
            (kaeriten, RegionRole::Kaeriten, SpliceSafety::Direct),
            (illustration, RegionRole::Illustration, SpliceSafety::Direct),
            (line, RegionRole::Line, SpliceSafety::Direct),
            (page_break, RegionRole::PageBreak, SpliceSafety::Direct),
            (
                section_break,
                RegionRole::SectionBreak,
                SpliceSafety::Direct,
            ),
            (body_end, RegionRole::BodyEnd, SpliceSafety::Direct),
            (forced_break, RegionRole::ForcedBreak, SpliceSafety::Direct),
            (directive, RegionRole::Directive, SpliceSafety::Direct),
        ];
        for (node, role, safety) in cases {
            assert_eq!(
                classify_node_ref(NodeRef::Inline(node)),
                (role, safety),
                "classify mismatch for {role:?}",
            );
        }
    }

    /// A coupled heading hint re-forms as a referent-bearing hint **or** a
    /// promoted heading — the `||` disjunct (an `&&` here can never
    /// hold, so both true cases would collapse to `false`).
    #[test]
    fn reparsed_in_family_heading_hint_accepts_hint_or_promoted_heading() {
        use crate::syntax::alloc::Allocator;
        use crate::syntax::{HeadingKind, HeadingStyle};

        let mut a = Allocator::new();
        let text = a.content_plain("");
        let promoted = a.aozora_heading(HeadingKind::Large, HeadingStyle::Standard, text);
        let hint = a.heading_hint(HeadingKind::Medium, HeadingStyle::Standard, "序章", false);
        let hint_sc = a.heading_hint(HeadingKind::Medium, HeadingStyle::Standard, "序章", true);

        // Promoted heading: the second (`Heading`) disjunct.
        assert!(reparsed_in_family(
            NodeRef::Inline(promoted),
            CoupledKind::HeadingHint
        ));
        // Referent-bearing hint: the first disjunct.
        assert!(reparsed_in_family(
            NodeRef::Inline(hint),
            CoupledKind::HeadingHint
        ));
        // A self-contained hint owns its target — not a re-formation.
        assert!(!reparsed_in_family(
            NodeRef::Inline(hint_sc),
            CoupledKind::HeadingHint
        ));
    }

    /// An interstitial gap region spans `(previous node end .. next node start)`.
    /// Pins the `nodes[next_idx - 1]` index against `+ 1` / `/ 1`,
    /// which would read a different node's end. Three nodes so `next_idx + 1`
    /// stays in bounds (an in-bounds wrong value, not a panic).
    #[test]
    fn region_at_gap_start_is_previous_node_end() {
        let src = "あ|青梅《おうめ》い|里芋《さといも》う|大豆《だいず》え";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let regions = tree.regions();
        // Layout: [あ] [ruby] [い] [ruby] [う] [ruby] [え]; the gap between the
        // first two rubies is regions[2].
        let gap = regions[2];
        assert_eq!(gap.role, RegionRole::Interstitial);
        let got = tree.region_at(SourceOffset::new(gap.span.start)).unwrap();
        assert_eq!(
            got.span, gap.span,
            "gap must span (prev node end .. next node start)",
        );
    }

    /// A non-container coupled region (a forward reference) resolves its upstream
    /// partner — pins the `Coupled(kind)` arm (its deletion drops to
    /// `_ => None`). The upstream `青空` begins after `まず` (offset 6), so this
    /// also pins `at = from + rel` against `from * rel` (which would
    /// mislocate the occurrence to offset 0 and then read it as ambiguous).
    #[test]
    fn coupling_of_forward_reference_returns_upstream_partner() {
        let src = "まず青空がひろがる、その[#「青空」に傍点]";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let r = role_of(src, RegionRole::ForwardReferenced);
        let c = tree.coupling(r).expect("forward reference is coupled");
        assert_eq!(c.kind, CoupledKind::ForwardReference);
        assert_eq!(c.primary, r.span);
        assert_eq!(c.partner.start, 6, "partner starts after まず, not at 0");
        let partner_text =
            &tree.normalized_source()[c.partner.start as usize..c.partner.end as usize];
        assert_eq!(partner_text, "青空");
    }

    /// A container **close** marker couples back to its **open** — pins the
    /// `span == close_span` disjunct (an `!=` there makes the close
    /// query never match its own pair, returning `None`).
    #[test]
    fn coupling_of_container_close_returns_open_partner() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let close = role_of(src, RegionRole::ContainerClose);
        let c = tree.coupling(close).expect("close couples to its open");
        assert_eq!(c.kind, CoupledKind::Container);
        assert_eq!(c.primary, close.span);
        let open = role_of(src, RegionRole::ContainerOpen);
        assert_eq!(c.partner, open.span);
        assert!(c.partner.start < c.primary.start, "open precedes close");
    }

    /// `block_open_format_at` recovers the open format only when the offset is
    /// the node's exact start — pins the `sn.source_span.start == start` guard
    /// against `true`, which would accept an interior offset.
    #[test]
    fn block_open_format_at_requires_offset_at_node_start() {
        let src = "\n[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n";
        let doc = Document::new(src);
        let tree = doc.snapshot();
        let open = role_of(src, RegionRole::ContainerOpen);
        assert!(block_open_format_at(&tree, open.span.start).is_some());
        // Interior offset (past the leading `[`): node_at_source still returns
        // the BlockOpen, but its span.start != off, so the guard must reject.
        assert!(block_open_format_at(&tree, open.span.start + 3).is_none());
    }

    /// `lone_open_format` accepts a marker only when its first source node sits
    /// at offset 0 — pins the `sn.source_span.start == 0` guard
    /// against `true`, which would accept a marker buried after leading text.
    #[test]
    fn lone_open_format_requires_first_node_at_offset_zero() {
        assert!(lone_open_format("[#ここから2字下げ]").is_some());
        assert!(lone_open_format("前置き\n[#ここから2字下げ]").is_none());
    }

    /// `marker_in_family` requires the first node to be at offset 0 **and** in
    /// the family — pins the `-> true` body and the `&&` (which an `||`
    /// weakens). Leading text makes offset-0 false while family
    /// stays true, isolating the conjunction.
    #[test]
    fn marker_in_family_needs_container_at_offset_zero() {
        assert!(marker_in_family(
            "[#ここから2字下げ]",
            CoupledKind::Container
        ));
        // start != 0 but family true → only the `&&` (not `||`) rejects it.
        assert!(!marker_in_family(
            "\n[#ここから2字下げ]",
            CoupledKind::Container
        ));
        // No leading node at all.
        assert!(!marker_in_family("ただの本文", CoupledKind::Container));
    }

    /// Pin every family arm and origin/self-contained guard of
    /// `window_reforms_coupled`: each construct family must re-form only with a
    /// matching target, and a `SelfContained` / `self_contained` re-parse must
    /// **not** count.
    #[test]
    fn window_reforms_coupled_pins_families_and_guards() {
        // Referent-bearing forward re-forms with the matching target.
        assert!(window_reforms_coupled(
            "海がひろがる、その[#「海」に傍点]",
            CoupledKind::ForwardReference,
            "",
        ));
        // A `SelfContained` forward (no upstream referent) is NOT a re-formation
        // — kills the `f.origin != SelfContained` guard -> true.
        assert!(!window_reforms_coupled(
            "[#「海」に傍点]",
            CoupledKind::ForwardReference,
            "",
        ));
        // Referent-bearing heading hint re-forms.
        assert!(window_reforms_coupled(
            "海、その[#「海」は中見出し]",
            CoupledKind::HeadingHint,
            "",
        ));
        // A `self_contained` hint is NOT a re-formation — kills the
        // `!h.self_contained` guard -> true.
        assert!(!window_reforms_coupled(
            "[#「海」は中見出し]",
            CoupledKind::HeadingHint,
            "",
        ));
        // A promoted heading is an equally valid re-formation — kills deletion of
        // the `(HeadingHint, Heading)` arm.
        assert!(window_reforms_coupled(
            "\n[#「海」は中見出し]",
            CoupledKind::HeadingHint,
            "",
        ));
        // A margin note re-forms on its base — kills deletion of the
        // `(MarginNote, MarginNote)` arm.
        assert!(window_reforms_coupled(
            "青空[#「青空」の左に「あお」の注記]",
            CoupledKind::MarginNote,
            "青空",
        ));
        // A non-matching window never re-forms — kills the `-> true` body.
        assert!(!window_reforms_coupled(
            "ただの本文",
            CoupledKind::ForwardReference,
            "",
        ));
        // A right family but wrong target also fails.
        assert!(!window_reforms_coupled(
            "海がひろがる、その[#「海」に傍点]",
            CoupledKind::ForwardReference,
            "",
        ));
    }
}