eure-document 0.1.9

Value type for Eure
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
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
pub mod constructor;
pub mod interpreter_sink;
pub mod node;
pub mod source_constructor;

use crate::document::node::{NodeArray, NodeTuple};
use crate::map::PartialNodeMap;
use crate::prelude_internal::*;
use crate::value::PartialObjectKey;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(pub usize);

#[derive(Debug, Clone)]
pub struct EureDocument {
    pub(crate) root: NodeId,
    nodes: Vec<Node>,
}

#[derive(Debug, PartialEq, thiserror::Error, Clone)]
#[error("Insert error: {kind} at {path}")]
pub struct InsertError {
    pub kind: InsertErrorKind,
    pub path: EurePath,
}

#[derive(Debug, PartialEq, thiserror::Error, Clone)]
pub enum InsertErrorKind {
    #[error("Already assigned")]
    AlreadyAssigned { key: ObjectKey },
    #[error("Extension already assigned: {identifier}")]
    AlreadyAssignedExtension { identifier: Identifier },
    #[error("Expected array")]
    ExpectedArray,
    #[error("Array index invalid: expected {expected_index} but got {index}")]
    ArrayIndexInvalid { index: usize, expected_index: usize },
    #[error("Expected map")]
    ExpectedMap,
    #[error("Expected tuple")]
    ExpectedTuple,
    #[error("Tuple index invalid: expected {expected_index} but got {index}")]
    TupleIndexInvalid { index: u8, expected_index: usize },
    #[error("Binding target already has a value")]
    BindingTargetHasValue,
    #[error("Scope error: {0}")]
    ScopeError(#[from] constructor::ScopeError),
    #[error("Constructor error: {0}")]
    ConstructorError(#[from] ConstructorError),
    #[error(
        "`[^]` has no prior push in the current block scope for the target array (node {array_node_id:?})"
    )]
    ArrayCurrentOutOfScope { array_node_id: NodeId },
}

/// Protocol errors for SourceConstructor operations.
#[derive(Debug, PartialEq, thiserror::Error, Clone)]
pub enum ConstructorError {
    #[error("set_block_value called without a preceding bind operation")]
    MissingBindBeforeSetBlockValue,
    #[error("end_binding_value called without a preceding bind operation")]
    MissingBindBeforeEndBindingValue,
    #[error("end_binding_block called without a preceding end_eure_block")]
    MissingEndEureBlockBeforeEndBindingBlock,
    #[error("end_section_block called without a preceding end_eure_block")]
    MissingEndEureBlockBeforeEndSectionBlock,
    #[error("end_eure_block called but builder stack is not in EureBlock state")]
    InvalidBuilderStackForEndEureBlock,
    #[error("end_section_items called but builder stack is not in SectionItems state")]
    InvalidBuilderStackForEndSectionItems,
    #[error("ArrayIndex must follow a key segment; standalone [] is not valid")]
    StandaloneArrayIndex,
}

impl Default for EureDocument {
    fn default() -> Self {
        Self::new()
    }
}

impl PartialEq for EureDocument {
    fn eq(&self, other: &Self) -> bool {
        self.nodes_equal(self.root, other, other.root)
    }
}

impl EureDocument {
    /// Returns the total number of nodes in this document.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Compare two nodes structurally, ignoring NodeId values
    fn nodes_equal(&self, id1: NodeId, other: &EureDocument, id2: NodeId) -> bool {
        let node1 = &self.nodes[id1.0];
        let node2 = &other.nodes[id2.0];

        // Compare extensions
        if node1.extensions.len() != node2.extensions.len() {
            return false;
        }

        for (key1, &child_id1) in &node1.extensions {
            match node2.extensions.get(key1) {
                Some(&child_id2) => {
                    if !self.nodes_equal(child_id1, other, child_id2) {
                        return false;
                    }
                }
                None => return false,
            }
        }

        // Compare content
        self.node_values_equal(&node1.content, other, &node2.content)
    }

    /// Compare two NodeValues structurally
    fn node_values_equal(
        &self,
        value1: &NodeValue,
        other: &EureDocument,
        value2: &NodeValue,
    ) -> bool {
        match (value1, value2) {
            (NodeValue::Hole(l1), NodeValue::Hole(l2)) => l1 == l2,
            (NodeValue::Primitive(p1), NodeValue::Primitive(p2)) => p1 == p2,
            (NodeValue::Array(arr1), NodeValue::Array(arr2)) => {
                self.node_arrays_equal(arr1, other, arr2)
            }
            (NodeValue::Tuple(tup1), NodeValue::Tuple(tup2)) => {
                self.node_tuples_equal(tup1, other, tup2)
            }
            (NodeValue::Map(map1), NodeValue::Map(map2)) => self.node_maps_equal(map1, other, map2),
            (NodeValue::PartialMap(pm1), NodeValue::PartialMap(pm2)) => {
                self.node_partial_maps_equal(pm1, other, pm2)
            }
            _ => false,
        }
    }

    fn node_arrays_equal(&self, arr1: &NodeArray, other: &EureDocument, arr2: &NodeArray) -> bool {
        if arr1.len() != arr2.len() {
            return false;
        }

        for (child_id1, child_id2) in arr1.iter().zip(arr2.iter()) {
            if !self.nodes_equal(*child_id1, other, *child_id2) {
                return false;
            }
        }

        true
    }

    fn node_tuples_equal(&self, tup1: &NodeTuple, other: &EureDocument, tup2: &NodeTuple) -> bool {
        if tup1.len() != tup2.len() {
            return false;
        }

        for (child_id1, child_id2) in tup1.iter().zip(tup2.iter()) {
            if !self.nodes_equal(*child_id1, other, *child_id2) {
                return false;
            }
        }

        true
    }

    fn node_partial_maps_equal(
        &self,
        pm1: &PartialNodeMap,
        other: &EureDocument,
        pm2: &PartialNodeMap,
    ) -> bool {
        if pm1.len() != pm2.len() {
            return false;
        }
        for ((key1, &child_id1), (key2, &child_id2)) in pm1.iter().zip(pm2.iter()) {
            if key1 != key2 {
                return false;
            }
            if !self.nodes_equal(child_id1, other, child_id2) {
                return false;
            }
        }
        true
    }

    fn node_maps_equal(&self, map1: &NodeMap, other: &EureDocument, map2: &NodeMap) -> bool {
        if map1.len() != map2.len() {
            return false;
        }

        for (key1, &child_id1) in map1.iter() {
            match map2.get(key1) {
                Some(&child_id2) => {
                    if !self.nodes_equal(child_id1, other, child_id2) {
                        return false;
                    }
                }
                None => return false,
            }
        }

        true
    }

    pub fn new() -> Self {
        Self {
            root: NodeId(0),
            nodes: vec![Node {
                content: NodeValue::hole(),
                extensions: Map::new(),
            }],
        }
    }

    pub fn new_empty() -> Self {
        Self {
            root: NodeId(0),
            nodes: vec![Node {
                content: NodeValue::Map(Default::default()),
                extensions: Map::new(),
            }],
        }
    }

    pub fn new_primitive(value: PrimitiveValue) -> Self {
        Self {
            root: NodeId(0),
            nodes: vec![Node {
                content: NodeValue::Primitive(value),
                extensions: Map::new(),
            }],
        }
    }

    pub fn root(&self) -> &Node {
        &self.nodes[self.root.0]
    }

    pub fn get_root_id(&self) -> NodeId {
        self.root
    }

    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id.0]
    }

    pub fn get_node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id.0)
    }

    pub fn node_mut(&mut self, id: NodeId) -> &mut Node {
        &mut self.nodes[id.0]
    }

    pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
        self.nodes.get_mut(id.0)
    }

    pub fn create_node(&mut self, new: NodeValue) -> NodeId {
        self.nodes.push(Node {
            content: new,
            extensions: Map::new(),
        });
        NodeId(self.nodes.len() - 1)
    }

    pub fn create_node_uninitialized(&mut self) -> NodeId {
        self.create_node(NodeValue::hole())
    }

    /// Set the content of a node directly
    pub fn set_content(&mut self, node_id: NodeId, content: NodeValue) {
        self.nodes[node_id.0].content = content;
    }

    pub fn add_child_by_segment(
        &mut self,
        segment: PathSegment,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        match segment {
            PathSegment::Ident(identifier) => {
                let key = ObjectKey::String(identifier.into_string());
                // If parent is already a PartialMap, add as resolved key there
                if matches!(self.node(parent_node_id).content, NodeValue::PartialMap(_)) {
                    self.add_partial_map_child(PartialObjectKey::from(key), parent_node_id)
                } else {
                    self.add_map_child(key, parent_node_id)
                }
            }
            PathSegment::Value(object_key) => {
                if matches!(self.node(parent_node_id).content, NodeValue::PartialMap(_)) {
                    self.add_partial_map_child(PartialObjectKey::from(object_key), parent_node_id)
                } else {
                    self.add_map_child(object_key, parent_node_id)
                }
            }
            PathSegment::PartialValue(key) => self.add_partial_map_child(key, parent_node_id),
            PathSegment::Extension(identifier) => self.add_extension(identifier, parent_node_id),
            PathSegment::TupleIndex(index) => self.add_tuple_element(index, parent_node_id),
            PathSegment::ArrayIndex(ArrayIndexKind::Push) => {
                self.add_array_element(None, parent_node_id)
            }
            PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)) => {
                self.add_array_element(Some(index), parent_node_id)
            }
            PathSegment::ArrayIndex(ArrayIndexKind::Current) => {
                // `[^]` cannot create new elements; the constructor must intercept this
                // before reaching add_child_by_segment. If we get here, the array had no
                // prior push in the current block scope.
                self.node(parent_node_id)
                    .as_array()
                    .ok_or(InsertErrorKind::ExpectedArray)?;
                Err(InsertErrorKind::ArrayCurrentOutOfScope {
                    array_node_id: parent_node_id,
                })
            }
            PathSegment::HoleKey(label) => {
                self.add_partial_map_child(PartialObjectKey::Hole(label), parent_node_id)
            }
        }
    }

    /// Add a child node to a PartialMap, upgrading from Hole or Map if necessary.
    pub fn add_partial_map_child(
        &mut self,
        key: PartialObjectKey,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        let pm = node.require_partial_map()?;
        pm.push(key, node_id);
        Ok(NodeMut::new(self, node_id))
    }

    pub fn add_map_child(
        &mut self,
        object_key: ObjectKey,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        let map = node.require_map()?;
        map.add(object_key, node_id)?;
        Ok(NodeMut::new(self, node_id))
    }

    pub fn add_extension(
        &mut self,
        identifier: Identifier,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        if node.extensions.contains_key(&identifier) {
            return Err(InsertErrorKind::AlreadyAssignedExtension { identifier });
        }
        node.extensions.insert(identifier, node_id);
        Ok(NodeMut::new(self, node_id))
    }

    pub fn add_tuple_element(
        &mut self,
        index: u8,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        let tuple = node.require_tuple()?;
        tuple.add_at(index, node_id)?;
        Ok(NodeMut::new(self, node_id))
    }

    pub fn add_array_element(
        &mut self,
        index: Option<usize>,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        let array = node.require_array()?;
        if let Some(index) = index {
            array.add_at(index, node_id)?;
        } else {
            array.push(node_id)?;
        }
        Ok(NodeMut::new(self, node_id))
    }

    pub fn insert_array_element(
        &mut self,
        index: usize,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        let node_id = self.create_node_uninitialized();
        let node = self.node_mut(parent_node_id);
        let array = node.require_array()?;
        array.insert_at(index, node_id)?;
        Ok(NodeMut::new(self, node_id))
    }

    pub fn remove_map_child(
        &mut self,
        object_key: &ObjectKey,
        parent_node_id: NodeId,
    ) -> Result<Option<NodeId>, InsertErrorKind> {
        let node = self.node_mut(parent_node_id);
        let map = node.require_map()?;
        Ok(map.remove_ordered(object_key))
    }

    pub fn remove_extension(
        &mut self,
        identifier: &Identifier,
        parent_node_id: NodeId,
    ) -> Option<NodeId> {
        self.node_mut(parent_node_id)
            .extensions
            .remove_ordered(identifier)
    }

    pub fn remove_array_element(
        &mut self,
        index: usize,
        parent_node_id: NodeId,
    ) -> Result<Option<NodeId>, InsertErrorKind> {
        let node = self.node_mut(parent_node_id);
        let array = node.require_array()?;
        Ok(array.remove_at(index))
    }

    /// Resolves a path segment to a node ID, creating if necessary.
    ///
    /// This operation is idempotent for most segments, reusing existing nodes.
    /// Exception: `ArrayIndex(ArrayIndexKind::Push)` always creates a new array element (push operation).
    pub fn resolve_child_by_segment(
        &mut self,
        segment: PathSegment,
        parent_node_id: NodeId,
    ) -> Result<NodeMut<'_>, InsertErrorKind> {
        // 既存のノードを探す
        let node = self.node(parent_node_id);

        let existing = match &segment {
            PathSegment::Ident(identifier) => {
                let obj_key = ObjectKey::String(identifier.clone().into_string());
                // Check both Map and PartialMap
                node.as_map()
                    .and_then(|m| m.get(&obj_key))
                    .copied()
                    .or_else(|| {
                        node.as_partial_map()
                            .and_then(|pm| {
                                pm.find(&PartialObjectKey::String(identifier.clone().into_string()))
                            })
                            .copied()
                    })
            }
            PathSegment::Value(object_key) => {
                let partial_key = PartialObjectKey::from(object_key.clone());
                node.as_map()
                    .and_then(|m| m.get(object_key))
                    .copied()
                    .or_else(|| {
                        node.as_partial_map()
                            .and_then(|pm| pm.find(&partial_key))
                            .copied()
                    })
            }
            PathSegment::PartialValue(key) => node
                .as_partial_map()
                .and_then(|pm| pm.find(key))
                .copied()
                .or_else(|| {
                    ObjectKey::try_from(key.clone())
                        .ok()
                        .and_then(|object_key| node.as_map().and_then(|m| m.get(&object_key)))
                        .copied()
                }),
            PathSegment::Extension(identifier) => node.get_extension(identifier),
            PathSegment::TupleIndex(index) => node.as_tuple().and_then(|t| t.get(*index as usize)),
            PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)) => {
                node.as_array().and_then(|a| a.get(*index))
            }
            PathSegment::ArrayIndex(ArrayIndexKind::Push) => None, // push always creates new
            // `[^]` is resolved by the DocumentConstructor before reaching this point; here we
            // fall through so add_child_by_segment yields ArrayCurrentOutOfScope.
            PathSegment::ArrayIndex(ArrayIndexKind::Current) => None,
            PathSegment::HoleKey(label) => node
                .as_partial_map()
                .and_then(|pm| pm.find(&PartialObjectKey::Hole(label.clone())))
                .copied(),
        };

        // 既存ノードがあればそれを返す
        if let Some(node_id) = existing {
            return Ok(NodeMut::new(self, node_id));
        }

        // なければ作成
        self.add_child_by_segment(segment, parent_node_id)
    }

    /// Convert a subtree of a document to a standalone document.
    pub fn node_subtree_to_document(&self, node_id: NodeId) -> EureDocument {
        let mut result = EureDocument::new();
        let root_id = result.get_root_id();
        self.copy_subtree(node_id, &mut result, root_id);
        result
    }

    pub fn copy_subtree(&self, src_id: NodeId, dst: &mut EureDocument, dst_id: NodeId) {
        let src_node = self.node(src_id);

        // Copy content based on type. For containers, we must NOT clone the content
        // directly because it contains NodeIds from the source document. Instead,
        // create empty containers and populate with recursively copied children.
        match &src_node.content {
            NodeValue::Hole(label) => {
                dst.node_mut(dst_id).content = NodeValue::Hole(label.clone());
            }
            NodeValue::Primitive(p) => {
                dst.node_mut(dst_id).content = NodeValue::Primitive(p.clone());
            }
            NodeValue::Array(arr) => {
                dst.node_mut(dst_id).content = NodeValue::empty_array();
                for &child_src_id in arr.iter() {
                    if let Ok(result) = dst.add_array_element(None, dst_id) {
                        let child_dst_id = result.node_id;
                        self.copy_subtree(child_src_id, dst, child_dst_id);
                    }
                }
            }
            NodeValue::Tuple(tuple) => {
                dst.node_mut(dst_id).content = NodeValue::empty_tuple();
                for (idx, &child_src_id) in tuple.iter().enumerate() {
                    if let Ok(result) = dst.add_tuple_element(idx as u8, dst_id) {
                        let child_dst_id = result.node_id;
                        self.copy_subtree(child_src_id, dst, child_dst_id);
                    }
                }
            }
            NodeValue::Map(map) => {
                dst.node_mut(dst_id).content = NodeValue::empty_map();
                for (key, &child_src_id) in map.iter() {
                    if let Ok(result) = dst.add_map_child(key.clone(), dst_id) {
                        let child_dst_id = result.node_id;
                        self.copy_subtree(child_src_id, dst, child_dst_id);
                    }
                }
            }
            NodeValue::PartialMap(pm) => {
                dst.node_mut(dst_id).content = NodeValue::empty_partial_map();
                let entries: Vec<(PartialObjectKey, NodeId)> =
                    pm.iter().map(|(k, &v)| (k.clone(), v)).collect();
                for (key, child_src_id) in entries {
                    let child_dst_id = dst.create_node_uninitialized();
                    if let NodeValue::PartialMap(dst_pm) = &mut dst.node_mut(dst_id).content {
                        dst_pm.push(key, child_dst_id);
                    }
                    self.copy_subtree(child_src_id, dst, child_dst_id);
                }
            }
        }

        // Copy extensions recursively
        let extensions: Vec<_> = self
            .node(src_id)
            .extensions
            .iter()
            .map(|(k, v)| (k.clone(), *v))
            .collect();
        for (ext_name, ext_src_id) in extensions {
            if let Ok(result) = dst.add_extension(ext_name, dst_id) {
                let ext_dst_id = result.node_id;
                self.copy_subtree(ext_src_id, dst, ext_dst_id);
            }
        }
    }

    pub fn overwrite_subtree_from(
        &mut self,
        dst_id: NodeId,
        src_doc: &EureDocument,
        src_id: NodeId,
    ) {
        self.node_mut(dst_id).extensions = Map::new();
        src_doc.copy_subtree(src_id, self, dst_id);
    }
}

/// Commands
impl EureDocument {
    pub fn replace_with_primitive(&mut self, value: PrimitiveValue) -> Result<(), InsertErrorKind> {
        self.nodes.clear();
        self.nodes[self.root.0].content = NodeValue::Primitive(value);
        Ok(())
    }

    pub fn reset_as_map(&mut self) -> Result<(), InsertErrorKind> {
        self.nodes.clear();
        self.nodes[self.root.0].content = NodeValue::Map(Default::default());
        Ok(())
    }
}

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

    fn identifier(s: &str) -> Identifier {
        s.parse().unwrap()
    }

    #[test]
    fn test_add_map_child_success() {
        let mut doc = EureDocument::new();
        let map_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_map())
        };
        let key = ObjectKey::String("test_key".to_string());

        let child_id = doc
            .add_map_child(key.clone(), map_id)
            .expect("Failed to add map child")
            .node_id;

        let map = doc.node(map_id).as_map().expect("Expected map");
        assert_eq!(map.get(&key), Some(&child_id));
    }

    #[test]
    fn test_add_map_child_error_expected_map() {
        let mut doc = EureDocument::new();
        let primitive_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::Primitive(PrimitiveValue::Null))
        };
        let key = ObjectKey::String("test".to_string());

        let result = doc.add_map_child(key, primitive_id);
        assert_eq!(result.err(), Some(InsertErrorKind::ExpectedMap));
    }

    #[test]
    fn test_add_map_child_error_already_assigned() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let key = ObjectKey::String("test".to_string());

        let _result1 = doc
            .add_map_child(key.clone(), root_id)
            .expect("First add should succeed");

        let result2 = doc.add_map_child(key.clone(), root_id);
        assert_eq!(
            result2.err(),
            Some(InsertErrorKind::AlreadyAssigned { key })
        );
    }

    #[test]
    fn test_add_extension_success_multiple() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let id1 = identifier("ext1");
        let id2 = identifier("ext2");

        let node_id1 = doc
            .add_extension(id1.clone(), root_id)
            .expect("Failed to add extension")
            .node_id;

        let node_id2 = doc
            .add_extension(id2.clone(), root_id)
            .expect("Failed to add extension")
            .node_id;

        let node = doc.node(root_id);
        assert_eq!(node.extensions.get(&id1), Some(&node_id1));
        assert_eq!(node.extensions.get(&id2), Some(&node_id2));
    }

    #[test]
    fn test_add_extension_success() {
        let mut doc = EureDocument::new();
        let primitive_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::Primitive(PrimitiveValue::Null))
        };
        let identifier = identifier("ext");

        let node_id = doc
            .add_extension(identifier.clone(), primitive_id)
            .expect("Failed to add extension")
            .node_id;

        let node = doc.node(primitive_id);
        assert_eq!(node.extensions.get(&identifier), Some(&node_id));
    }

    #[test]
    fn test_add_extension_error_already_assigned() {
        let mut doc = EureDocument::new();
        let map_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_map())
        };
        let identifier = identifier("ext");

        let _result1 = doc
            .add_extension(identifier.clone(), map_id)
            .expect("First add should succeed");

        let result2 = doc.add_extension(identifier.clone(), map_id);
        assert_eq!(
            result2.err(),
            Some(InsertErrorKind::AlreadyAssignedExtension { identifier })
        );
    }

    #[test]
    fn test_add_tuple_element_success_index_0() {
        let mut doc = EureDocument::new();
        let tuple_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_tuple())
        };

        let node_id = doc
            .add_tuple_element(0, tuple_id)
            .expect("Failed to add tuple element")
            .node_id;

        let tuple = doc.node(tuple_id).as_tuple().expect("Expected tuple");
        assert_eq!(tuple.to_vec(), vec![node_id]);
    }

    #[test]
    fn test_add_tuple_element_success_sequential() {
        let mut doc = EureDocument::new();
        let tuple_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_tuple())
        };

        let node_id1 = doc
            .add_tuple_element(0, tuple_id)
            .expect("Failed to add tuple element")
            .node_id;

        let node_id2 = doc
            .add_tuple_element(1, tuple_id)
            .expect("Failed to add tuple element")
            .node_id;

        let tuple = doc.node(tuple_id).as_tuple().expect("Expected tuple");
        assert_eq!(tuple.to_vec(), vec![node_id1, node_id2]);
    }

    #[test]
    fn test_add_tuple_element_error_expected_tuple() {
        let mut doc = EureDocument::new();
        let map_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_map())
        };

        let result = doc.add_tuple_element(0, map_id);
        assert_eq!(result.err(), Some(InsertErrorKind::ExpectedTuple));
    }

    #[test]
    fn test_add_tuple_element_error_invalid_index() {
        let mut doc = EureDocument::new();
        let tuple_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_tuple())
        };

        let result = doc.add_tuple_element(1, tuple_id);
        assert_eq!(
            result.err(),
            Some(InsertErrorKind::TupleIndexInvalid {
                index: 1,
                expected_index: 0
            })
        );
    }

    #[test]
    fn test_add_array_element_success_push() {
        let mut doc = EureDocument::new();
        let array_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_array())
        };

        let node_id = doc
            .add_array_element(None, array_id)
            .expect("Failed to add array element")
            .node_id;

        let array = doc.node(array_id).as_array().expect("Expected array");
        assert_eq!(array.to_vec(), vec![node_id]);
    }

    #[test]
    fn test_add_array_element_success_at_index() {
        let mut doc = EureDocument::new();
        let array_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_array())
        };

        let node_id1 = doc
            .add_array_element(Some(0), array_id)
            .expect("Failed to add array element")
            .node_id;

        let node_id2 = doc
            .add_array_element(Some(1), array_id)
            .expect("Failed to add array element")
            .node_id;

        let array = doc.node(array_id).as_array().expect("Expected array");
        assert_eq!(array.to_vec(), vec![node_id1, node_id2]);
    }

    #[test]
    fn test_add_array_element_error_expected_array() {
        let mut doc = EureDocument::new();
        let map_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_map())
        };

        let result = doc.add_array_element(None, map_id);
        assert_eq!(result.err(), Some(InsertErrorKind::ExpectedArray));
    }

    #[test]
    fn test_add_array_element_error_invalid_index() {
        let mut doc = EureDocument::new();
        let array_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_array())
        };

        let result = doc.add_array_element(Some(1), array_id);
        assert_eq!(
            result.err(),
            Some(InsertErrorKind::ArrayIndexInvalid {
                index: 1,
                expected_index: 0
            })
        );
    }

    #[test]
    fn test_add_child_by_segment_ident() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let identifier = identifier("test");
        let segment = PathSegment::Ident(identifier.clone());

        let result = doc.add_child_by_segment(segment, root_id);
        assert!(result.is_ok());

        let map = doc.node(root_id).as_map().expect("Expected map");
        let key = ObjectKey::String(identifier.into_string());
        assert!(map.get(&key).is_some());
    }

    #[test]
    fn test_add_child_by_segment_value() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let key = ObjectKey::String("test".to_string());
        let segment = PathSegment::Value(key.clone());

        let result = doc.add_child_by_segment(segment, root_id);
        assert!(result.is_ok());

        let map = doc.node(root_id).as_map().expect("Expected map");
        assert!(map.get(&key).is_some());
    }

    #[test]
    fn test_add_child_by_segment_extension() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let identifier = identifier("ext");
        let segment = PathSegment::Extension(identifier.clone());

        let result = doc.add_child_by_segment(segment, root_id);
        assert!(result.is_ok());

        let node = doc.node(root_id);
        assert!(node.extensions.contains_key(&identifier));
    }

    #[test]
    fn test_add_child_by_segment_tuple_index() {
        let mut doc = EureDocument::new();
        let tuple_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_tuple())
        };
        let segment = PathSegment::TupleIndex(0);

        let result = doc.add_child_by_segment(segment, tuple_id);
        assert!(result.is_ok());

        let tuple = doc.node(tuple_id).as_tuple().expect("Expected tuple");
        assert_eq!(tuple.len(), 1);
    }

    #[test]
    fn test_add_child_by_segment_array_index_none() {
        let mut doc = EureDocument::new();
        let array_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_array())
        };
        let segment = PathSegment::ArrayIndex(ArrayIndexKind::Push);

        let result = doc.add_child_by_segment(segment, array_id);
        assert!(result.is_ok());

        let array = doc.node(array_id).as_array().expect("Expected array");
        assert_eq!(array.len(), 1);
    }

    #[test]
    fn test_add_child_by_segment_array_index_some() {
        let mut doc = EureDocument::new();
        let array_id = {
            let doc: &mut EureDocument = &mut doc;
            doc.create_node(NodeValue::empty_array())
        };
        let segment = PathSegment::ArrayIndex(ArrayIndexKind::Specific(0));

        let result = doc.add_child_by_segment(segment, array_id);
        assert!(result.is_ok());

        let array = doc.node(array_id).as_array().expect("Expected array");
        assert_eq!(array.len(), 1);
    }

    #[test]
    fn test_resolve_ident_idempotent() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let identifier = identifier("field");

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(PathSegment::Ident(identifier.clone()), root_id)
            .expect("First call failed")
            .node_id;

        // Second call - returns existing node
        let node_id2 = doc
            .resolve_child_by_segment(PathSegment::Ident(identifier), root_id)
            .expect("Second call failed")
            .node_id;

        assert_eq!(node_id1, node_id2);
    }

    #[test]
    fn test_resolve_value_idempotent() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let object_key = ObjectKey::String("key".to_string());

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(PathSegment::Value(object_key.clone()), root_id)
            .expect("First call failed")
            .node_id;

        // Second call - returns existing node
        let node_id2 = doc
            .resolve_child_by_segment(PathSegment::Value(object_key), root_id)
            .expect("Second call failed")
            .node_id;

        assert_eq!(node_id1, node_id2);
    }

    #[test]
    fn test_resolve_extension_idempotent() {
        let mut doc = EureDocument::new();
        let root_id = doc.get_root_id();
        let identifier = identifier("ext");

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(PathSegment::Extension(identifier.clone()), root_id)
            .expect("First call failed")
            .node_id;

        // Second call - returns existing node
        let node_id2 = doc
            .resolve_child_by_segment(PathSegment::Extension(identifier), root_id)
            .expect("Second call failed")
            .node_id;

        assert_eq!(node_id1, node_id2);
    }

    #[test]
    fn test_resolve_tuple_index_idempotent() {
        let mut doc = EureDocument::new();
        let parent_id = doc.create_node_uninitialized();

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(PathSegment::TupleIndex(0), parent_id)
            .expect("First call failed")
            .node_id;

        // Second call - returns existing node
        let node_id2 = doc
            .resolve_child_by_segment(PathSegment::TupleIndex(0), parent_id)
            .expect("Second call failed")
            .node_id;

        assert_eq!(node_id1, node_id2);
    }

    #[test]
    fn test_resolve_array_index_some_idempotent() {
        let mut doc = EureDocument::new();
        let parent_id = doc.create_node_uninitialized();

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(
                PathSegment::ArrayIndex(ArrayIndexKind::Specific(0)),
                parent_id,
            )
            .expect("First call failed")
            .node_id;

        // Second call - returns existing node
        let node_id2 = doc
            .resolve_child_by_segment(
                PathSegment::ArrayIndex(ArrayIndexKind::Specific(0)),
                parent_id,
            )
            .expect("Second call failed")
            .node_id;

        assert_eq!(node_id1, node_id2);
    }

    #[test]
    fn test_resolve_array_index_none_always_creates_new() {
        let mut doc = EureDocument::new();
        let parent_id = doc.create_node_uninitialized();

        // First call - creates new node
        let node_id1 = doc
            .resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Push), parent_id)
            .expect("First call failed")
            .node_id;

        // Second call - creates another new node (NOT idempotent)
        let node_id2 = doc
            .resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Push), parent_id)
            .expect("Second call failed")
            .node_id;

        // ArrayIndex(ArrayIndexKind::Push) always creates new nodes (push operation)
        assert_ne!(node_id1, node_id2);

        // Verify both nodes exist in array
        let array = doc.node(parent_id).as_array().expect("Expected array");
        assert_eq!(array.len(), 2);
        assert_eq!(array.get(0).unwrap(), node_id1);
        assert_eq!(array.get(1).unwrap(), node_id2);
    }

    #[test]
    fn test_get_node_with_valid_id() {
        let mut doc = EureDocument::new();
        let node_id = doc.create_node(NodeValue::Primitive(PrimitiveValue::Null));

        let result = doc.get_node(node_id);
        assert!(result.is_some());

        let node = result.unwrap();
        assert_eq!(node.content, NodeValue::Primitive(PrimitiveValue::Null));
    }

    #[test]
    fn test_get_node_with_invalid_id() {
        let doc = EureDocument::new();
        // Create an invalid NodeId that's out of bounds
        let invalid_id = NodeId(9999);

        let result = doc.get_node(invalid_id);
        assert!(result.is_none());
    }

    #[test]
    fn test_get_node_mut_with_valid_id() {
        let mut doc = EureDocument::new();
        let node_id = doc.create_node(NodeValue::Primitive(PrimitiveValue::Null));

        let result = doc.get_node_mut(node_id);
        assert!(result.is_some());

        // Verify we can mutate through the returned reference
        let node = result.unwrap();
        node.content = NodeValue::Primitive(PrimitiveValue::Bool(true));

        // Verify the mutation persisted
        assert_eq!(
            doc.node(node_id).content,
            NodeValue::Primitive(PrimitiveValue::Bool(true))
        );
    }

    #[test]
    fn test_get_node_mut_with_invalid_id() {
        let mut doc = EureDocument::new();
        // Create an invalid NodeId that's out of bounds
        let invalid_id = NodeId(9999);

        let result = doc.get_node_mut(invalid_id);
        assert!(result.is_none());
    }

    #[test]
    fn test_partialeq_empty_documents() {
        let doc1 = EureDocument::new();
        let doc2 = EureDocument::new();
        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_primitive_documents() {
        let doc1 = EureDocument::new_primitive(PrimitiveValue::Bool(true));
        let doc2 = EureDocument::new_primitive(PrimitiveValue::Bool(true));
        let doc3 = EureDocument::new_primitive(PrimitiveValue::Bool(false));

        assert_eq!(doc1, doc2);
        assert_ne!(doc1, doc3);
    }

    #[test]
    fn test_partialeq_with_map_children() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        let root1 = doc1.get_root_id();
        let root2 = doc2.get_root_id();

        let key = ObjectKey::String("test".to_string());

        doc1.add_map_child(key.clone(), root1)
            .expect("Failed to add child");
        doc2.add_map_child(key.clone(), root2)
            .expect("Failed to add child");

        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_with_different_map_children() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        let root1 = doc1.get_root_id();
        let root2 = doc2.get_root_id();

        doc1.add_map_child(ObjectKey::String("key1".to_string()), root1)
            .expect("Failed to add child");
        doc2.add_map_child(ObjectKey::String("key2".to_string()), root2)
            .expect("Failed to add child");

        assert_ne!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_with_extensions() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        let root1 = doc1.get_root_id();
        let root2 = doc2.get_root_id();

        let ext_id = identifier("ext");

        doc1.add_extension(ext_id.clone(), root1)
            .expect("Failed to add extension");
        doc2.add_extension(ext_id.clone(), root2)
            .expect("Failed to add extension");

        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_with_different_extensions() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        let root1 = doc1.get_root_id();
        let root2 = doc2.get_root_id();

        doc1.add_extension(identifier("ext1"), root1)
            .expect("Failed to add extension");
        doc2.add_extension(identifier("ext2"), root2)
            .expect("Failed to add extension");

        assert_ne!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_with_arrays() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        // Create array in doc1
        let array_id1 = doc1.create_node(NodeValue::empty_array());
        doc1.add_array_element(None, array_id1)
            .expect("Failed to add array element");
        doc1.root = array_id1;

        // Create array in doc2
        let array_id2 = doc2.create_node(NodeValue::empty_array());
        doc2.add_array_element(None, array_id2)
            .expect("Failed to add array element");
        doc2.root = array_id2;

        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_with_tuples() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        // Create tuple in doc1
        let tuple_id1 = doc1.create_node(NodeValue::empty_tuple());
        doc1.add_tuple_element(0, tuple_id1)
            .expect("Failed to add tuple element");
        doc1.root = tuple_id1;

        // Create tuple in doc2
        let tuple_id2 = doc2.create_node(NodeValue::empty_tuple());
        doc2.add_tuple_element(0, tuple_id2)
            .expect("Failed to add tuple element");
        doc2.root = tuple_id2;

        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_nested_structure() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        // Create nested structure in doc1
        let root1 = doc1.get_root_id();
        let child1 = doc1
            .add_map_child(ObjectKey::String("child".to_string()), root1)
            .expect("Failed to add child")
            .node_id;
        doc1.node_mut(child1).content = NodeValue::Primitive(PrimitiveValue::Bool(true));

        // Create nested structure in doc2
        let root2 = doc2.get_root_id();
        let child2 = doc2
            .add_map_child(ObjectKey::String("child".to_string()), root2)
            .expect("Failed to add child")
            .node_id;
        doc2.node_mut(child2).content = NodeValue::Primitive(PrimitiveValue::Bool(true));

        assert_eq!(doc1, doc2);
    }

    #[test]
    fn test_partialeq_ignores_node_id_values() {
        let mut doc1 = EureDocument::new();
        let mut doc2 = EureDocument::new();

        // Create a more complex structure in doc1
        let root1 = doc1.get_root_id();
        let _intermediate = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));
        let child1 = doc1
            .add_map_child(ObjectKey::String("key".to_string()), root1)
            .expect("Failed")
            .node_id;

        // Create the same structure in doc2 (without intermediate node)
        let root2 = doc2.get_root_id();
        let child2 = doc2
            .add_map_child(ObjectKey::String("key".to_string()), root2)
            .expect("Failed")
            .node_id;

        // Even though child1 and child2 have different NodeId values,
        // the structures should be equal
        assert_eq!(doc1, doc2);

        // Verify that NodeIds are actually different
        assert_ne!(child1.0, child2.0);
    }

    #[test]
    fn test_require_map_converts_hole() {
        let mut doc = EureDocument::new();
        let node_id = doc.create_node(NodeValue::hole());

        assert!(doc.node(node_id).content.is_hole());

        {
            let node = doc.node_mut(node_id);
            let _map = node.require_map().expect("Should convert to map");
        }

        assert!(doc.node(node_id).as_map().is_some());
    }

    #[test]
    fn test_require_array_converts_hole() {
        let mut doc = EureDocument::new();
        let node_id = doc.create_node(NodeValue::hole());

        assert!(doc.node(node_id).content.is_hole());

        {
            let node = doc.node_mut(node_id);
            let _array = node.require_array().expect("Should convert to array");
        }

        assert!(doc.node(node_id).as_array().is_some());
    }

    #[test]
    fn test_require_tuple_converts_hole() {
        let mut doc = EureDocument::new();
        let node_id = doc.create_node(NodeValue::hole());

        assert!(doc.node(node_id).content.is_hole());

        {
            let node = doc.node_mut(node_id);
            let _tuple = node.require_tuple().expect("Should convert to tuple");
        }

        assert!(doc.node(node_id).as_tuple().is_some());
    }

    #[test]
    fn test_require_methods_fail_on_wrong_type() {
        let mut doc = EureDocument::new();
        let primitive_id = doc.create_node(NodeValue::Primitive(PrimitiveValue::Null));

        let node = doc.node_mut(primitive_id);
        assert_eq!(node.require_map().err(), Some(InsertErrorKind::ExpectedMap));

        let node = doc.node_mut(primitive_id);
        assert_eq!(
            node.require_array().err(),
            Some(InsertErrorKind::ExpectedArray)
        );

        let node = doc.node_mut(primitive_id);
        assert_eq!(
            node.require_tuple().err(),
            Some(InsertErrorKind::ExpectedTuple)
        );
    }
}

#[cfg(test)]
mod proptests {
    extern crate std;

    use super::*;
    use proptest::prelude::*;
    use std::vec::Vec;

    // =========================================================================
    // Strategy generators
    // =========================================================================

    /// Characters valid as the first character of an identifier (XID_Start or underscore).
    fn xid_start_char() -> impl Strategy<Value = char> {
        prop_oneof![
            prop::char::range('a', 'z'),
            prop::char::range('A', 'Z'),
            Just('_'),
            Just('α'),
            Just(''),
        ]
    }

    /// Characters valid in the continuation of an identifier (XID_Continue or hyphen).
    fn xid_continue_char() -> impl Strategy<Value = char> {
        prop_oneof![
            prop::char::range('a', 'z'),
            prop::char::range('A', 'Z'),
            prop::char::range('0', '9'),
            Just('_'),
            Just('-'),
            Just('α'),
            Just(''),
        ]
    }

    /// Strategy for generating valid identifiers with broader character coverage.
    fn arb_identifier() -> impl Strategy<Value = Identifier> {
        (
            xid_start_char(),
            proptest::collection::vec(xid_continue_char(), 0..15),
        )
            .prop_map(|(first, rest)| {
                let mut s = alloc::string::String::with_capacity(1 + rest.len());
                s.push(first);
                s.extend(rest);
                s
            })
            .prop_filter_map("valid identifier", |s| s.parse::<Identifier>().ok())
    }

    /// Strategy for generating object keys with broader coverage.
    fn arb_object_key() -> impl Strategy<Value = ObjectKey> {
        prop_oneof![
            // Identifier-style string keys (broader range)
            arb_identifier().prop_map(|id| ObjectKey::String(id.to_string())),
            // Numeric keys (including negative)
            (-1000i64..1000).prop_map(|n| ObjectKey::Number(n.into())),
        ]
    }

    /// Strategy for generating primitive values.
    fn arb_primitive_value() -> impl Strategy<Value = PrimitiveValue> {
        prop_oneof![
            Just(PrimitiveValue::Null),
            proptest::bool::ANY.prop_map(PrimitiveValue::Bool),
            (-1000i64..1000).prop_map(|n| PrimitiveValue::Integer(n.into())),
            proptest::num::f64::NORMAL.prop_map(PrimitiveValue::F64),
            "[a-zA-Z0-9 ]{0,50}".prop_map(|s| PrimitiveValue::Text(Text::plaintext(s))),
        ]
    }

    // =========================================================================
    // resolve_child_by_segment idempotency tests
    // =========================================================================

    proptest! {
        /// Invariant: resolve_child_by_segment is idempotent for Ident segments.
        /// Calling twice with the same identifier returns the same NodeId.
        #[test]
        fn resolve_ident_is_idempotent(ident in arb_identifier()) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let node_id1 = doc
                .resolve_child_by_segment(PathSegment::Ident(ident.clone()), root_id)
                .expect("First resolve failed")
                .node_id;

            let node_id2 = doc
                .resolve_child_by_segment(PathSegment::Ident(ident), root_id)
                .expect("Second resolve failed")
                .node_id;

            prop_assert_eq!(node_id1, node_id2, "Ident resolution should be idempotent");
        }

        /// Invariant: resolve_child_by_segment is idempotent for Value segments.
        #[test]
        fn resolve_value_is_idempotent(key in arb_object_key()) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let node_id1 = doc
                .resolve_child_by_segment(PathSegment::Value(key.clone()), root_id)
                .expect("First resolve failed")
                .node_id;

            let node_id2 = doc
                .resolve_child_by_segment(PathSegment::Value(key), root_id)
                .expect("Second resolve failed")
                .node_id;

            prop_assert_eq!(node_id1, node_id2, "Value resolution should be idempotent");
        }

        /// Invariant: resolve_child_by_segment is idempotent for Extension segments.
        #[test]
        fn resolve_extension_is_idempotent(ident in arb_identifier()) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let node_id1 = doc
                .resolve_child_by_segment(PathSegment::Extension(ident.clone()), root_id)
                .expect("First resolve failed")
                .node_id;

            let node_id2 = doc
                .resolve_child_by_segment(PathSegment::Extension(ident), root_id)
                .expect("Second resolve failed")
                .node_id;

            prop_assert_eq!(node_id1, node_id2, "Extension resolution should be idempotent");
        }

        /// Invariant: resolve_child_by_segment is idempotent for TupleIndex segments.
        #[test]
        fn resolve_tuple_index_is_idempotent(index in 0u8..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node_uninitialized();

            // First add indices sequentially up to `index`
            for i in 0..index {
                doc.add_tuple_element(i, parent_id).expect("Sequential add failed");
            }

            // Now resolve the next index
            let node_id1 = doc
                .resolve_child_by_segment(PathSegment::TupleIndex(index), parent_id)
                .expect("First resolve failed")
                .node_id;

            let node_id2 = doc
                .resolve_child_by_segment(PathSegment::TupleIndex(index), parent_id)
                .expect("Second resolve failed")
                .node_id;

            prop_assert_eq!(node_id1, node_id2, "TupleIndex resolution should be idempotent");
        }

        /// Invariant: resolve_child_by_segment is idempotent for ArrayIndex(ArrayIndexKind::Specific(n)) segments.
        #[test]
        fn resolve_array_index_some_is_idempotent(index in 0usize..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node_uninitialized();

            // First add indices sequentially up to `index`
            for i in 0..index {
                doc.add_array_element(Some(i), parent_id).expect("Sequential add failed");
            }

            // Now resolve the next index
            let node_id1 = doc
                .resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)), parent_id)
                .expect("First resolve failed")
                .node_id;

            let node_id2 = doc
                .resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)), parent_id)
                .expect("Second resolve failed")
                .node_id;

            prop_assert_eq!(node_id1, node_id2, "ArrayIndex(Some) resolution should be idempotent");
        }

        /// Invariant: ArrayIndex(ArrayIndexKind::Push) always creates new elements (NOT idempotent - push behavior).
        #[test]
        fn resolve_array_index_none_always_creates_new(count in 1usize..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node_uninitialized();

            let mut node_ids = Vec::new();
            for _ in 0..count {
                let node_id = doc
                    .resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Push), parent_id)
                    .expect("Resolve failed")
                    .node_id;
                node_ids.push(node_id);
            }

            // All node IDs should be unique
            for i in 0..node_ids.len() {
                for j in (i+1)..node_ids.len() {
                    prop_assert_ne!(node_ids[i], node_ids[j],
                        "ArrayIndex(ArrayIndexKind::Push) should create unique nodes");
                }
            }

            // Array length should match push count
            let array = doc.node(parent_id).as_array().expect("Expected array");
            prop_assert_eq!(array.len(), count, "Array length should match push count");
        }

        /// Error: ArrayIndex segment on non-array parent fails.
        #[test]
        fn resolve_array_index_on_map_fails(index in 0usize..10) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id(); // Root starts as a hole/map

            // Make root explicitly a map
            doc.node_mut(root_id).content = NodeValue::empty_map();

            let result = doc.resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Specific(index)), root_id);
            prop_assert!(result.is_err(), "ArrayIndex on map should fail");
            prop_assert_eq!(result.err(), Some(InsertErrorKind::ExpectedArray));
        }

        /// Error: TupleIndex segment on non-tuple parent fails.
        #[test]
        fn resolve_tuple_index_on_array_fails(index in 0u8..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node(NodeValue::empty_array());

            let result = doc.resolve_child_by_segment(PathSegment::TupleIndex(index), parent_id);
            prop_assert!(result.is_err(), "TupleIndex on array should fail");
            prop_assert_eq!(result.err(), Some(InsertErrorKind::ExpectedTuple));
        }

        /// Error: ArrayIndex segment on primitive fails.
        #[test]
        fn resolve_array_index_on_primitive_fails(value in arb_primitive_value()) {
            let mut doc = EureDocument::new();
            let node_id = doc.create_node(NodeValue::Primitive(value));

            let result = doc.resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Specific(0)), node_id);
            prop_assert!(result.is_err(), "ArrayIndex on primitive should fail");
            prop_assert_eq!(result.err(), Some(InsertErrorKind::ExpectedArray));
        }

        /// Error: Non-sequential ArrayIndex fails.
        #[test]
        fn resolve_array_index_non_sequential_fails(skip in 1usize..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node(NodeValue::empty_array());

            // Try to add at index `skip` without filling 0..skip first
            let result = doc.resolve_child_by_segment(PathSegment::ArrayIndex(ArrayIndexKind::Specific(skip)), parent_id);
            prop_assert!(result.is_err(), "Non-sequential ArrayIndex should fail");

            match result.err() {
                Some(InsertErrorKind::ArrayIndexInvalid { index, expected_index }) => {
                    prop_assert_eq!(index, skip);
                    prop_assert_eq!(expected_index, 0);
                }
                other => prop_assert!(false, "Expected ArrayIndexInvalid, got {:?}", other),
            }
        }

        /// Error: Non-sequential TupleIndex fails.
        #[test]
        fn resolve_tuple_index_non_sequential_fails(skip in 1u8..10) {
            let mut doc = EureDocument::new();
            let parent_id = doc.create_node(NodeValue::empty_tuple());

            let result = doc.resolve_child_by_segment(PathSegment::TupleIndex(skip), parent_id);
            prop_assert!(result.is_err(), "Non-sequential TupleIndex should fail");

            match result.err() {
                Some(InsertErrorKind::TupleIndexInvalid { index, expected_index }) => {
                    prop_assert_eq!(index, skip);
                    prop_assert_eq!(expected_index, 0);
                }
                other => prop_assert!(false, "Expected TupleIndexInvalid, got {:?}", other),
            }
        }
    }

    // =========================================================================
    // Extension uniqueness tests
    // =========================================================================

    proptest! {
        /// Invariant: Multiple different extensions can be added to a single node.
        #[test]
        fn multiple_different_extensions_allowed(
            ext1 in arb_identifier(),
            ext2 in arb_identifier(),
        ) {
            prop_assume!(ext1 != ext2);

            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let node_id1 = doc.add_extension(ext1.clone(), root_id)
                .expect("First extension failed")
                .node_id;
            let node_id2 = doc.add_extension(ext2.clone(), root_id)
                .expect("Second extension failed")
                .node_id;

            let node = doc.node(root_id);
            prop_assert_eq!(node.extensions.get(&ext1), Some(&node_id1));
            prop_assert_eq!(node.extensions.get(&ext2), Some(&node_id2));
        }

        /// Invariant: Duplicate extension identifier fails with AlreadyAssignedExtension.
        #[test]
        fn duplicate_extension_fails(ext in arb_identifier()) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let _first = doc.add_extension(ext.clone(), root_id)
                .expect("First extension should succeed");

            let result = doc.add_extension(ext.clone(), root_id);
            prop_assert_eq!(
                result.err(),
                Some(InsertErrorKind::AlreadyAssignedExtension { identifier: ext }),
                "Duplicate extension should fail"
            );
        }
    }

    // =========================================================================
    // Document equality tests
    // =========================================================================

    proptest! {
        /// Invariant: Two documents with same structure are equal even with different NodeIds.
        #[test]
        fn document_equality_ignores_node_ids(
            keys in proptest::collection::vec(arb_object_key(), 1..5)
                .prop_filter("unique keys", |keys| {
                    let unique: std::collections::HashSet<_> = keys.iter().collect();
                    unique.len() == keys.len()
                }),
        ) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            // Add an unrelated node to doc1 to offset NodeIds
            let _ = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            // Add same children to both documents
            for key in &keys {
                doc1.add_map_child(key.clone(), root1).expect("Add failed");
                doc2.add_map_child(key.clone(), root2).expect("Add failed");
            }

            prop_assert_eq!(doc1, doc2, "Documents with same structure should be equal");
        }

        /// Invariant: Reflexive equality - a document equals itself.
        #[test]
        fn document_equality_reflexive(
            keys in proptest::collection::vec(arb_object_key(), 0..5)
                .prop_filter("unique keys", |keys| {
                    let unique: std::collections::HashSet<_> = keys.iter().collect();
                    unique.len() == keys.len()
                }),
        ) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            for key in &keys {
                doc.add_map_child(key.clone(), root_id).expect("Add failed");
            }

            prop_assert_eq!(&doc, &doc, "Document should equal itself");
        }

        /// Invariant: Documents with different content are not equal.
        #[test]
        fn document_equality_different_content(
            key1 in arb_object_key(),
            key2 in arb_object_key(),
        ) {
            prop_assume!(key1 != key2);

            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            doc1.add_map_child(key1, root1).expect("Add failed");
            doc2.add_map_child(key2, root2).expect("Add failed");

            prop_assert_ne!(doc1, doc2, "Documents with different keys should not be equal");
        }

        /// Invariant: Document equality works for arrays.
        #[test]
        fn document_equality_for_arrays(count in 1usize..10) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            // Offset NodeIds in doc1
            let _ = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            // Convert roots to arrays
            doc1.node_mut(root1).content = NodeValue::empty_array();
            doc2.node_mut(root2).content = NodeValue::empty_array();

            for _ in 0..count {
                doc1.add_array_element(None, root1).expect("Add failed");
                doc2.add_array_element(None, root2).expect("Add failed");
            }

            prop_assert_eq!(doc1, doc2, "Documents with same array structure should be equal");
        }

        /// Invariant: Document equality works for tuples.
        #[test]
        fn document_equality_for_tuples(count in 1u8..10) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            let _ = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            doc1.node_mut(root1).content = NodeValue::empty_tuple();
            doc2.node_mut(root2).content = NodeValue::empty_tuple();

            for i in 0..count {
                doc1.add_tuple_element(i, root1).expect("Add failed");
                doc2.add_tuple_element(i, root2).expect("Add failed");
            }

            prop_assert_eq!(doc1, doc2, "Documents with same tuple structure should be equal");
        }

        /// Invariant: Document equality works for primitive values.
        #[test]
        fn document_equality_for_primitives(value in arb_primitive_value()) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            let _ = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            doc1.node_mut(root1).content = NodeValue::Primitive(value.clone());
            doc2.node_mut(root2).content = NodeValue::Primitive(value);

            prop_assert_eq!(doc1, doc2, "Documents with same primitive value should be equal");
        }

        /// Invariant: Document equality considers extensions.
        #[test]
        fn document_equality_considers_extensions(
            ext_name in arb_identifier(),
            value in arb_primitive_value(),
        ) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            let _ = doc1.create_node(NodeValue::Primitive(PrimitiveValue::Null));

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            // Add same extension to both
            let ext1_id = doc1.add_extension(ext_name.clone(), root1).expect("Add ext failed").node_id;
            let ext2_id = doc2.add_extension(ext_name.clone(), root2).expect("Add ext failed").node_id;

            // Set same value in extensions
            doc1.node_mut(ext1_id).content = NodeValue::Primitive(value.clone());
            doc2.node_mut(ext2_id).content = NodeValue::Primitive(value);

            prop_assert_eq!(doc1, doc2, "Documents with same extensions should be equal");
        }

        /// Invariant: Documents with different extensions are not equal.
        #[test]
        fn document_equality_different_extensions(
            ext1 in arb_identifier(),
            ext2 in arb_identifier(),
        ) {
            prop_assume!(ext1 != ext2);

            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            doc1.add_extension(ext1, root1).expect("Add ext failed");
            doc2.add_extension(ext2, root2).expect("Add ext failed");

            prop_assert_ne!(doc1, doc2, "Documents with different extensions should not be equal");
        }
    }

    // =========================================================================
    // Copy subtree tests
    // =========================================================================

    proptest! {
        /// Invariant: copy_subtree preserves primitive values.
        #[test]
        fn copy_subtree_preserves_primitive(value in arb_primitive_value()) {
            let mut src = EureDocument::new();
            let src_id = src.create_node(NodeValue::Primitive(value.clone()));

            let dst = src.node_subtree_to_document(src_id);

            let dst_node = dst.root();
            match &dst_node.content {
                NodeValue::Primitive(copied_value) => {
                    prop_assert_eq!(copied_value, &value, "Primitive value should be preserved");
                }
                other => {
                    prop_assert!(false, "Expected Primitive, got {:?}", other);
                }
            }
        }

        /// Invariant: copy_subtree for arrays must create valid NodeIds in destination.
        /// All NodeIds stored in the copied array must exist in the destination document.
        #[test]
        fn copy_subtree_array_has_valid_node_ids(count in 1usize..10) {
            let mut src = EureDocument::new();
            let array_id = src.create_node(NodeValue::empty_array());

            for _ in 0..count {
                src.add_array_element(None, array_id).expect("Add failed");
            }

            let dst = src.node_subtree_to_document(array_id);

            // The destination array should have exactly `count` elements
            let dst_array = dst.root().as_array().expect("Expected array");
            prop_assert_eq!(dst_array.len(), count, "Copied array should have correct length");

            // All NodeIds in the destination array must be valid
            for i in 0..dst_array.len() {
                let child_id = dst_array.get(i).expect("Should have element");
                prop_assert!(
                    dst.get_node(child_id).is_some(),
                    "NodeId {:?} at index {} must exist in destination", child_id, i
                );
            }
        }

        /// Invariant: copy_subtree for maps must create valid NodeIds in destination.
        #[test]
        fn copy_subtree_map_has_valid_node_ids(
            keys in proptest::collection::vec(arb_object_key(), 1..5)
                .prop_filter("unique keys", |keys| {
                    let unique: std::collections::HashSet<_> = keys.iter().collect();
                    unique.len() == keys.len()
                }),
        ) {
            let mut src = EureDocument::new();
            let map_id = src.create_node(NodeValue::empty_map());

            for key in &keys {
                src.add_map_child(key.clone(), map_id).expect("Add failed");
            }

            let dst = src.node_subtree_to_document(map_id);

            let dst_map = dst.root().as_map().expect("Expected map");
            prop_assert_eq!(dst_map.len(), keys.len(), "Copied map should have correct size");

            // All NodeIds in the destination map must be valid
            for (key, &child_id) in dst_map.iter() {
                prop_assert!(
                    dst.get_node(child_id).is_some(),
                    "NodeId {:?} for key {:?} must exist in destination", child_id, key
                );
            }
        }

        /// Invariant: copy_subtree for tuples must create valid NodeIds in destination.
        #[test]
        fn copy_subtree_tuple_has_valid_node_ids(count in 1u8..10) {
            let mut src = EureDocument::new();
            let tuple_id = src.create_node(NodeValue::empty_tuple());

            for i in 0..count {
                src.add_tuple_element(i, tuple_id).expect("Add failed");
            }

            let dst = src.node_subtree_to_document(tuple_id);

            let dst_tuple = dst.root().as_tuple().expect("Expected tuple");
            prop_assert_eq!(dst_tuple.len(), count as usize, "Copied tuple should have correct length");

            // All NodeIds in the destination tuple must be valid
            for i in 0..dst_tuple.len() {
                let child_id = dst_tuple.get(i).expect("Should have element");
                prop_assert!(
                    dst.get_node(child_id).is_some(),
                    "NodeId {:?} at index {} must exist in destination", child_id, i
                );
            }
        }

        /// Invariant: copy_subtree preserves nested mixed content (map → array → primitive).
        #[test]
        fn copy_subtree_preserves_nested_mixed_content(
            key in arb_object_key(),
            value in arb_primitive_value(),
        ) {
            let mut src = EureDocument::new();
            let map_id = src.create_node(NodeValue::empty_map());

            // Create map → array → primitive structure
            let child_id = src.add_map_child(key.clone(), map_id).expect("Add failed").node_id;
            src.node_mut(child_id).content = NodeValue::empty_array();
            let elem_id = src.add_array_element(None, child_id).expect("Add failed").node_id;
            src.node_mut(elem_id).content = NodeValue::Primitive(value.clone());

            let dst = src.node_subtree_to_document(map_id);

            // Verify structure
            let dst_map = dst.root().as_map().expect("Expected map");
            let dst_child_id = dst_map.get(&key).expect("Should have key");
            let dst_child = dst.get_node(*dst_child_id).expect("Child should exist");
            let dst_array = dst_child.as_array().expect("Expected array");
            prop_assert_eq!(dst_array.len(), 1);

            let dst_elem_id = dst_array.get(0).expect("Should have element");
            let dst_elem = dst.get_node(dst_elem_id).expect("Element should exist");
            prop_assert_eq!(
                &dst_elem.content,
                &NodeValue::Primitive(value),
                "Primitive value should be preserved in nested structure"
            );
        }

        /// Invariant: copy_subtree preserves extensions on nodes.
        #[test]
        fn copy_subtree_preserves_extensions(
            ext_name in arb_identifier(),
            ext_value in arb_primitive_value(),
        ) {
            let mut src = EureDocument::new();
            let node_id = src.create_node(NodeValue::empty_map());

            // Add extension to the node
            let ext_id = src.add_extension(ext_name.clone(), node_id).expect("Add ext failed").node_id;
            src.node_mut(ext_id).content = NodeValue::Primitive(ext_value.clone());

            let dst = src.node_subtree_to_document(node_id);

            // Verify extension exists in destination
            let dst_ext = dst.root().extensions.get(&ext_name);
            prop_assert!(dst_ext.is_some(), "Extension should be copied");

            let dst_ext_id = *dst_ext.unwrap();
            let dst_ext_node = dst.get_node(dst_ext_id).expect("Extension node should exist");
            prop_assert_eq!(
                &dst_ext_node.content,
                &NodeValue::Primitive(ext_value),
                "Extension value should be preserved"
            );
        }

        /// Invariant: copy_subtree preserves extensions on nested nodes.
        #[test]
        fn copy_subtree_preserves_nested_extensions(
            key in arb_object_key(),
            ext_name in arb_identifier(),
        ) {
            let mut src = EureDocument::new();
            let map_id = src.create_node(NodeValue::empty_map());

            // Add child to map
            let child_id = src.add_map_child(key.clone(), map_id).expect("Add failed").node_id;
            // Add extension to child
            src.add_extension(ext_name.clone(), child_id).expect("Add ext failed");

            let dst = src.node_subtree_to_document(map_id);

            // Verify nested extension exists
            let dst_map = dst.root().as_map().expect("Expected map");
            let dst_child_id = dst_map.get(&key).expect("Should have key");
            let dst_child = dst.get_node(*dst_child_id).expect("Child should exist");

            prop_assert!(
                dst_child.extensions.contains_key(&ext_name),
                "Extension on nested node should be preserved"
            );
        }
    }

    // =========================================================================
    // Map key uniqueness tests
    // =========================================================================

    proptest! {
        /// Invariant: Map keys must be unique; duplicate key fails with AlreadyAssigned.
        #[test]
        fn map_key_uniqueness(key in arb_object_key()) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            let _first = doc.add_map_child(key.clone(), root_id)
                .expect("First add should succeed");

            let result = doc.add_map_child(key.clone(), root_id);
            prop_assert_eq!(
                result.err(),
                Some(InsertErrorKind::AlreadyAssigned { key }),
                "Duplicate map key should fail"
            );
        }

        /// Invariant: Multiple different map keys can coexist.
        #[test]
        fn multiple_map_keys_allowed(
            keys in proptest::collection::vec(arb_object_key(), 2..10)
                .prop_filter("unique keys", |keys| {
                    let unique: std::collections::HashSet<_> = keys.iter().collect();
                    unique.len() == keys.len()
                })
        ) {
            let mut doc = EureDocument::new();
            let root_id = doc.get_root_id();

            for key in &keys {
                doc.add_map_child(key.clone(), root_id).expect("Add should succeed");
            }

            let map = doc.node(root_id).as_map().expect("Expected map");
            prop_assert_eq!(map.len(), keys.len(), "All unique keys should be present");
        }
    }

    // =========================================================================
    // Node validity tests
    // =========================================================================

    proptest! {
        /// Invariant: All created nodes can be accessed via get_node.
        #[test]
        fn created_nodes_are_accessible(count in 1usize..20) {
            let mut doc = EureDocument::new();
            let mut node_ids = Vec::new();

            for _ in 0..count {
                let id = doc.create_node_uninitialized();
                node_ids.push(id);
            }

            for id in node_ids {
                prop_assert!(doc.get_node(id).is_some(),
                    "Created node {:?} should be accessible", id);
            }
        }

        /// Invariant: Invalid NodeIds return None from get_node.
        #[test]
        fn invalid_node_ids_return_none(count in 1usize..10) {
            let mut doc = EureDocument::new();

            for _ in 0..count {
                doc.create_node_uninitialized();
            }

            // Access an invalid NodeId (beyond the nodes vector)
            let invalid_id = NodeId(count + 100);
            prop_assert!(doc.get_node(invalid_id).is_none(),
                "Invalid NodeId should return None");
        }

        /// Invariant: Root node is always accessible.
        #[test]
        fn root_is_always_accessible(count in 0usize..10) {
            let mut doc = EureDocument::new();

            // Create some additional nodes
            for _ in 0..count {
                doc.create_node_uninitialized();
            }

            let root_id = doc.get_root_id();
            prop_assert!(doc.get_node(root_id).is_some(), "Root should always be accessible");
            prop_assert_eq!(root_id, NodeId(0), "Root should be NodeId(0)");
        }
    }

    // =========================================================================
    // Nested structure tests
    // =========================================================================

    proptest! {
        /// Invariant: Nested structures can be built and are equal across documents.
        #[test]
        fn nested_structures_are_equal(
            keys in proptest::collection::vec(arb_object_key(), 1..3),
            depth in 1usize..4,
        ) {
            let mut doc1 = EureDocument::new();
            let mut doc2 = EureDocument::new();

            fn build_nested(
                doc: &mut EureDocument,
                parent_id: NodeId,
                keys: &[ObjectKey],
                depth: usize,
            ) {
                if depth == 0 {
                    return;
                }
                // First collect child node IDs to avoid borrow conflict
                let child_ids: Vec<NodeId> = keys
                    .iter()
                    .filter_map(|key| {
                        doc.add_map_child(key.clone(), parent_id).ok().map(|c| c.node_id)
                    })
                    .collect();

                // Then recursively build nested structures
                for child_id in child_ids {
                    build_nested(doc, child_id, keys, depth - 1);
                }
            }

            let root1 = doc1.get_root_id();
            let root2 = doc2.get_root_id();

            build_nested(&mut doc1, root1, &keys, depth);
            build_nested(&mut doc2, root2, &keys, depth);

            prop_assert_eq!(doc1, doc2, "Nested structures should be equal");
        }
    }
}