brink-runtime 0.0.10

Runtime/VM for executing compiled ink stories
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
//! Shared story state (`World`), the per-flow override layer (`FlowLocal`),
//! and the routing view that composes them behind [`ContextAccess`].
//!
//! This is the F1.3 stage of the scoped-flow-state restructuring
//! (`docs/scoped-flow-state-spec.md`): `World` replaces the old monolithic
//! `Context` as the core mutable-state primitive. The [`ContextView`]
//! routing view implements [`ContextAccess`] over `(&mut World, &mut
//! FlowLocal)`.
//!
//! F2.1 adds the **policy** types ([`Scope`], [`WorldPolicy`],
//! [`ResolvedPolicy`]) and their resolution against a [`Program`]'s symbol
//! table.
//!
//! F2.2 gave `FlowLocal` flat override storage (plain maps/options — no
//! `CoW` chain) and wired [`ContextView`] to route every [`ContextAccess`]
//! op by consulting `World`'s [`ResolvedPolicy`] with **read-through**
//! semantics: a `Local`-scoped unit reads its `FlowLocal` override if
//! present, else falls back to `World`'s value; a `World`-scoped unit
//! always goes straight to `World`. Writes to a `Local`-scoped unit land in
//! `FlowLocal`; writes to a `World`-scoped unit land in `World`,
//! immediately visible to every flow sharing it.
//!
//! F3.1 upgraded `FlowLocal`'s storage to a copy-on-write, frozen-base
//! read-through **chain**: `FlowLocal` gains an optional [`Arc<FrozenLocal>`]
//! base, an immutable snapshot of another `FlowLocal`'s overrides (captured
//! via [`FlowLocal::freeze`]) that can itself chain to a further base. A read
//! walks **own overrides → base (recursively) → [miss]**; a miss falls
//! through to `World` exactly as before. Writes still land only in the
//! flow's own top-layer overrides.
//!
//! **F3.2 (this stage)** adds **fork + sandbox mode + discard**: [`Mode`]
//! (`Normal`/`Sandbox`), baked onto a `FlowLocal` at construction/fork time,
//! and [`FlowLocal::fork`], which builds a child whose `base` is a frozen
//! snapshot of the parent (via `freeze`) and whose own overrides start
//! empty. `Normal` fork children route exactly like any other `FlowLocal` —
//! by policy. `Sandbox` children are the side-effect-proof primitive
//! watch/eval needs: `ContextView` treats **every** unit as `Local`
//! regardless of policy, so the shared `World` is a read-only base — reads
//! chain-read-through to `World`'s live value on a miss, but writes always
//! land in the sandboxed flow's own overrides and never reach `World`.
//! Discard is simply dropping the forked `FlowLocal`: since a `Sandbox`
//! child's writes never touched `World` (and a `Normal` child's writes never
//! touched its parent or `World` either — only its own top layer), there is
//! nothing to unwind. A deferred `commit` seam (fold a fork's writes back
//! into its parent) is documented but intentionally left unimplemented — see
//! [`CommitError`] and [`commit`].
//!
//! No existing construction path calls `fork` or requests `Mode::Sandbox` —
//! every flow the oracle corpus drives is `Mode::Normal` with `base: None`,
//! so `ContextView` takes exactly the F3.1 branch on every op. The all-
//! `World` policy (the default, and the only policy the oracle corpus
//! exercises) takes the `World` branch on every op, so `ContextView` stays
//! byte-identical to the F1.3 passthrough for every existing single-flow
//! construction path.

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use brink_format::{DefinitionId, Value};

use crate::program::Program;
use crate::rng::StoryRng;
use crate::state::ContextAccess;

// ── Policy ───────────────────────────────────────────────────────────────
//
// The scoped-flow-state model (`docs/scoped-flow-state-spec.md`, "The
// policy") homes every unit of story-state — globals, visit/turn counts,
// turn index, RNG — to either the shared `World` or a flow's private
// `FlowLocal`. `WorldPolicy` is the host-facing, name-based declaration of
// that split; `ResolvedPolicy` is the fast id/slot-based form the runtime
// actually consults, built once at `World` creation.
//
// F2.1 introduces both shapes and resolution only. `ResolvedPolicy` is
// stored on `World` but unread — F2.2 wires `ContextView` to consult it.

/// Where a unit of story-state lives: the shared [`World`] or a flow's
/// private [`FlowLocal`].
///
/// `World` is visible to every flow sharing that world immediately on
/// write — the coordination path. `Local` is private to one flow; it
/// persists for that flow's lifetime and only folds back into a parent via
/// an explicit (currently unimplemented, F3) `commit`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Scope {
    /// Shared across every flow over the world. This is the default —
    /// matches today's single-`Context` behavior byte-for-byte.
    #[default]
    World,
    /// Private to one flow.
    Local,
}

/// Host-facing, name-based declaration of the world/local split.
///
/// Resolved once (via [`ResolvedPolicy::resolve`]) against a linked
/// [`Program`]'s symbol table into a fast id/slot-based [`ResolvedPolicy`].
/// Unlisted variables and knots/stitches fall back to `default`.
///
/// The all-`World` default (via [`WorldPolicy::default`]) is the
/// degenerate, oracle-safety-anchoring policy: every unit homed to
/// `World`, no overrides — identical to today's single-flow behavior.
///
/// **Name precedence:** a name in `overrides` is tried as a global variable
/// first, then as a knot/stitch path (see [`ResolvedPolicy::resolve`]). If a
/// name is (unusually) both a declared global VAR and a resolvable knot/
/// stitch path, the override resolves against the **variable**, never the
/// knot — the knot path is not consulted once a variable of the same name
/// is found.
///
/// **Knot/stitch overrides are subtree-inclusive** (F6.1c —
/// `docs/scoped-flow-state-spec.md`'s F6 AMENDMENT, ruling 3): a knot
/// override covers the knot's own visit/turn count, every stitch nested
/// directly under it, and every interior container (weave/sequence/choice
/// container) nested anywhere under the knot or one of its stitches — not
/// just the knot's own `DefinitionId`. This matters because ink's
/// sequence/cycle/stopping machinery (`{ Halt! | Back again? }`) keys its
/// counter off the *sequence's own* interior container id, not the
/// enclosing knot's id; without subtree inclusion, a knot marked `Local`
/// would leave those interior counters silently `World`-scoped.
///
/// **Most-specific override wins.** If both a knot and one of its stitches
/// appear in `overrides` (e.g. knot `a` is `Local`, stitch `a.b` is
/// `World`), every interior container nested under `a.b` resolves `World`;
/// the rest of `a`'s subtree (the knot's own id, its other stitches, and
/// any interior container not under `a.b`) resolves `Local`. A stitch's
/// override always wins over its enclosing knot's for the stitch's own
/// subtree, regardless of which name appears earlier in `overrides` (see
/// [`ResolvedPolicy::resolve`] for how this is implemented).
#[derive(Debug, Clone, Default)]
pub struct WorldPolicy {
    /// Scope for any variable or knot/stitch not named in `overrides`.
    pub default: Scope,
    /// Per-name exceptions to `default`, for global variables (matched
    /// against `Program::global_index`'s name grammar) and knot/stitch
    /// paths (matched against `Program::find_path_target`'s path
    /// grammar). A name may appear in only one of the two — the resolver
    /// tries variables first, then knot paths. Knot/stitch overrides are
    /// subtree-inclusive with most-specific-wins precedence — see the type
    /// docs above.
    pub overrides: BTreeMap<String, Scope>,
    /// Scope of the turn index (a single scalar field).
    pub turn_index: Scope,
    /// Scope of the RNG stream (`rng_seed` + `previous_random`, a single
    /// scalar stream). See the spec's determinism caveat: a `World`-scoped
    /// RNG interleaves draws from every flow sharing the world by
    /// execution order.
    pub rng: Scope,
}

/// Errors resolving a [`WorldPolicy`] against a [`Program`]'s symbol table.
///
/// Resolution happens once, at `World` creation — an unknown name here is
/// a host configuration error, not a runtime one.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum PolicyError {
    /// A name in `WorldPolicy::overrides` matched neither a declared
    /// global variable nor a resolvable knot/stitch path.
    #[error("unknown variable or knot/stitch in world policy overrides: {0}")]
    UnknownName(String),
}

/// Fast, id/slot-based resolution of a [`WorldPolicy`] against a specific
/// [`Program`]. Built once at `World` creation via
/// [`ResolvedPolicy::resolve`]; consulted on every state access (from F2.2
/// on) with O(1) lookups — no string matching on the hot path.
#[derive(Debug, Clone)]
pub struct ResolvedPolicy {
    /// Default scope for globals/knots not otherwise listed.
    default: Scope,
    /// Per-slot scope for every global variable, dense (length ==
    /// `Program::global_count()`). Populated with `default` for slots with
    /// no override, so lookups never need a fallback branch.
    global_scopes: Vec<Scope>,
    /// Non-default scope for a knot/stitch (or an interior weave/sequence/
    /// choice container nested under one), keyed by its defining
    /// `DefinitionId` (the same id `ContextAccess::visit_count` and friends
    /// are called with — e.g. `vm.rs`'s `handle_sequence` keys a stopping/
    /// cycle sequence's counter off the *sequence's own* interior container
    /// id, not its enclosing knot's).
    ///
    /// **Subtree-inclusive (F6.1c):** an override on a knot/stitch name is
    /// expanded at resolve time (see [`resolve`](Self::resolve)) to cover
    /// its own id, every stitch nested directly under it (if it's a knot),
    /// and every interior container nested anywhere under it or one of its
    /// stitches — not just the literal `DefinitionId` the override name
    /// resolved to. Only exceptions to `default` are stored — sparse, since
    /// most programs have far more knots/interior containers than
    /// overrides.
    knot_scopes: HashMap<DefinitionId, Scope>,
    /// Scope of the turn index.
    turn_index: Scope,
    /// Scope of the RNG stream.
    rng: Scope,
}

impl ResolvedPolicy {
    /// The all-`World` resolved policy — no name lookups needed. This is
    /// the fast path for [`WorldPolicy::default()`] and the only policy
    /// exercised by the oracle-anchored single-flow path.
    #[must_use]
    pub fn all_world() -> Self {
        Self {
            default: Scope::World,
            global_scopes: Vec::new(),
            knot_scopes: HashMap::new(),
            turn_index: Scope::World,
            rng: Scope::World,
        }
    }

    /// Resolve a host-facing [`WorldPolicy`] against a linked `Program`'s
    /// symbol table.
    ///
    /// Variable names are resolved via [`Program::global_index`]; knot/
    /// stitch paths via `Program`'s path-to-`DefinitionId` resolution
    /// (the same table `find_address`/`find_path_target` use). A name is
    /// tried as a variable first, then as a knot/stitch path; a name
    /// matching neither is a [`PolicyError::UnknownName`].
    ///
    /// **Subtree expansion (F6.1c).** Every knot/stitch override is
    /// expanded here, once, into every `DefinitionId` in its definition
    /// subtree — see [`expand_knot_scope`] for the containment mechanism
    /// (`Program::scope_ids`, the nearest-enclosing-scope table every
    /// interior container carries, plus `Program::address_by_path`'s
    /// dotted knot/stitch grammar for the one-level knot→stitch link that
    /// `scope_ids` alone doesn't carry). `overrides` is a `BTreeMap`, so
    /// this loop's iteration order is deterministic (sorted by name) — and
    /// because a knot's name is always a proper prefix of (and therefore
    /// sorts lexicographically before) any of its stitches' names, a knot
    /// override's subtree expansion always runs *before* a same-subtree
    /// stitch override in this same pass, so the stitch override's own
    /// `insert`s (which land later) win — implementing "most-specific
    /// override wins" as a natural consequence of processing order, no
    /// separate precedence pass needed.
    ///
    /// The all-`World` default (empty `overrides`) resolves without any
    /// name lookups (see [`all_world`](Self::all_world)) — this is the
    /// fast path every existing construction path takes today.
    pub fn resolve(program: &Program, policy: &WorldPolicy) -> Result<Self, PolicyError> {
        if policy.overrides.is_empty()
            && policy.default == Scope::World
            && policy.turn_index == Scope::World
            && policy.rng == Scope::World
        {
            return Ok(Self::all_world());
        }

        let mut global_scopes = vec![policy.default; program.global_count() as usize];
        let mut knot_scopes = HashMap::new();
        let interior_by_scope = interior_containers_by_scope(program);

        // `overrides` is a `BTreeMap`, so iteration order is deterministic
        // (sorted by name) — resolution never depends on hash-map order.
        for (name, &scope) in &policy.overrides {
            if let Some(slot) = program.global_index(name) {
                global_scopes[slot as usize] = scope;
            } else if let Some(id) = program.find_path_target(name) {
                expand_knot_scope(
                    program,
                    &interior_by_scope,
                    &mut knot_scopes,
                    name,
                    id,
                    scope,
                );
            } else {
                return Err(PolicyError::UnknownName(name.clone()));
            }
        }

        Ok(Self {
            default: policy.default,
            global_scopes,
            knot_scopes,
            turn_index: policy.turn_index,
            rng: policy.rng,
        })
    }

    /// Scope of a global variable by slot index.
    #[must_use]
    pub fn scope_of_global(&self, slot: u32) -> Scope {
        self.global_scopes
            .get(slot as usize)
            .copied()
            .unwrap_or(self.default)
    }

    /// Scope of a knot/stitch — or of an interior weave/sequence/choice
    /// container nested under one — by its defining `DefinitionId`. See the
    /// `knot_scopes` field docs and [`resolve`](Self::resolve) for how a
    /// knot/stitch override is expanded, at resolve time, to cover every id
    /// in its definition subtree.
    #[must_use]
    pub fn scope_of_knot(&self, id: DefinitionId) -> Scope {
        self.knot_scopes.get(&id).copied().unwrap_or(self.default)
    }

    /// Scope of the turn index.
    #[must_use]
    pub fn turn_index_scope(&self) -> Scope {
        self.turn_index
    }

    /// Scope of the RNG stream.
    #[must_use]
    pub fn rng_scope(&self) -> Scope {
        self.rng
    }
}

// ── Subtree-inclusive knot scope (F6.1c) ────────────────────────────────
//
// Containment mechanism, verified against a compiled `Program` (see the
// `subtree_scope_tests` module below and the investigation in the F6.1c
// build log — not restated here):
//
// - `ContainerDef::scope_id` (preserved on `Program` as the parallel
//   `scope_ids`/`scope_table_idx` tables) gives every container — knot,
//   stitch, root, or an anonymous interior weave/sequence/choice
//   container, at any nesting depth — the `DefinitionId` of its *nearest
//   enclosing* knot/stitch/root scope, correctly propagated through
//   arbitrarily deep nesting by the codegen's recursive walk. A container
//   is itself a scope owner (a knot, stitch, or root) exactly when its own
//   `scope_id` equals its own id — self-scoped, no parent. This gives an
//   exact, structural (not name-based) map from any interior container to
//   its owning knot/stitch: `interior_containers_by_scope`, below.
// - `scope_id` does *not* link a stitch to its enclosing knot (a stitch is
//   self-scoped, by the same rule above) — ink only nests stitches one
//   level under a knot, and that one link has to come from
//   `Program::address_by_path`'s dotted qualified-path grammar (the same
//   table `find_address`/`find_path_target` already use): a knot named `N`
//   knows its direct stitches are exactly the `address_by_path` entries
//   `"N.<segment>"` with no further `.` in `<segment>`, whose target is
//   itself a scope owner (ruling out an author-labeled gather directly in
//   the knot, which shares the same two-segment path shape but is *not*
//   self-scoped).
//
// Both of these are compile-time/link-time structural facts already
// present on `Program` — no id arithmetic or heuristic string matching on
// unstructured names.

/// Group every non-scope-owning ("interior") container's own id by the
/// `DefinitionId` of its nearest enclosing knot/stitch/root scope.
///
/// Built once per non-fast-path [`ResolvedPolicy::resolve`] call — this is
/// resolve-time bookkeeping, not a hot-path lookup (the all-`World` fast
/// path never calls this at all).
fn interior_containers_by_scope(program: &Program) -> HashMap<DefinitionId, Vec<DefinitionId>> {
    let mut by_scope: HashMap<DefinitionId, Vec<DefinitionId>> = HashMap::new();
    for (idx, container) in program.containers.iter().enumerate() {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "container count fits in u32"
        )]
        let idx = idx as u32;
        let owner = program.scope_ids[program.scope_table_idx(idx) as usize];
        if owner != container.id {
            by_scope.entry(owner).or_default().push(container.id);
        }
    }
    by_scope
}

/// Apply `scope` to `id` and every interior container `interior_by_scope`
/// says is nested directly under it (i.e. `id`'s own subtree, one scope
/// level — not a recursive walk, since ink knots/stitches never nest
/// containers whose `scope_id` chain needs more than one enclosing-scope
/// hop to resolve; see `interior_containers_by_scope`).
fn apply_scope_to_subtree(
    interior_by_scope: &HashMap<DefinitionId, Vec<DefinitionId>>,
    knot_scopes: &mut HashMap<DefinitionId, Scope>,
    id: DefinitionId,
    scope: Scope,
) {
    knot_scopes.insert(id, scope);
    if let Some(interior) = interior_by_scope.get(&id) {
        for &child_id in interior {
            knot_scopes.insert(child_id, scope);
        }
    }
}

/// Expand a single `WorldPolicy::overrides` knot/stitch entry (`name` →
/// `id`, already resolved via `Program::find_path_target`) into every
/// `DefinitionId` in its definition subtree, writing `scope` for each into
/// `knot_scopes`.
///
/// Covers: `id`'s own subtree (its own id plus its direct interior
/// containers), then — since a stitch override's own call to this function
/// already covers everything a stitch can own, and ink never nests a
/// stitch under another stitch — cascades once to `name`'s direct child
/// stitches (found via `address_by_path`'s dotted grammar, see the module
/// docs above) and covers each of *their* subtrees too. A child stitch
/// that itself has a more specific override is still safe to cascade into
/// here: `resolve`'s `BTreeMap` iteration order guarantees the stitch's own
/// (later, more specific) entry is processed after `name`'s and overwrites
/// whatever this cascade wrote — see `resolve`'s docs.
fn expand_knot_scope(
    program: &Program,
    interior_by_scope: &HashMap<DefinitionId, Vec<DefinitionId>>,
    knot_scopes: &mut HashMap<DefinitionId, Scope>,
    name: &str,
    id: DefinitionId,
    scope: Scope,
) {
    apply_scope_to_subtree(interior_by_scope, knot_scopes, id, scope);

    let prefix = format!("{name}.");
    for (path, target) in &program.address_by_path {
        let Some(rest) = path.strip_prefix(prefix.as_str()) else {
            continue;
        };
        if rest.is_empty() || rest.contains('.') {
            continue; // Not a direct one-segment child of `name`.
        }
        if target.byte_offset != 0 {
            continue; // Not a container's own primary address.
        }
        // Confirm the target is itself a scope-owning container (a real
        // stitch), not an author-labeled gather directly in the knot that
        // happens to share the same two-segment path shape.
        let owner = program.scope_ids[program.scope_table_idx(target.container_idx) as usize];
        if owner != target.id {
            continue;
        }
        apply_scope_to_subtree(interior_by_scope, knot_scopes, target.id, scope);
    }
}

/// Shared game state that lives above individual flows.
///
/// Holds globals, visit/turn tracking, and RNG state. This is the natural
/// serialization boundary for save/load (deferred).
///
/// Multiple [`FlowInstance`](crate::FlowInstance)s can share a single
/// `World` (matching inklecate's semantics where flow writes are
/// immediately visible to other flows), or each flow can hold its own
/// cloned `World` if the consumer wants fork/branch/rollback semantics.
/// The runtime's step functions take `&mut World` (or any
/// `&mut impl ContextAccess`) without prescribing where it lives.
#[derive(Debug, Clone)]
pub struct World {
    pub globals: Vec<Value>,
    pub visit_counts: HashMap<DefinitionId, u32>,
    pub turn_counts: HashMap<DefinitionId, u32>,
    pub turn_index: u32,
    pub rng_seed: i32,
    pub previous_random: i32,
    /// The resolved world/local scoping policy for this world.
    ///
    /// Boxed so `World` (cloned per-flow-spawn and stored inline in several
    /// call sites and enums across the crate graph) doesn't balloon in size
    /// for consumers that never touch policy — `ResolvedPolicy` carries a
    /// per-slot `Vec` and a `HashMap` that dwarf `World`'s other fields.
    ///
    /// **Consulted by [`ContextView`] (F2.2 on)** to route every
    /// [`ContextAccess`] op between `World` and `FlowLocal`. Every
    /// construction path that predates policy (`World::from_globals`,
    /// `FlowInstance::new_at*`, `Story::new`) resolves
    /// [`WorldPolicy::default()`] (all-`World`), so those paths route every
    /// op straight to `World` — unchanged from F1.3.
    policy: Box<ResolvedPolicy>,
}

impl World {
    /// Create a fresh `World` for `program`, resolving `policy` against the
    /// program's symbol table.
    ///
    /// Globals are initialized from the program's declared defaults; visit
    /// counts, turn counts, turn index, and RNG state start zeroed —
    /// identical to `FlowInstance::new_at`'s inline construction. Fails if
    /// `policy` names a variable or knot/stitch the program doesn't
    /// declare ([`PolicyError::UnknownName`]).
    ///
    /// [`WorldPolicy::default()`] (all-`World`) always resolves — see
    /// [`ResolvedPolicy::all_world`] — so passing it here can't produce a
    /// `PolicyError`.
    pub fn new(program: &Program, policy: &WorldPolicy) -> Result<Self, PolicyError> {
        let resolved = ResolvedPolicy::resolve(program, policy)?;
        Ok(Self::from_globals(program.global_defaults(), resolved))
    }

    /// Build a `World` from an explicit globals vector and an
    /// already-resolved policy. Used by [`crate::FlowInstance::new_at`] (whose
    /// signature predates policy and can't take a `Result`) to construct
    /// the all-`World` default without re-deriving it from a `Program` each
    /// time.
    pub(crate) fn from_globals(globals: Vec<Value>, policy: ResolvedPolicy) -> Self {
        Self {
            globals,
            visit_counts: HashMap::new(),
            turn_counts: HashMap::new(),
            turn_index: 0,
            rng_seed: 0,
            previous_random: 0,
            policy: Box::new(policy),
        }
    }

    /// Construct a `World` directly from its field values, with the
    /// all-`World` policy. Only for test fixtures that need to hand-build a
    /// `World` without a `Program` (e.g. `bevy-brink`'s commit-merge
    /// tests) — production code should go through [`World::new`].
    #[cfg(feature = "testing")]
    #[must_use]
    pub fn new_for_testing(
        globals: Vec<Value>,
        visit_counts: HashMap<DefinitionId, u32>,
        turn_counts: HashMap<DefinitionId, u32>,
        turn_index: u32,
        rng_seed: i32,
        previous_random: i32,
    ) -> Self {
        Self {
            globals,
            visit_counts,
            turn_counts,
            turn_index,
            rng_seed,
            previous_random,
            policy: Box::new(ResolvedPolicy::all_world()),
        }
    }
}

/// A flow-local override of the shared RNG stream (`rng_seed` +
/// `previous_random`), the two scalars [`WorldPolicy::rng`] scopes as a
/// single unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LocalRng {
    pub seed: i32,
    pub previous_random: i32,
}

/// An immutable snapshot of a [`FlowLocal`]'s override layer, frozen via
/// [`FlowLocal::freeze`].
///
/// `FrozenLocal` chains: its own `base` is whatever the source `FlowLocal`'s
/// base was at freeze time, so a chain of forks ([`FlowLocal::fork`]) can
/// walk arbitrarily far back through frozen ancestors. Cloning a
/// `FrozenLocal` reference is cheap — callers hold it behind an [`Arc`].
#[derive(Debug, Clone, Default)]
pub struct FrozenLocal {
    /// Overridden values for globals `ResolvedPolicy` homes to `Local`,
    /// keyed by slot index.
    globals: BTreeMap<u32, Value>,
    /// Overridden visit counts for knots/stitches homed to `Local`.
    visit_counts: BTreeMap<DefinitionId, u32>,
    /// Overridden turn counts for knots homed to `Local`.
    turn_counts: BTreeMap<DefinitionId, u32>,
    /// Overridden turn index, when `turn_index_scope() == Local`.
    turn_index: Option<u32>,
    /// Overridden RNG stream, when `rng_scope() == Local`.
    rng: Option<LocalRng>,
    /// The next link in the chain, if this snapshot's source `FlowLocal`
    /// itself had a base at freeze time.
    base: Option<Arc<FrozenLocal>>,
}

impl FrozenLocal {
    /// Chain-lookup a global override: this snapshot's own overrides, else
    /// recurse into `base`. Returns `None` on a miss all the way down the
    /// chain — the caller falls through to `World`.
    fn chain_get_global(&self, idx: u32) -> Option<&Value> {
        self.globals
            .get(&idx)
            .or_else(|| self.base.as_deref().and_then(|b| b.chain_get_global(idx)))
    }

    /// Chain-lookup a visit-count override.
    fn chain_get_visit_count(&self, id: DefinitionId) -> Option<u32> {
        self.visit_counts.get(&id).copied().or_else(|| {
            self.base
                .as_deref()
                .and_then(|b| b.chain_get_visit_count(id))
        })
    }

    /// Chain-lookup a turn-count override.
    fn chain_get_turn_count(&self, id: DefinitionId) -> Option<u32> {
        self.turn_counts.get(&id).copied().or_else(|| {
            self.base
                .as_deref()
                .and_then(|b| b.chain_get_turn_count(id))
        })
    }

    /// Chain-lookup the overridden turn index.
    fn chain_get_turn_index(&self) -> Option<u32> {
        self.turn_index.or_else(|| {
            self.base
                .as_deref()
                .and_then(FrozenLocal::chain_get_turn_index)
        })
    }

    /// Chain-lookup the overridden RNG stream.
    fn chain_get_rng(&self) -> Option<LocalRng> {
        self.rng
            .or_else(|| self.base.as_deref().and_then(FrozenLocal::chain_get_rng))
    }
}

/// Execution mode of a [`FlowLocal`], baked in at construction/fork time and
/// read by [`ContextView`] to decide how it routes every unit.
///
/// `Mode` is orthogonal to [`WorldPolicy`]/[`ResolvedPolicy`]: policy homes a
/// *unit* (a global, a knot's visit count, …) to `World` or `Local`; `Mode`
/// decides, for *this flow*, whether that homing is honored at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    /// Route every unit by policy, exactly as [`ContextView`]'s F2.2/F3.1
    /// docs describe: `World`-scoped units go straight to `World`,
    /// `Local`-scoped units chain-read-through/write to `FlowLocal`. Every
    /// construction path before F3.2 produces `Mode::Normal` — this is what
    /// keeps the oracle corpus byte-identical.
    #[default]
    Normal,
    /// Treat **every** unit as `Local`, regardless of policy: the shared
    /// `World` becomes a read-only base for this flow. Reads still
    /// chain-read-through to `World`'s current value on a total miss (so a
    /// sandboxed flow sees live world state), but writes always land in
    /// this flow's own top-layer overrides — `World` (and any `Normal`
    /// ancestor) is never mutated. Combined with [`FlowLocal::fork`]'s
    /// frozen base, this is the side-effect-proof primitive watch/eval
    /// needs: run a flow against current state, observe its output, then
    /// discard it (drop) with the shared world untouched.
    Sandbox,
}

/// Per-flow override layer over the shared [`World`].
///
/// **F3.1: copy-on-write, frozen-base read-through chain.** Each field is a
/// plain map/option holding this flow's own overrides for units
/// [`ResolvedPolicy`] homes to [`Scope::Local`] (or, in [`Mode::Sandbox`],
/// *every* unit — see [`Mode`]), plus an optional `base`: an immutable
/// [`FrozenLocal`] snapshot (see [`FlowLocal::freeze`]) of another
/// `FlowLocal`, captured at some earlier point. A read walks **own
/// overrides → base (recursively) → [miss]**; [`ContextView`] treats a miss
/// as "not in the local chain" and falls through to `World`, exactly as in
/// F2.2. Writes always land in the flow's own top-layer overrides — never
/// in `base`, which is immutable by construction.
///
/// A fresh `FlowLocal` (via `Default`/[`FlowLocal::new`]) has empty
/// overrides, `base: None`, and `mode: Mode::Normal`, so it contributes no
/// reads and every access falls through to `World` — this is what keeps the
/// all-`World` policy (and every construction path that doesn't call
/// [`fork`](Self::fork)) byte-identical to the F2.2 flat-storage behavior.
/// [`FlowLocal::fork`] (F3.2) is what actually populates a child's `base` by
/// freezing its parent, and what bakes in a non-`Normal` `mode`.
///
/// [`ContextView`] (below) is what actually consults these maps; see its
/// docs for the read-through/copy-on-write-increment/mode semantics.
#[derive(Debug, Clone, Default)]
pub struct FlowLocal {
    /// Overridden values for globals `ResolvedPolicy` homes to `Local`,
    /// keyed by slot index.
    globals: BTreeMap<u32, Value>,
    /// Overridden visit counts for knots/stitches homed to `Local`.
    visit_counts: BTreeMap<DefinitionId, u32>,
    /// Overridden turn counts for knots homed to `Local`.
    turn_counts: BTreeMap<DefinitionId, u32>,
    /// Overridden turn index, when `turn_index_scope() == Local`.
    turn_index: Option<u32>,
    /// Overridden RNG stream, when `rng_scope() == Local`.
    rng: Option<LocalRng>,
    /// Frozen snapshot of an earlier `FlowLocal`'s overrides, read *after*
    /// this layer's own overrides on a miss. Populated by [`FlowLocal::fork`];
    /// `None` for every construction path that doesn't fork.
    base: Option<Arc<FrozenLocal>>,
    /// This flow's execution mode — see [`Mode`]. Baked in at construction
    /// (`Mode::Normal`, the `Default`) or at [`FlowLocal::fork`] time.
    mode: Mode,
}

impl FlowLocal {
    /// Construct an empty flow-local layer — overrides nothing and has no
    /// base, so every access routes through to `World`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Freeze this `FlowLocal`'s current state into an immutable
    /// [`FrozenLocal`] snapshot, suitable for use as another `FlowLocal`'s
    /// `base`.
    ///
    /// Captures the override maps (cloned — cheap, since only `Local`-scoped
    /// units are ever present) and cheap-clones the current `base` `Arc` so
    /// the new snapshot chains to the same ancestry this `FlowLocal` had.
    ///
    /// Called by [`FlowLocal::fork`] to snapshot a parent into a child's
    /// `base`.
    #[must_use]
    fn freeze(&self) -> Arc<FrozenLocal> {
        Arc::new(FrozenLocal {
            globals: self.globals.clone(),
            visit_counts: self.visit_counts.clone(),
            turn_counts: self.turn_counts.clone(),
            turn_index: self.turn_index,
            rng: self.rng,
            base: self.base.clone(),
        })
    }

    /// Fork a child `FlowLocal` from this one.
    ///
    /// The child's `base` is a frozen, point-in-time snapshot of `self` (via
    /// [`freeze`](Self::freeze)) — an `O(1)`-ish operation that clones this
    /// flow's own (small) override maps and `Arc`-bumps the rest of the
    /// ancestry chain, never a full `World` copy. The child's own override
    /// layer starts empty, and it runs in `mode` for its lifetime (`Mode` is
    /// baked in here, not mutable afterward).
    ///
    /// Because the base is frozen, later mutations to `self` (the parent)
    /// are **not** visible to the child — the child sees the parent exactly
    /// as it was at fork time. Symmetrically, nothing the child does is ever
    /// visible to `self` or `World`: writes land only in the child's own top
    /// layer (see [`Mode`] for how `Sandbox` additionally diverts
    /// `World`-scoped writes there too). That makes **discard** trivial —
    /// dropping the returned `FlowLocal` is the entire discard operation, no
    /// unwinding required. Folding a child's writes back into `self` instead
    /// of discarding them is the deferred `commit` seam — see [`CommitError`]
    /// and [`commit`].
    #[must_use]
    pub fn fork(&self, mode: Mode) -> FlowLocal {
        FlowLocal {
            base: Some(self.freeze()),
            mode,
            ..FlowLocal::new()
        }
    }

    /// Chain-lookup a global override: own overrides → `base` (recursively)
    /// → `None` on a total miss, which [`ContextView`] treats as "fall
    /// through to `World`".
    fn chain_get_global(&self, idx: u32) -> Option<&Value> {
        self.globals
            .get(&idx)
            .or_else(|| self.base.as_deref().and_then(|b| b.chain_get_global(idx)))
    }

    /// Chain-lookup a visit-count override.
    fn chain_get_visit_count(&self, id: DefinitionId) -> Option<u32> {
        self.visit_counts.get(&id).copied().or_else(|| {
            self.base
                .as_deref()
                .and_then(|b| b.chain_get_visit_count(id))
        })
    }

    /// Chain-lookup a turn-count override.
    fn chain_get_turn_count(&self, id: DefinitionId) -> Option<u32> {
        self.turn_counts.get(&id).copied().or_else(|| {
            self.base
                .as_deref()
                .and_then(|b| b.chain_get_turn_count(id))
        })
    }

    /// Chain-lookup the overridden turn index.
    fn chain_get_turn_index(&self) -> Option<u32> {
        self.turn_index.or_else(|| {
            self.base
                .as_deref()
                .and_then(FrozenLocal::chain_get_turn_index)
        })
    }

    /// Chain-lookup the overridden RNG stream.
    fn chain_get_rng(&self) -> Option<LocalRng> {
        self.rng
            .or_else(|| self.base.as_deref().and_then(FrozenLocal::chain_get_rng))
    }
}

/// Errors from [`commit`].
///
/// A single variant today: `commit` is a documented, deferred seam (see
/// `docs/scoped-flow-state-spec.md`, "Write-back is determined by scope, not
/// a separate knob") — this release ships fork + discard only.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum CommitError {
    /// Folding a forked child's own-layer overrides back into its parent is
    /// deferred past this release. Fork's only supported terminal operation
    /// today is **discard** (drop the child); `commit` always returns this.
    #[error(
        "commit is not implemented in this release; fork's only supported terminal operation is discard (drop the child)"
    )]
    NotImplemented,
}

/// Fold a forked child's own-layer overrides back into its parent's,
/// making the child's writes visible through `parent` (and, transitively,
/// anything `parent` itself chains to or is later written through).
///
/// **This is a deferred seam, not implemented in this release.** It exists
/// so the shape of the eventual write-back API is fixed and callers can
/// write code against it now (always getting `CommitError::NotImplemented`
/// back) rather than the API appearing later with no forward-compatible
/// slot. Per the spec, only a **fork** ever commits — a root flow has no
/// parent to fold into, and its `Local`-scoped writes already persist for
/// its own lifetime; `World`-scoped writes already escape live, with no
/// "make it back" step needed.
///
/// Intended semantics, when implemented: walk `child`'s own top-layer
/// overrides (globals, visit counts, turn counts, turn index, RNG) and
/// apply each onto `parent`'s own top layer, as if `child`'s writes had
/// been made directly against `parent` — last-write-wins per unit, since a
/// fork is single-writer for its whole lifetime (no concurrent-write
/// conflict is possible, so no merge policy is needed). Commit never
/// touches `World` directly: a folded `Local`-scoped write still only
/// lands in `parent`'s overrides, reaching `World` only if `parent` is
/// itself later written through a `World`-scoped op or committed further up
/// the chain. `Sandbox`-mode writes are exactly what this would fold
/// back — commit is what would turn a sandboxed probe into a real,
/// persisted mutation, for a caller that chooses to call it instead of
/// dropping the child.
///
/// # Errors
///
/// Always returns [`CommitError::NotImplemented`] in this release.
pub fn commit(_child: FlowLocal, _parent: &mut FlowLocal) -> Result<(), CommitError> {
    Err(CommitError::NotImplemented)
}

/// Routing view implementing [`ContextAccess`] over `(&mut World, &mut
/// FlowLocal)`.
///
/// This is what the VM's drive path receives as its `impl ContextAccess`.
/// Every op computes an **effective scope** for its unit — see
/// [`ContextView::effective_scope`] — and then routes exactly as before:
///
/// - **`World`-scoped**: always routes straight to `World` — reads and
///   writes are immediately visible to every flow sharing that `World`.
/// - **`Local`-scoped, read**: **chain read-through** — walks the
///   `FlowLocal`'s own overrides, then its frozen `base` (recursively, see
///   [`FlowLocal::chain_get_global`] and friends), then falls back to
///   `World`'s current value on a total miss (so a flow that has never
///   written a Local unit, nor inherited one from a base, sees the shared
///   default until its first local write).
/// - **`Local`-scoped, write**: lands in the `FlowLocal`'s own top-layer
///   overrides only; `World` (and any frozen `base`) is untouched.
/// - **`Local`-scoped, increment** (`increment_visit`,
///   `increment_turn_index`): copy-on-write from the *chain read-through*
///   value — read the current value (own override, else base chain, else
///   World fallback), add one, store the result as the new top-layer
///   override. This is what makes a flow's first local increment start
///   from the chain's (or World's) count rather than 0.
///
/// **The effective scope, not the raw policy scope, drives all of the
/// above.** In [`Mode::Normal`] (every construction path before F3.2, and
/// every non-forked flow today) the effective scope of a unit *is* its
/// `ResolvedPolicy` scope — unchanged from F2.2/F3.1. In [`Mode::Sandbox`]
/// the effective scope of **every** unit is `Local`, no matter what the
/// policy says: a sandboxed flow's reads still chain-read-through to
/// `World`'s live value on a miss (so it observes current shared state),
/// but its writes — including to units the policy homes to `World` — land
/// only in its own `FlowLocal` overrides. `World` is therefore a read-only
/// base from a sandboxed flow's perspective: nothing it does can mutate the
/// shared world.
///
/// Because the all-`World` policy (the only policy the oracle corpus
/// exercises) takes the `World` branch on every op *and* no existing
/// construction path ever sets `Mode::Sandbox`, this is byte-identical to
/// the F1.3 all-`World` passthrough for every existing single-flow
/// construction path.
pub struct ContextView<'a> {
    world: &'a mut World,
    local: &'a mut FlowLocal,
}

impl<'a> ContextView<'a> {
    /// Build a routing view over a `World` and `FlowLocal` pair for the
    /// duration of one step.
    pub fn new(world: &'a mut World, local: &'a mut FlowLocal) -> Self {
        Self { world, local }
    }

    /// The scope a unit actually routes by: `policy_scope` in
    /// [`Mode::Normal`], or unconditionally [`Scope::Local`] in
    /// [`Mode::Sandbox`] — see the type docs above.
    #[inline]
    fn effective_scope(&self, policy_scope: Scope) -> Scope {
        match self.local.mode {
            Mode::Normal => policy_scope,
            Mode::Sandbox => Scope::Local,
        }
    }
}

impl ContextAccess for World {
    #[inline]
    fn global(&self, idx: u32) -> &Value {
        &self.globals[idx as usize]
    }

    #[inline]
    fn set_global(&mut self, idx: u32, value: Value) {
        self.globals[idx as usize] = value;
    }

    #[inline]
    fn visit_count(&self, id: DefinitionId) -> u32 {
        self.visit_counts.get(&id).copied().unwrap_or(0)
    }

    #[inline]
    fn increment_visit(&mut self, id: DefinitionId) {
        *self.visit_counts.entry(id).or_insert(0) += 1;
    }

    #[inline]
    fn set_visit_count(&mut self, id: DefinitionId, count: u32) {
        self.visit_counts.insert(id, count);
    }

    #[inline]
    fn turn_count(&self, id: DefinitionId) -> Option<u32> {
        self.turn_counts.get(&id).copied()
    }

    #[inline]
    fn set_turn_count(&mut self, id: DefinitionId, turn: u32) {
        self.turn_counts.insert(id, turn);
    }

    #[inline]
    fn turn_index(&self) -> u32 {
        self.turn_index
    }

    #[inline]
    fn increment_turn_index(&mut self) {
        self.turn_index += 1;
    }

    #[inline]
    fn set_turn_index(&mut self, index: u32) {
        self.turn_index = index;
    }

    #[inline]
    fn rng_seed(&self) -> i32 {
        self.rng_seed
    }

    #[inline]
    fn set_rng_seed(&mut self, seed: i32) {
        self.rng_seed = seed;
    }

    #[inline]
    fn previous_random(&self) -> i32 {
        self.previous_random
    }

    #[inline]
    fn set_previous_random(&mut self, val: i32) {
        self.previous_random = val;
    }

    #[inline]
    fn next_random<R: StoryRng>(&self, seed: i32) -> i32 {
        let mut rng = R::from_seed(seed);
        rng.next_int()
    }

    fn random_sequence<R: StoryRng>(&self, seed: i32, count: usize) -> Vec<i32> {
        let mut rng = R::from_seed(seed);
        (0..count).map(|_| rng.next_int()).collect()
    }
}

impl ContextAccess for ContextView<'_> {
    #[inline]
    fn global(&self, idx: u32) -> &Value {
        match self.effective_scope(self.world.policy.scope_of_global(idx)) {
            Scope::Local => self
                .local
                .chain_get_global(idx)
                .unwrap_or_else(|| self.world.global(idx)),
            Scope::World => self.world.global(idx),
        }
    }

    #[inline]
    fn set_global(&mut self, idx: u32, value: Value) {
        match self.effective_scope(self.world.policy.scope_of_global(idx)) {
            Scope::Local => {
                self.local.globals.insert(idx, value);
            }
            Scope::World => self.world.set_global(idx, value),
        }
    }

    #[inline]
    fn visit_count(&self, id: DefinitionId) -> u32 {
        match self.effective_scope(self.world.policy.scope_of_knot(id)) {
            Scope::Local => self
                .local
                .chain_get_visit_count(id)
                .unwrap_or_else(|| self.world.visit_count(id)),
            Scope::World => self.world.visit_count(id),
        }
    }

    #[inline]
    fn increment_visit(&mut self, id: DefinitionId) {
        match self.effective_scope(self.world.policy.scope_of_knot(id)) {
            Scope::Local => {
                let base = self.visit_count(id);
                self.local.visit_counts.insert(id, base + 1);
            }
            Scope::World => self.world.increment_visit(id),
        }
    }

    #[inline]
    fn set_visit_count(&mut self, id: DefinitionId, count: u32) {
        match self.effective_scope(self.world.policy.scope_of_knot(id)) {
            Scope::Local => {
                self.local.visit_counts.insert(id, count);
            }
            Scope::World => self.world.set_visit_count(id, count),
        }
    }

    #[inline]
    fn turn_count(&self, id: DefinitionId) -> Option<u32> {
        match self.effective_scope(self.world.policy.scope_of_knot(id)) {
            Scope::Local => self
                .local
                .chain_get_turn_count(id)
                .or_else(|| self.world.turn_count(id)),
            Scope::World => self.world.turn_count(id),
        }
    }

    #[inline]
    fn set_turn_count(&mut self, id: DefinitionId, turn: u32) {
        match self.effective_scope(self.world.policy.scope_of_knot(id)) {
            Scope::Local => {
                self.local.turn_counts.insert(id, turn);
            }
            Scope::World => self.world.set_turn_count(id, turn),
        }
    }

    #[inline]
    fn turn_index(&self) -> u32 {
        match self.effective_scope(self.world.policy.turn_index_scope()) {
            Scope::Local => self
                .local
                .chain_get_turn_index()
                .unwrap_or_else(|| self.world.turn_index()),
            Scope::World => self.world.turn_index(),
        }
    }

    #[inline]
    fn increment_turn_index(&mut self) {
        match self.effective_scope(self.world.policy.turn_index_scope()) {
            Scope::Local => {
                let base = self.turn_index();
                self.local.turn_index = Some(base + 1);
            }
            Scope::World => self.world.increment_turn_index(),
        }
    }

    #[inline]
    fn set_turn_index(&mut self, index: u32) {
        match self.effective_scope(self.world.policy.turn_index_scope()) {
            Scope::Local => {
                self.local.turn_index = Some(index);
            }
            Scope::World => self.world.set_turn_index(index),
        }
    }

    #[inline]
    fn rng_seed(&self) -> i32 {
        match self.effective_scope(self.world.policy.rng_scope()) {
            Scope::Local => self
                .local
                .chain_get_rng()
                .map_or_else(|| self.world.rng_seed(), |rng| rng.seed),
            Scope::World => self.world.rng_seed(),
        }
    }

    #[inline]
    fn set_rng_seed(&mut self, seed: i32) {
        match self.effective_scope(self.world.policy.rng_scope()) {
            Scope::Local => {
                // CoW from the chain read-through value: seed a fresh local
                // override from the base chain's RNG if present, else World.
                // (base is always None in F3.1, so this reduces to World.)
                let fallback = self.local.chain_get_rng().unwrap_or(LocalRng {
                    seed: self.world.rng_seed(),
                    previous_random: self.world.previous_random(),
                });
                let rng = self.local.rng.get_or_insert(fallback);
                rng.seed = seed;
            }
            Scope::World => self.world.set_rng_seed(seed),
        }
    }

    #[inline]
    fn previous_random(&self) -> i32 {
        match self.effective_scope(self.world.policy.rng_scope()) {
            Scope::Local => self
                .local
                .chain_get_rng()
                .map_or_else(|| self.world.previous_random(), |rng| rng.previous_random),
            Scope::World => self.world.previous_random(),
        }
    }

    #[inline]
    fn set_previous_random(&mut self, val: i32) {
        match self.effective_scope(self.world.policy.rng_scope()) {
            Scope::Local => {
                // CoW from the chain read-through value (see `set_rng_seed`).
                let fallback = self.local.chain_get_rng().unwrap_or(LocalRng {
                    seed: self.world.rng_seed(),
                    previous_random: self.world.previous_random(),
                });
                let rng = self.local.rng.get_or_insert(fallback);
                rng.previous_random = val;
            }
            Scope::World => self.world.set_previous_random(val),
        }
    }

    #[inline]
    fn next_random<R: StoryRng>(&self, seed: i32) -> i32 {
        // Pure function of the explicit `seed` argument — not routed
        // state, so this delegates to `World`'s implementation unchanged.
        // The routed `rng_seed()` above is what call sites read to obtain
        // `seed` in the first place.
        self.world.next_random::<R>(seed)
    }

    fn random_sequence<R: StoryRng>(&self, seed: i32, count: usize) -> Vec<i32> {
        self.world.random_sequence::<R>(seed, count)
    }
}

#[cfg(test)]
mod policy_tests {
    use super::*;
    use crate::link;

    /// Compile a small ink story with the brink compiler and link it, for
    /// resolving policies against a real `Program` symbol table.
    fn compile(src: &str) -> Program {
        let out = brink_compiler::compile("t.ink", |p| {
            if p == "t.ink" {
                Ok(src.to_string())
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "no such include",
                ))
            }
        })
        .expect("compile");
        let (program, _line_tables) = link(&out.data).expect("link");
        program
    }

    fn sample_program() -> Program {
        compile(
            "VAR gold = 0\n\
             VAR mood = 0\n\
             -> shrine\n\
             === shrine ===\n\
             At the shrine.\n\
             -> END\n\
             === cellar ===\n\
             In the cellar.\n\
             -> END\n",
        )
    }

    /// The default `WorldPolicy` (all-`World`) must resolve via the fast
    /// path — no name lookups — and every scope must read back as `World`.
    #[test]
    fn all_world_default_resolves_via_fast_path() {
        let program = sample_program();
        let policy = WorldPolicy::default();

        let resolved = ResolvedPolicy::resolve(&program, &policy).expect("resolves");

        // Fast path: no per-slot table populated.
        assert!(resolved.global_scopes.is_empty());
        assert!(resolved.knot_scopes.is_empty());

        let gold_slot = program.global_index("gold").expect("gold declared");
        let mood_slot = program.global_index("mood").expect("mood declared");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");
        let cellar_id = program.find_path_target("cellar").expect("cellar exists");

        assert_eq!(resolved.scope_of_global(gold_slot), Scope::World);
        assert_eq!(resolved.scope_of_global(mood_slot), Scope::World);
        assert_eq!(resolved.scope_of_knot(shrine_id), Scope::World);
        assert_eq!(resolved.scope_of_knot(cellar_id), Scope::World);
        assert_eq!(resolved.turn_index_scope(), Scope::World);
        assert_eq!(resolved.rng_scope(), Scope::World);
    }

    /// A policy with `default: Local` plus explicit variable and knot
    /// overrides resolves each override to its named scope and leaves
    /// everything else at the default.
    #[test]
    fn resolves_valid_variable_and_knot_overrides() {
        let program = sample_program();
        let mut overrides = BTreeMap::new();
        overrides.insert("gold".to_owned(), Scope::World);
        overrides.insert("shrine".to_owned(), Scope::World);
        let policy = WorldPolicy {
            default: Scope::Local,
            overrides,
            turn_index: Scope::Local,
            rng: Scope::Local,
        };

        let resolved = ResolvedPolicy::resolve(&program, &policy).expect("resolves");

        let gold_slot = program.global_index("gold").expect("gold declared");
        let mood_slot = program.global_index("mood").expect("mood declared");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");
        let cellar_id = program.find_path_target("cellar").expect("cellar exists");

        // Named overrides win.
        assert_eq!(resolved.scope_of_global(gold_slot), Scope::World);
        assert_eq!(resolved.scope_of_knot(shrine_id), Scope::World);

        // Unlisted variable/knot fall back to `default`.
        assert_eq!(resolved.scope_of_global(mood_slot), Scope::Local);
        assert_eq!(resolved.scope_of_knot(cellar_id), Scope::Local);

        // Scalars resolve independently of `overrides`.
        assert_eq!(resolved.turn_index_scope(), Scope::Local);
        assert_eq!(resolved.rng_scope(), Scope::Local);
    }

    /// A name in `overrides` that matches neither a declared variable nor a
    /// resolvable knot/stitch path is a `PolicyError`, not a silent
    /// fallback to `default`.
    #[test]
    fn unknown_override_name_is_an_error() {
        let program = sample_program();
        let mut overrides = BTreeMap::new();
        overrides.insert("not_a_real_name".to_owned(), Scope::World);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };

        let err = ResolvedPolicy::resolve(&program, &policy).expect_err("must fail");
        assert_eq!(err, PolicyError::UnknownName("not_a_real_name".to_owned()));
    }

    /// `World::new` resolves the policy and constructs a `World` whose
    /// globals match the program's declared defaults.
    #[test]
    fn world_new_resolves_policy_and_initializes_globals() {
        let program = sample_program();
        let world = World::new(&program, &WorldPolicy::default()).expect("world builds");
        assert_eq!(world.globals, program.global_defaults());
    }

    /// `World::new` propagates the resolver's error for an unknown override
    /// name rather than panicking or silently ignoring it.
    #[test]
    fn world_new_propagates_unknown_name_error() {
        let program = sample_program();
        let mut overrides = BTreeMap::new();
        overrides.insert("nonexistent".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            overrides,
            ..WorldPolicy::default()
        };

        let err = World::new(&program, &policy).expect_err("must fail");
        assert_eq!(err, PolicyError::UnknownName("nonexistent".to_owned()));
    }
}

#[cfg(test)]
mod routing_tests {
    use super::*;
    use crate::link;

    /// Compile a small ink story with the brink compiler and link it, for
    /// resolving policies against a real `Program` symbol table.
    fn compile(src: &str) -> Program {
        let out = brink_compiler::compile("t.ink", |p| {
            if p == "t.ink" {
                Ok(src.to_string())
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "no such include",
                ))
            }
        })
        .expect("compile");
        let (program, _line_tables) = link(&out.data).expect("link");
        program
    }

    fn sample_program() -> Program {
        compile(
            "VAR gold = 0\n\
             VAR mood = 0\n\
             -> shrine\n\
             === shrine ===\n\
             At the shrine.\n\
             -> END\n\
             === cellar ===\n\
             In the cellar.\n\
             -> END\n",
        )
    }

    /// `mood` is Local, `gold` stays World (the default). `shrine`/`cellar`
    /// are left at the World default too, so visit counts there stay
    /// shared — exercised separately below.
    fn mixed_policy() -> WorldPolicy {
        let mut overrides = BTreeMap::new();
        overrides.insert("mood".to_owned(), Scope::Local);
        WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        }
    }

    /// Writing a `Local`-scoped global in one flow must not affect another
    /// flow's `ContextView` over the same `World`, nor the `World` itself.
    /// Writing a `World`-scoped global in one flow must be immediately
    /// visible through another flow's `ContextView`.
    #[test]
    fn local_write_isolated_world_write_shared() {
        let program = sample_program();
        let policy = mixed_policy();
        let mut world = World::new(&program, &policy).expect("world builds");

        let gold_slot = program.global_index("gold").expect("gold declared");
        let mood_slot = program.global_index("mood").expect("mood declared");

        let mut local_a = FlowLocal::new();
        let mut local_b = FlowLocal::new();

        // Flow A writes its Local `mood`.
        {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            view_a.set_global(mood_slot, Value::Int(42));
            assert_eq!(view_a.global(mood_slot), &Value::Int(42));
        }

        // Flow B's view over the same World must not see A's local write —
        // it read-throughs to World's untouched default.
        {
            let view_b = ContextView::new(&mut world, &mut local_b);
            assert_eq!(view_b.global(mood_slot), &Value::Int(0));
            // World itself is untouched too.
            assert_eq!(world.global(mood_slot), &Value::Int(0));
        }

        // Flow A writes its World-scoped `gold` — this must be immediately
        // visible via Flow B's view (and via World directly).
        {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            view_a.set_global(gold_slot, Value::Int(7));
        }
        {
            let view_b = ContextView::new(&mut world, &mut local_b);
            assert_eq!(view_b.global(gold_slot), &Value::Int(7));
        }
        assert_eq!(world.global(gold_slot), &Value::Int(7));
    }

    /// Local visit counts increment independently per flow, while a
    /// World-scoped knot's visits are shared across flows.
    #[test]
    fn local_visits_independent_world_visits_shared() {
        let program = sample_program();

        // shrine: Local: cellar stays at the World default.
        let mut overrides = BTreeMap::new();
        overrides.insert("shrine".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let mut world = World::new(&program, &policy).expect("world builds");

        let shrine_id = program.find_path_target("shrine").expect("shrine exists");
        let cellar_id = program.find_path_target("cellar").expect("cellar exists");

        let mut local_a = FlowLocal::new();
        let mut local_b = FlowLocal::new();

        // Flow A visits `shrine` (Local) twice.
        {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            view_a.increment_visit(shrine_id);
            view_a.increment_visit(shrine_id);
            assert_eq!(view_a.visit_count(shrine_id), 2);
        }
        // Flow B's local shrine count is independent — still 0.
        {
            let view_b = ContextView::new(&mut world, &mut local_b);
            assert_eq!(view_b.visit_count(shrine_id), 0);
        }
        // World's own bookkeeping for a Local-scoped knot is never touched.
        assert_eq!(world.visit_count(shrine_id), 0);

        // `cellar` (World-scoped): Flow A's increment is visible to Flow B.
        {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            view_a.increment_visit(cellar_id);
        }
        {
            let view_b = ContextView::new(&mut world, &mut local_b);
            assert_eq!(view_b.visit_count(cellar_id), 1);
        }
        assert_eq!(world.visit_count(cellar_id), 1);
    }

    /// A `Local`-scoped global reads through to World's current value until
    /// the flow performs its first local write.
    #[test]
    fn local_read_through_returns_world_default_before_first_write() {
        let program = sample_program();
        let policy = mixed_policy();
        let mut world = World::new(&program, &policy).expect("world builds");
        let mood_slot = program.global_index("mood").expect("mood declared");

        // World's `mood` starts at the program default (0). A later World
        // write (e.g. host bootstrapping) should read through too, since A
        // hasn't written its own local override yet.
        world.set_global(mood_slot, Value::Int(99));

        let mut local_a = FlowLocal::new();
        let view_a = ContextView::new(&mut world, &mut local_a);
        assert_eq!(view_a.global(mood_slot), &Value::Int(99));
    }

    /// Local visit-count increment is copy-on-write from the read-through
    /// value: if World already has a nonzero count when Local is scoped
    /// in, the flow's first local increment starts from that base, not 0.
    #[test]
    fn local_increment_is_cow_from_read_through_base() {
        let program = sample_program();
        let mut overrides = BTreeMap::new();
        overrides.insert("shrine".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let mut world = World::new(&program, &policy).expect("world builds");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");

        // Seed World's bookkeeping directly (simulating pre-existing shared
        // state before this knot was scoped Local for this flow).
        world.increment_visit(shrine_id);
        world.increment_visit(shrine_id);
        assert_eq!(world.visit_count(shrine_id), 2);

        let mut local_a = FlowLocal::new();
        let mut view_a = ContextView::new(&mut world, &mut local_a);
        // First local increment must start from World's base (2), not 0.
        view_a.increment_visit(shrine_id);
        assert_eq!(view_a.visit_count(shrine_id), 3);

        // World's own count is untouched by the Local increment.
        assert_eq!(world.visit_count(shrine_id), 2);
    }

    /// F3.1 chain read-through: a `FlowLocal` with a frozen `base` reads a
    /// value from the base when its own top layer has no override, and its
    /// own top-layer override shadows the base. Values that appear in
    /// neither layer still fall through to `World`.
    ///
    /// Built by hand (no fork exists yet — that's F3.2): freeze a parent
    /// `FlowLocal` that has some overrides, then attach that snapshot as a
    /// child's `base`.
    #[test]
    fn chain_read_through_reads_base_and_top_shadows() {
        let program = sample_program();

        // Home both globals, both knots, turn index, and RNG to Local so the
        // chain (not World) is what's exercised on every read.
        let mut overrides = BTreeMap::new();
        overrides.insert("gold".to_owned(), Scope::Local);
        overrides.insert("mood".to_owned(), Scope::Local);
        overrides.insert("shrine".to_owned(), Scope::Local);
        overrides.insert("cellar".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::Local,
            rng: Scope::Local,
        };
        let mut world = World::new(&program, &policy).expect("world builds");

        let gold_slot = program.global_index("gold").expect("gold declared");
        let mood_slot = program.global_index("mood").expect("mood declared");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");
        let cellar_id = program.find_path_target("cellar").expect("cellar exists");

        // World defaults are distinct from anything we put in the chain, so a
        // read hitting World rather than the chain would be visible.
        world.set_global(gold_slot, Value::Int(1));
        world.set_global(mood_slot, Value::Int(1));

        // Build a parent FlowLocal with overrides, then freeze it.
        let mut parent = FlowLocal::new();
        {
            let mut pv = ContextView::new(&mut world, &mut parent);
            pv.set_global(gold_slot, Value::Int(100));
            pv.set_global(mood_slot, Value::Int(200));
            pv.increment_visit(shrine_id); // parent shrine visit = 1
            pv.set_turn_count(cellar_id, 5);
            pv.increment_turn_index(); // parent turn index = 1
            pv.set_rng_seed(777);
        }
        let base = parent.freeze();

        // Child inherits the frozen parent as its base, with its own empty
        // top layer.
        let mut child = FlowLocal {
            base: Some(base),
            ..FlowLocal::new()
        };

        // Reads with an empty top layer see the base's values (not World's).
        {
            let view = ContextView::new(&mut world, &mut child);
            assert_eq!(view.global(gold_slot), &Value::Int(100));
            assert_eq!(view.global(mood_slot), &Value::Int(200));
            assert_eq!(view.visit_count(shrine_id), 1);
            assert_eq!(view.turn_count(cellar_id), Some(5));
            assert_eq!(view.turn_index(), 1);
            assert_eq!(view.rng_seed(), 777);
        }

        // A top-layer override shadows the base for that one unit; other
        // units keep reading through to the base.
        {
            let mut view = ContextView::new(&mut world, &mut child);
            view.set_global(gold_slot, Value::Int(999));
            assert_eq!(view.global(gold_slot), &Value::Int(999)); // shadowed
            assert_eq!(view.global(mood_slot), &Value::Int(200)); // still base
        }

        // A knot with no override anywhere in the chain falls through to
        // World (whose count for the Local-scoped `cellar` is untouched: 0).
        {
            let view = ContextView::new(&mut world, &mut child);
            assert_eq!(view.visit_count(cellar_id), 0);
        }
    }

    /// F3.2 fork isolation (`Mode::Normal` child): forking a parent
    /// `FlowLocal` gives the child a frozen view of the parent's overrides
    /// at fork time. A write the child makes to a `Local`-scoped unit lands
    /// only in the child's own top layer — the parent's `FlowLocal` and
    /// `World` are both unaffected.
    #[test]
    fn fork_isolation_normal_child_write_does_not_leak_to_parent_or_world() {
        let program = sample_program();
        let policy = mixed_policy(); // mood: Local, gold: World (default)
        let mut world = World::new(&program, &policy).expect("world builds");
        let mood_slot = program.global_index("mood").expect("mood declared");

        let mut parent = FlowLocal::new();
        {
            let mut view = ContextView::new(&mut world, &mut parent);
            view.set_global(mood_slot, Value::Int(42));
        }

        // Fork a Normal child from the parent.
        let mut child = parent.fork(Mode::Normal);

        // The child reads the parent's frozen state via `base` — it never
        // wrote `mood` itself.
        {
            let view = ContextView::new(&mut world, &mut child);
            assert_eq!(view.global(mood_slot), &Value::Int(42));
        }

        // The child writes its own override for `mood`.
        {
            let mut view = ContextView::new(&mut world, &mut child);
            view.set_global(mood_slot, Value::Int(100));
            assert_eq!(view.global(mood_slot), &Value::Int(100));
        }

        // The parent's own `FlowLocal` still reads its original write — the
        // child's write never reached it.
        {
            let view = ContextView::new(&mut world, &mut parent);
            assert_eq!(view.global(mood_slot), &Value::Int(42));
        }

        // `World` was never touched — `mood` is Local-scoped, so it was
        // never written there in the first place.
        assert_eq!(world.global(mood_slot), &Value::Int(0));
    }

    /// F3.2 frozen snapshot: a fork's `base` is a point-in-time snapshot.
    /// Mutating the parent *after* the fork must not be visible through the
    /// child, which still reads the parent's state as of the fork.
    #[test]
    fn fork_base_is_a_frozen_snapshot_later_parent_writes_invisible_to_child() {
        let program = sample_program();
        let policy = mixed_policy(); // mood: Local
        let mut world = World::new(&program, &policy).expect("world builds");
        let mood_slot = program.global_index("mood").expect("mood declared");

        let mut parent = FlowLocal::new();
        {
            let mut view = ContextView::new(&mut world, &mut parent);
            view.set_global(mood_slot, Value::Int(1));
        }

        let mut child = parent.fork(Mode::Normal);

        // Mutate the parent *after* the fork.
        {
            let mut view = ContextView::new(&mut world, &mut parent);
            view.set_global(mood_slot, Value::Int(2));
        }

        // The child's frozen base still reflects the pre-fork value.
        let view = ContextView::new(&mut world, &mut child);
        assert_eq!(view.global(mood_slot), &Value::Int(1));
    }

    /// F3.2 sandbox side-effect-proof: in `Mode::Sandbox`, a `World`-scoped
    /// unit is still readable through the live `World` value, but any write
    /// — even to a unit the policy homes to `World` — lands only in the
    /// sandboxed flow's own overrides. `World` itself is never mutated, and
    /// dropping the sandboxed `FlowLocal` leaves no trace.
    #[test]
    fn sandbox_mode_writes_never_reach_world_reads_see_live_world() {
        let program = sample_program();
        let policy = mixed_policy(); // gold: World (default), mood: Local
        let mut world = World::new(&program, &policy).expect("world builds");
        let gold_slot = program.global_index("gold").expect("gold declared");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");

        // Simulate pre-existing shared state the sandboxed flow should see.
        world.set_global(gold_slot, Value::Int(7));
        world.increment_visit(shrine_id);
        world.increment_visit(shrine_id);
        world.increment_visit(shrine_id);
        assert_eq!(world.visit_count(shrine_id), 3);

        // Fork a sandboxed child from a "live" flow's (empty) FlowLocal.
        let live = FlowLocal::new();
        {
            let mut sandboxed = live.fork(Mode::Sandbox);

            // Reads see World's current, live value even though `gold` and
            // `shrine` are World-scoped by policy.
            {
                let view = ContextView::new(&mut world, &mut sandboxed);
                assert_eq!(view.global(gold_slot), &Value::Int(7));
                assert_eq!(view.visit_count(shrine_id), 3);
            }

            // Writing the World-scoped `gold` in the sandbox diverts to the
            // sandbox's own overrides — it does not touch `World`.
            {
                let mut view = ContextView::new(&mut world, &mut sandboxed);
                view.set_global(gold_slot, Value::Int(555));
                assert_eq!(view.global(gold_slot), &Value::Int(555)); // visible locally
            }
            assert_eq!(world.global(gold_slot), &Value::Int(7)); // World unchanged

            // Incrementing a World-scoped visit count in the sandbox is
            // copy-on-write from the live World count, but the increment
            // itself stays local — World's count is untouched.
            {
                let mut view = ContextView::new(&mut world, &mut sandboxed);
                view.increment_visit(shrine_id);
                assert_eq!(view.visit_count(shrine_id), 4); // sandbox sees 4
            }
            assert_eq!(world.visit_count(shrine_id), 3); // World still 3

            // Dropping `sandboxed` here (end of scope) is discard — nothing
            // escaped to World, so there is nothing to unwind.
        }

        // World is still clean after the sandboxed child is gone.
        assert_eq!(world.global(gold_slot), &Value::Int(7));
        assert_eq!(world.visit_count(shrine_id), 3);
    }
}

#[cfg(test)]
mod save_load_tests {
    use super::*;
    use crate::link;
    use crate::rng::FastRng;
    use crate::story::{FallbackHandler, FlowInstance};
    use crate::{load_state, save_state};

    /// Compile a small ink story with the brink compiler and link it,
    /// keeping the line tables `FlowInstance::drive_to_terminal` needs.
    fn compile_for_flow(src: &str) -> (Program, Vec<Vec<brink_format::LineEntry>>) {
        let out = brink_compiler::compile("t.ink", |p| {
            if p == "t.ink" {
                Ok(src.to_string())
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "no such include",
                ))
            }
        })
        .expect("compile");
        link(&out.data).expect("link")
    }

    /// A scoped save/load roundtrip (F6.1b): `gold` (global) and `shrine`
    /// (knot) are policy-scoped `Local`; `silver` (global) stays `World`
    /// (the default). Driving the flow populates both layers; saving
    /// through the routing view captures effective values regardless of
    /// scope. Loading into a **fresh** `(World, FlowLocal)` pair through a
    /// fresh view must land each unit back in the layer its policy
    /// names — `Local` units in the new `FlowLocal`'s override maps (the new
    /// `World`'s own copy stays untouched), `World` units directly in the
    /// new `World` (the new `FlowLocal` contributes nothing for them).
    #[test]
    fn scoped_save_load_lands_each_unit_in_its_policy_layer() {
        let (program, tables) = compile_for_flow(
            "VAR gold = 0\n\
             VAR silver = 0\n\
             ~ silver = 7\n\
             -> shrine\n\
             === shrine ===\n\
             ~ gold = 5\n\
             At the shrine.\n\
             -> DONE\n\
             === reader ===\n\
             {READ_COUNT(-> shrine)}\n\
             -> DONE\n",
            // `reader` is never entered — it exists only so the compiler's
            // counting-flags pass sees a visit-count read of `shrine` and
            // sets `CountingFlags::VISITS` on it (a knot whose visit count
            // is never read anywhere in the program has counting disabled
            // entirely — an existing compiler optimization).
        );

        let mut overrides = BTreeMap::new();
        overrides.insert("gold".to_owned(), Scope::Local);
        overrides.insert("shrine".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };

        let gold_slot = program.global_index("gold").expect("gold declared");
        let silver_slot = program.global_index("silver").expect("silver declared");
        let shrine_id = program.find_path_target("shrine").expect("shrine exists");

        // Drive the flow against a World built from our policy — the
        // `FlowInstance::new_at_root`-returned World is discarded; only the
        // callstack/thread state it seeds matters here.
        let mut world = World::new(&program, &policy).expect("world builds");
        let mut local = FlowLocal::new();
        let save = {
            let (mut flow, _unused_default_world) = FlowInstance::new_at_root(&program);
            let mut view = ContextView::new(&mut world, &mut local);
            flow.drive_to_terminal::<FastRng>(&program, &tables, &mut view, &FallbackHandler, None)
                .expect("drive succeeds");
            save_state(&program, &view)
        };

        assert_eq!(save.globals.get("gold"), Some(&Value::Int(5)));
        assert_eq!(save.globals.get("silver"), Some(&Value::Int(7)));
        assert_eq!(
            save.visits
                .iter()
                .find(|e| e.id == shrine_id)
                .map(|e| e.count),
            Some(1),
            "shrine should have a captured visit entry"
        );

        // Load into a fresh (World, FlowLocal) pair, built from the same
        // policy but with none of the driven state.
        let mut world2 = World::new(&program, &policy).expect("world builds");
        let mut local2 = FlowLocal::new();
        let report = {
            let mut view2 = ContextView::new(&mut world2, &mut local2);
            load_state(&program, &mut view2, &save)
        };
        assert!(report.unknown_globals.is_empty(), "clean load: {report:?}");

        // `gold` is Local-scoped: the load must land it in `local2`'s
        // override map, leaving `world2`'s own copy at its untouched
        // default. The routing view's effective read still sees 5.
        assert_eq!(
            world2.global(gold_slot),
            &Value::Int(0),
            "gold is Local-scoped; World's own copy must stay untouched"
        );
        {
            let view2 = ContextView::new(&mut world2, &mut local2);
            assert_eq!(view2.global(gold_slot), &Value::Int(5));
        }

        // `silver` is World-scoped: the load must land it directly in
        // `world2`, readable without any FlowLocal involvement.
        assert_eq!(
            world2.global(silver_slot),
            &Value::Int(7),
            "silver is World-scoped; must land directly in World"
        );

        // `shrine`'s visit count is Local-scoped: same split as `gold`.
        assert_eq!(
            world2.visit_count(shrine_id),
            0,
            "shrine is Local-scoped; World's own visit count must stay untouched"
        );
        {
            let view2 = ContextView::new(&mut world2, &mut local2);
            assert_eq!(view2.visit_count(shrine_id), 1);
        }
    }
}

#[cfg(test)]
mod subtree_scope_tests {
    use super::*;
    use crate::link;
    use crate::rng::FastRng;
    use crate::story::{FallbackHandler, FlowInstance, Line};

    /// Compile a small ink story with the brink compiler and link it,
    /// keeping the line tables `FlowInstance::drive_to_terminal` needs.
    fn compile_for_flow(src: &str) -> (Program, Vec<Vec<brink_format::LineEntry>>) {
        let out = brink_compiler::compile("t.ink", |p| {
            if p == "t.ink" {
                Ok(src.to_string())
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "no such include",
                ))
            }
        })
        .expect("compile");
        link(&out.data).expect("link")
    }

    /// A knot `guard_talk` with its own top-level stopping sequence
    /// (`{ Halt! | Back again? }`) plus a stitch `guard_talk.inner` with its
    /// own stopping sequence, and an unrelated `other_knot` — the minimal
    /// shape needed to exercise interior-container containment, the knot→
    /// stitch cascade, and most-specific-wins precedence.
    fn story_with_stitch_and_sequences() -> (Program, Vec<Vec<brink_format::LineEntry>>) {
        compile_for_flow(
            "VAR gold = 0\n\
             -> guard_talk\n\
             === guard_talk ===\n\
             { stopping: Halt! | Back again? }\n\
             -> inner\n\
             = inner\n\
             { stopping: A | B | C }\n\
             -> DONE\n\
             === other_knot ===\n\
             Other.\n\
             -> DONE\n",
        )
    }

    /// Find the `DefinitionId` of the (single) interior container directly
    /// owned by `scope_owner` that carries `CountingFlags::VISITS` — i.e.
    /// the anonymous sequence container `handle_sequence` (`vm.rs`) keys its
    /// counter off. Panics if there isn't exactly one, since every test
    /// story here is built with exactly one stopping sequence per scope.
    fn find_owned_sequence_id(program: &Program, scope_owner: DefinitionId) -> DefinitionId {
        let mut found = None;
        for (idx, container) in program.containers.iter().enumerate() {
            #[expect(clippy::cast_possible_truncation, reason = "test fixture")]
            let idx = idx as u32;
            let owner = program.scope_ids[program.scope_table_idx(idx) as usize];
            if owner == scope_owner
                && container
                    .counting_flags
                    .contains(brink_format::CountingFlags::VISITS)
            {
                assert!(
                    found.is_none(),
                    "expected exactly one VISITS-counted interior container owned by {scope_owner:?}"
                );
                found = Some(container.id);
            }
        }
        found.expect("expected a VISITS-counted interior container")
    }

    /// A knot marked `Local` must cover not just its own `DefinitionId` but
    /// the interior sequence container nested directly under it — this is
    /// the exact bug the F6 AMENDMENT (ruling 3) describes:
    /// `handle_sequence` keys a stopping/cycle counter off the sequence's
    /// *own* container id, not the enclosing knot's, so without subtree
    /// expansion a `Local`-marked knot would silently leave that counter
    /// `World`-scoped.
    #[test]
    fn marked_local_knot_covers_its_interior_sequence_container() {
        let (program, _tables) = story_with_stitch_and_sequences();
        let guard_talk_id = program
            .find_path_target("guard_talk")
            .expect("guard_talk exists");
        let other_knot_id = program
            .find_path_target("other_knot")
            .expect("other_knot exists");
        let sequence_id = find_owned_sequence_id(&program, guard_talk_id);

        let mut overrides = BTreeMap::new();
        overrides.insert("guard_talk".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let resolved = ResolvedPolicy::resolve(&program, &policy).expect("resolves");

        assert_eq!(resolved.scope_of_knot(guard_talk_id), Scope::Local);
        assert_eq!(
            resolved.scope_of_knot(sequence_id),
            Scope::Local,
            "the interior sequence container must inherit guard_talk's Local scope"
        );
        // An unrelated knot must stay at the World default — the expansion
        // must not leak scope onto unrelated containers.
        assert_eq!(resolved.scope_of_knot(other_knot_id), Scope::World);
    }

    /// Stitch-level override + most-specific-wins precedence: knot
    /// `guard_talk` is `Local`, but its stitch `guard_talk.inner` is
    /// explicitly `World`. Every container under `inner` (the stitch
    /// itself, and its own interior sequence) must resolve `World`; the
    /// rest of `guard_talk`'s subtree (the knot's own id and its own
    /// interior sequence) must resolve `Local`.
    #[test]
    fn stitch_override_wins_over_enclosing_knot_for_its_own_subtree() {
        let (program, _tables) = story_with_stitch_and_sequences();
        let guard_talk_id = program
            .find_path_target("guard_talk")
            .expect("guard_talk exists");
        let inner_id = program
            .find_path_target("guard_talk.inner")
            .expect("guard_talk.inner exists");
        let guard_talk_sequence_id = find_owned_sequence_id(&program, guard_talk_id);
        let inner_sequence_id = find_owned_sequence_id(&program, inner_id);

        let mut overrides = BTreeMap::new();
        overrides.insert("guard_talk".to_owned(), Scope::Local);
        overrides.insert("guard_talk.inner".to_owned(), Scope::World);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let resolved = ResolvedPolicy::resolve(&program, &policy).expect("resolves");

        assert_eq!(resolved.scope_of_knot(guard_talk_id), Scope::Local);
        assert_eq!(resolved.scope_of_knot(guard_talk_sequence_id), Scope::Local);
        assert_eq!(
            resolved.scope_of_knot(inner_id),
            Scope::World,
            "the stitch's own explicit override must win over its enclosing knot's"
        );
        assert_eq!(
            resolved.scope_of_knot(inner_sequence_id),
            Scope::World,
            "the stitch's interior sequence must follow the stitch's own override, \
             not the enclosing knot's"
        );

        // And the reverse precedence: knot World (default), stitch Local —
        // confirms precedence isn't just "whichever happens to be Local".
        let mut overrides2 = BTreeMap::new();
        overrides2.insert("guard_talk".to_owned(), Scope::World);
        overrides2.insert("guard_talk.inner".to_owned(), Scope::Local);
        let policy2 = WorldPolicy {
            default: Scope::World,
            overrides: overrides2,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let resolved2 = ResolvedPolicy::resolve(&program, &policy2).expect("resolves");
        assert_eq!(resolved2.scope_of_knot(guard_talk_id), Scope::World);
        assert_eq!(
            resolved2.scope_of_knot(guard_talk_sequence_id),
            Scope::World
        );
        assert_eq!(resolved2.scope_of_knot(inner_id), Scope::Local);
        assert_eq!(resolved2.scope_of_knot(inner_sequence_id), Scope::Local);
    }

    /// The all-`World` default policy must still resolve via
    /// `ResolvedPolicy::all_world`'s fast path — no per-slot/per-knot tables
    /// populated — even against a program with stitches and sequences that
    /// would otherwise drive subtree expansion. This is the oracle-anchored
    /// path every existing single-flow construction path takes; it must
    /// stay byte-identical.
    #[test]
    fn all_world_default_still_takes_fast_path() {
        let (program, _tables) = story_with_stitch_and_sequences();
        let resolved =
            ResolvedPolicy::resolve(&program, &WorldPolicy::default()).expect("resolves");

        // Fast path: no per-slot/per-knot table populated, matching
        // `all_world()` exactly.
        assert!(resolved.global_scopes.is_empty());
        assert!(resolved.knot_scopes.is_empty());

        let guard_talk_id = program
            .find_path_target("guard_talk")
            .expect("guard_talk exists");
        assert_eq!(resolved.scope_of_knot(guard_talk_id), Scope::World);
    }

    /// An override name that resolves to neither a global nor a knot/
    /// stitch path is still a `PolicyError::UnknownName` — subtree
    /// expansion must not swallow or change this error path.
    #[test]
    fn unknown_override_name_still_errors() {
        let (program, _tables) = story_with_stitch_and_sequences();
        let mut overrides = BTreeMap::new();
        overrides.insert("guard_talk.nonexistent_stitch".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let err = ResolvedPolicy::resolve(&program, &policy).expect_err("must fail");
        assert_eq!(
            err,
            PolicyError::UnknownName("guard_talk.nonexistent_stitch".to_owned())
        );
    }

    /// End-to-end (F6.1c's motivating "per-entity memory" case): two
    /// `FlowInstance`s, each with its own `FlowLocal`, drive the *same*
    /// `guard_talk` knot (a stopping sequence, `{ Halt! | Back again? }`)
    /// over one shared `World` whose policy marks `guard_talk` `Local`.
    /// Without subtree expansion, the sequence's own interior container id
    /// isn't in `knot_scopes`, falls through to the `World` default, and
    /// the two flows' visits collide on one shared counter — the second
    /// flow would see "Back again?" on its very first encounter. With the
    /// fix, each flow's first encounter is independently the first-visit
    /// text.
    #[test]
    fn two_flows_over_shared_world_each_see_first_visit_text() {
        let (program, tables) = compile_for_flow(
            "VAR gold = 0\n\
             -> guard_talk\n\
             === guard_talk ===\n\
             { stopping: Halt! | Back again? }\n\
             -> DONE\n",
        );

        let mut overrides = BTreeMap::new();
        overrides.insert("guard_talk".to_owned(), Scope::Local);
        let policy = WorldPolicy {
            default: Scope::World,
            overrides,
            turn_index: Scope::World,
            rng: Scope::World,
        };
        let mut world = World::new(&program, &policy).expect("world builds");

        let drive = |flow: &mut FlowInstance, view: &mut ContextView<'_>| -> String {
            let lines = flow
                .drive_to_terminal::<FastRng>(&program, &tables, view, &FallbackHandler, None)
                .expect("drive succeeds");
            assert!(
                matches!(lines.last(), Some(Line::Done { .. })),
                "expected Done, got {lines:?}"
            );
            lines.iter().map(Line::text).collect::<String>()
        };

        // Flow A: first (and only, for this assertion) encounter.
        let (mut flow_a, _discarded_world_a) = FlowInstance::new_at_root(&program);
        let mut local_a = FlowLocal::new();
        let first_visit_a = {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            drive(&mut flow_a, &mut view_a)
        };

        // Flow B: independent FlowLocal, same shared World. Its first
        // encounter must read exactly like Flow A's — not "already
        // visited" — proving the interior sequence container's visit count
        // is Local per-flow, not accidentally shared through World.
        let (mut flow_b, _discarded_world_b) = FlowInstance::new_at_root(&program);
        let mut local_b = FlowLocal::new();
        let first_visit_b = {
            let mut view_b = ContextView::new(&mut world, &mut local_b);
            drive(&mut flow_b, &mut view_b)
        };

        assert_eq!(
            first_visit_a, first_visit_b,
            "both flows' first encounter with guard_talk must produce identical \
             (first-visit) text — each flow's visit count is independently local"
        );

        // Flow A, re-entered a second time (still its own FlowLocal): now
        // it must progress to the *next* branch of the stopping sequence,
        // proving Local scoping still lets a single flow's own state
        // advance normally.
        let second_visit_a = {
            let mut view_a = ContextView::new(&mut world, &mut local_a);
            flow_a
                .choose_path_string(&program, &mut view_a, "guard_talk")
                .expect("re-enter guard_talk");
            drive(&mut flow_a, &mut view_a)
        };
        assert_ne!(
            first_visit_a, second_visit_a,
            "flow A's second encounter must progress past the first-visit branch"
        );

        // Flow B's own local state must still be untouched by flow A's
        // second visit — driving B a second time reproduces A's *first*
        // progression, not A's second.
        let second_visit_b = {
            let mut view_b = ContextView::new(&mut world, &mut local_b);
            flow_b
                .choose_path_string(&program, &mut view_b, "guard_talk")
                .expect("re-enter guard_talk");
            drive(&mut flow_b, &mut view_b)
        };
        assert_eq!(
            second_visit_a, second_visit_b,
            "flow B's second encounter must match flow A's second encounter — \
             both progressed independently from the same (shared, untouched) \
             World default"
        );

        // World's own bookkeeping for the Local-scoped knot must never have
        // been touched by either flow.
        let sequence_id = find_owned_sequence_id(&program, {
            program
                .find_path_target("guard_talk")
                .expect("guard_talk exists")
        });
        assert_eq!(
            world.visit_count(sequence_id),
            0,
            "World's own copy of the Local-scoped sequence's visit count must stay untouched"
        );
    }
}