tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
//! `simulateMarketTick`'s live path, ported from the reference
//! implementation.
//!
//! # The order of operations IS the model
//!
//! Four phases, and the boundaries between them matter:
//!
//! 1. **Factors** — per company, compute the four live shock factors. Takes
//!    one normal and one uniform per company. The uniform is *stashed*, not
//!    used: it is consumed in phase 3.
//! 2. **Price** — the `s`-process, then `price = fairValue × exp(s)`, then the
//!    circuit breaker on the MODEL price.
//! 3. **Volume** — consumes the uniforms stashed in phase 1.
//! 4. **Settlement** — the book decides what actually printed, then the
//!    breaker is applied again to the PRINT.
//!
//! The phase-1 uniform being consumed two phases later is the trap here. A
//! port that drew it in phase 3, where it is used, would produce identical
//! counts and a completely different stream — the same class of mistake as
//! WP3's object-literal draw.
//!
//! # The factor model moves fair value OR price, never both
//!
//! `new_prices[i]` after phase 2 is **fair value**, not a price. Phase 4 reads
//! it only as the book's anchor. Treating it as the printed price would
//! double-count every driver, which is why the variable is never assigned to
//! `stock.price` directly.
//!
//! # The breaker is applied twice, deliberately
//!
//! Once to the model price in phase 2, once to the settled print in phase 4.
//! The second is the one that matters: spread widening and multi-level
//! book-walking can settle a print beyond an already-clamped fair value, and
//! because that print becomes the next tick's reference the overshoot
//! compounded within a day. A breaker that bounds an unobservable reference
//! and not the tape is not a breaker. See D6 in the port notes.

use crate::economy::EconomyState;
use crate::fair_value::{CompanyValuationInputs, EconomyValuationInputs};
use crate::mathx;
use crate::microstructure::{
    decompose, settle_price_through_book, settle_price_through_book_with_orders,
    CompanyMicrostructure, SettleOptions,
};
use crate::mispricing::crowd_lean_with;
use crate::params::ModelParams;
use crate::rng::Rng;

use super::factors::{
    calculate_live_factors, order_imbalance_with, FactorCompany, LiveFactors, NewsEvent,
    SharedFactors,
};
use super::hours::{intraday_vol, intraday_volume, MarketStatus};

/// Per-tick decay of the mispricing process: `MISPRICING_PHI ^ (1/390)`.
///
/// **Hardcoded from V8's recorded bits, deliberately not computed** — the same
/// treatment as `MISPRICING_PHI` and for a sharper reason: this one is applied
/// 390 times per simulated day, so a last-bit difference is not a rounding
/// curiosity but a different half-life compounding all session.
///
/// Measured: `libm::pow`, `f64::powf` and V8 all produce `3FEFFFC1E1385E9E`
/// for this input, so the hardcode is belt-and-braces rather than a
/// workaround. It stays hardcoded because agreeing today on one platform is
/// not a guarantee, and the bits are the contract.
pub const S_PHI_TICK: f64 = f64::from_bits(0x3FEF_FFC1_E138_5E9E);

/// BASELINE standard deviation of the shared market factor, at DAILY
/// scale — since the factor-variance change of the 2026-08 era, the
/// unconditional anchor of the factor's variance process
/// ([`super::factor_vol`]), not the sigma of any given day. The tick
/// draws at the CONDITIONAL sigma the engine passes in
/// ([`TickInputs::market_sigma_daily`]); this constant is the anchor the
/// process reverts to — scaled by (VIX/15)² since the coupling decision,
/// so it is the exact reversion level when VIX sits at its endogenous
/// mean — the unit its floor and ceiling are multiples of, and the
/// absolute denomination of the crash amplifier's threshold
/// (`factors.rs`).
///
/// **History, in three measured acts.** The reference implementation says
/// 0.003, which put a few percent of a typical name's variance in the
/// shared factor and produced cross-sectional correlation of 0.026
/// against a real 0.25-0.35 (findings 7-9). The first recalibration swept
/// the constant (`tools/calibration/sweep_market_factor_sigma.py`) and
/// proved the band UNREACHABLE by it: the factor was Gaussian at constant
/// sigma, so its correlation contribution was its variance share, and
/// every point of share Gaussian-diluted the GARCH tails — the band
/// arrived only at sigma 0.021, where excess kurtosis had collapsed to
/// 1.26 against a floor of 3 (finding 14). 0.0075 shipped as the largest
/// value whose median kurtosis stayed in band, and finding 14 named the
/// escape: give the factor its own fat-tailed conditional volatility,
/// funded from the idiosyncratic side. `factor_vol.rs` is that change,
/// and it alters what this constant buys — a conditional factor
/// CONTRIBUTES kurtosis and market-wide clustering instead of spending
/// them, so the baseline can sit where correlation needs it.
///
/// **0.016 comes from the factor-vol sweep**
/// (`tools/calibration/sweep_market_factor_vol.py`, committed results
/// `results/market-factor-vol-2026-08-2*.json`), chosen JOINTLY with
/// `IDIO_SIGMA_SCALE` = 0.84 — the funding side, which is why total
/// volatility FELL (48.3% -> 41.8% pooled) while the factor's share of it
/// roughly tripled. At the shipped vector, six-seed medians on the
/// published method: correlation 0.260 and excess kurtosis 3.14, both
/// inside their real bands for the first time in this model's history,
/// with volatility clustering 0.245 (in band) and the leverage effect
/// intact at -0.094. The finding-14 trade was dissolved by the process,
/// not re-positioned along the same curve.
///
/// Change this only by re-running the factor-vol sweep, and only TOGETHER
/// with `IDIO_SIGMA_SCALE` and the `factor_vol.rs` shape; a test pins the
/// value to make that deliberate.
pub const MARKET_FACTOR_SIGMA: f64 = 0.016;
/// Standard deviation of a shared sector factor, at DAILY scale.
pub const SECTOR_FACTOR_SIGMA: f64 = 0.002;

/// VIX points past `CRISIS_VIX_THRESHOLD` over which the sector→market
/// blend ramps to 1.0 (before [`CRISIS_BLEND_CAP`] truncates it).
///
/// A §5.4 promotion of the inline `/1.4`: the ramp is half of what makes
/// the re-sited crisis trigger MEAN something — the blend saturates by
/// VIX ≈ 26.6, the ceiling of what the macro chain can produce.
pub const CRISIS_BLEND_RAMP: f64 = 1.4;

/// Ceiling of the crisis correlation blend. A §5.4 promotion of the
/// inline `0.8`: even in a full crisis, sector factors keep 20% of their
/// own identity.
pub const CRISIS_BLEND_CAP: f64 = 0.8;

/// The session circuit breaker, as a fraction of the day's open (±25%).
///
/// A §5.4 promotion of the inline `1.25`/`0.75` pair. A GUARD, not a
/// knob: it is a worst-case guarantee backed by invariant tests, and it
/// is applied twice per tick — to the model price and to the settled
/// print — which is why the params carry it as the derived band
/// multipliers, computed once (§5.3).
pub const PRICE_BREAKER_FRACTION: f64 = 0.25;

/// Absolute cap on any model price. A guard (the reference's `50000`).
pub const PRICE_HARD_CAP: f64 = 50_000.0;

/// The mutable stock state a tick reads and writes.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TickStock {
    pub price: f64,
    pub previous_close: f64,
    /// `undefined` until the first tick prints — the reference implementation's field is
    /// optional, and a fabricated default here would diverge on tick zero of
    /// any freshly generated company.
    pub previous_tick_price: Option<f64>,
    pub open: f64,
    pub high: f64,
    pub low: f64,
    pub volume: f64,
    pub avg_volume: f64,
    pub shares_outstanding: f64,
    pub market_cap: f64,
    /// `None` until the first tick adopts the current premium/discount.
    pub mispricing_s: Option<f64>,
    pub mispricing_s_prev_close: Option<f64>,
    pub mispricing_momentum: Option<f64>,
    /// The name's log fair-value level `v`: what its own permanent news has
    /// moved its fair value away from the published fundamentals. `None`
    /// (and 0.0) under every preset through pt-v19, where no shock reaches
    /// fair value and the valuation reads the published figures as they
    /// stand. See `ModelParams::fair_value_news_share` and
    /// `ModelParams::opening_mispricing_sigma`.
    pub fair_value_offset: Option<f64>,
    /// The running log share-count reduction `L` under `buyback_accrual`:
    /// the close adds one session's buyback yield, and fair value reads
    /// `exp(L)`. None is 0.0, which every name holds while the switch or
    /// `buyback_payout_share` is off, and which a new listing starts at.
    pub buyback_log_shares: Option<f64>,
    /// The name's dividend state (`ModelParams::dividend_payout_share`).
    /// `None` on every preset, which pays no dividend; see
    /// [`crate::market::dividends`].
    pub dividend: Option<crate::market::dividends::DividendState>,
    pub maker_inventory: Option<f64>,
    pub garch_variance: f64,
    /// The variance cascade's components, when one is running.
    ///
    /// A fixed array rather than a `Vec`: this is per-name state touched at
    /// every close, and a heap allocation per company per day would be a real
    /// cost for a mechanism that ships switched off. All zeros means the
    /// cascade has never run, and `update_garch_cascade` seeds from the
    /// sector base on its first call. See
    /// [`crate::market::garch::update_garch_cascade`].
    pub garch_cascade: [f64; crate::market::garch::CASCADE_MAX],
    pub last_daily_return: Option<f64>,
    pub beta: Option<f64>,
    pub short_interest: f64,
    pub float: f64,
}

impl TickStock {
    /// A stock at `price` before its first tick: the open, high, low and
    /// previous close all at `price`, no volume yet, market cap
    /// `price * shares_outstanding`, the float equal to the shares
    /// outstanding, and every carried state absent or zero.
    ///
    /// `garch_variance` and `avg_volume` start at zero and a host sets them:
    /// [`crate::universe::InstrumentInit::to_tick_company`] seeds the
    /// variance at the sector's base, `sectors::by_key(key)` then
    /// `base_daily_variance()`. `garch_cascade` is all zeros, the "cascade
    /// has never run" state, which seeds from the sector base on first use.
    pub fn new(price: f64, shares_outstanding: f64) -> Self {
        TickStock {
            price,
            previous_close: price,
            previous_tick_price: None,
            open: price,
            high: price,
            low: price,
            volume: 0.0,
            avg_volume: 0.0,
            shares_outstanding,
            market_cap: price * shares_outstanding,
            mispricing_s: None,
            mispricing_s_prev_close: None,
            mispricing_momentum: None,
            fair_value_offset: None,
            buyback_log_shares: None,
            dividend: None,
            maker_inventory: None,
            garch_variance: 0.0,
            garch_cascade: [0.0; crate::market::garch::CASCADE_MAX],
            last_daily_return: None,
            beta: None,
            short_interest: 0.0,
            float: shares_outstanding,
        }
    }
}

/// One company, as the tick sees it.
///
/// A single struct rather than three composed ones. `fair_value`,
/// `factors` and `microstructure` each declare their own narrow input type by
/// convention, and duplicating `id`/`sector`/`beta` across three copies would
/// invite them to disagree. The narrow views are BUILT from this on demand,
/// so there is one source of truth per field.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TickCompany {
    pub id: String,
    pub ticker: String,
    pub sector: String,
    pub is_bankrupt: bool,
    pub is_public: bool,
    pub stock: TickStock,
    /// `SECTOR_CONFIGS[sector].volatility`, passed in rather than duplicated.
    pub sector_volatility: Option<f64>,
    /// `SECTOR_CONFIGS[sector].avgPe`, for the valuation. Note the casing —
    /// reading `avgPE` yields `undefined` and silently falls back to the
    /// default PE of 18, which is a real bug this port already shipped once.
    pub sector_avg_pe: Option<f64>,
    pub eps: Option<f64>,
    pub book_value_per_share: Option<f64>,
    pub revenue_growth: Option<f64>,
}

impl TickCompany {
    /// A listed, solvent company with no sector figures or fundamentals.
    /// Set `sector_volatility`, `sector_avg_pe`, `eps`,
    /// `book_value_per_share` and `revenue_growth` on the value.
    pub fn new(
        id: impl Into<String>,
        ticker: impl Into<String>,
        sector: impl Into<String>,
        stock: TickStock,
    ) -> Self {
        TickCompany {
            id: id.into(),
            ticker: ticker.into(),
            sector: sector.into(),
            is_bankrupt: false,
            is_public: true,
            stock,
            sector_volatility: None,
            sector_avg_pe: None,
            eps: None,
            book_value_per_share: None,
            revenue_growth: None,
        }
    }
}

/// Trading days in a year, the clock a market rate is quoted on.
///
/// Separate from the economy's 365 by intent. A buyback yield is earnings
/// over a TRADED price, so it is an annual rate on the market's own
/// calendar, and an `economy_days_per_year` that unified the macro clocks
/// would leave this alone.
pub const MARKET_DAYS_PER_YEAR: f64 = 252.0;

/// The per-share factor a buyback yield has produced by `elapsed_days`.
///
/// A company returning a share of its earnings as net buybacks retires
/// stock, so earnings and book per share grow faster than the company does,
/// by the buyback yield `b = payout_share * eps / price`. That yield is
/// earnings over price, so the mechanism pays more when the multiple is low
/// and less when it is high, which is the behaviour a real buyback
/// programme has and a flat premium does not.
///
/// # What is exact and what is not
///
/// The share count obeys `dS/S = -payout * eps(u)/P(u) du`, so the exact
/// factor is the exponential of the payout share times the INTEGRAL of the
/// earnings yield. This evaluates the yield at today's price and holds it
/// over the elapsed time, which is the form the design states and needs no
/// per-name accumulator. Measured against the integral on real price paths
/// at pt-v18: over 252 days on 200 name-seeds the difference is +0.026
/// points of annual index return at the median and +0.009 at the mean, and
/// over 1008 days on 120 name-seeds it is -0.015 and -0.068. The multiple
/// mean-reverts, so today's yield estimates the period's average yield at
/// both horizons. The worst single name is 1.39 points over four years and
/// the index averages forty of them with errors on both sides.
///
/// The yield reads the earnings the growth term has already restated, and
/// not the earnings this factor itself restates. Solving for the
/// self-consistent yield is a Lambert W with no bit-pinned implementation
/// here, and the term it omits is second order: at 1.85 per cent over a
/// year it understates the yield by 0.03 of a point, against a market
/// price in the denominator that rises with the same buybacks and pushes
/// the other way.
///
/// # The clamp on a loss-maker
///
/// A negative earnings yield would grow the share count, which is dilution
/// rather than buyback, and a company cannot return earnings it does not
/// have. So a loss-maker neither retires nor issues. That clamp does not
/// carry the hazard this era keeps finding in one-sided terms: `eps` is
/// fixed for a name at construction, so it selects a fixed share of the
/// roster once rather than branching on a zero-mean quantity every day. On
/// `Universe.random(40, seed=111)` it is 3 names of 40.
pub fn buyback_scale(p: &ModelParams, eps: Option<f64>, price: f64, elapsed_days: i64) -> f64 {
    buyback_scale_at(p, p.buyback_payout_share, eps, price, elapsed_days)
}

/// [`buyback_scale`] at an explicit share of earnings: the name's own under
/// `dividend_buyback_substitution` (`market::dividends::buyback_share`),
/// `buyback_payout_share` otherwise, where the two are the same arithmetic.
pub fn buyback_scale_at(
    p: &ModelParams,
    share: f64,
    eps: Option<f64>,
    price: f64,
    elapsed_days: i64,
) -> f64 {
    if p.buyback_payout_share == 0.0 || share == 0.0 {
        return 1.0;
    }
    let eps = match eps {
        Some(e) if e > 0.0 && e.is_finite() => e,
        _ => return 1.0,
    };
    if !(price > 0.0) || !price.is_finite() || elapsed_days <= 0 {
        return 1.0;
    }
    let b = share * eps / price;
    // The yield is read at TODAY's price and applied over every elapsed
    // year, so a name whose price collapses toward the 0.01 floor reads a
    // yield of hundreds and a fair value of exp(hundreds): the re-mark's
    // fixed point then diverges and the price jumps by orders of magnitude
    // (`buyback_yield_cap`). A branch at 0.0, the arithmetic that stood.
    let b = if p.buyback_yield_cap == 0.0 { b } else { mathx::min(b, p.buyback_yield_cap) };
    mathx::exp(b * elapsed_days as f64 / MARKET_DAYS_PER_YEAR)
}

/// The buyback factor the valuation applies. Under `buyback_accrual` it is
/// the accrued `exp(L)`, where `L` is the name's running log share-count
/// reduction (`TickStock::buyback_log_shares`), which does not read today's
/// price or the elapsed time; otherwise it is [`buyback_scale`], the term
/// that stood. A branch at 0.0, so every preset's arithmetic is the one it
/// was. `share` is the name's share of earnings spent on buybacks
/// (`market::dividends::buyback_share`): `buyback_payout_share` itself, or
/// under `dividend_buyback_substitution` that less the name's dividend
/// payout, in both the term that stood and the accrual.
///
/// [`buyback_scale`] reads the yield at today's price and applies it to
/// every elapsed year, so `d ln FV / d ln P_today = -b t`: fair value is
/// anti-elastic in the price it anchors, with a gain that grows with the
/// elapsed years. Past `b t = 1` the close's re-mark stops contracting and
/// the price flips each session (tick lag-1 autocorrelation toward -1 from
/// about year 30 on pt-v20), and relabelling the calendar origin moves
/// prices. The accrued factor is fixed within a session, so the elasticity
/// is zero at every horizon and the origin does not matter.
pub fn buyback_factor(p: &ModelParams, share: f64, eps: Option<f64>, price: f64,
                      elapsed_days: i64, log_shares: Option<f64>) -> f64 {
    if p.buyback_accrual != 0.0 {
        return match log_shares {
            Some(l) if l != 0.0 => mathx::exp(l),
            _ => 1.0,
        };
    }
    buyback_scale_at(p, share, eps, price, elapsed_days)
}

/// One session's increment to the log share-count reduction `L` under
/// `buyback_accrual`: `min(share * eps * exp(L) / price,
/// buyback_yield_cap) / 252`, where `share` is the name's buyback share of
/// earnings (`market::dividends::buyback_share`: `buyback_payout_share`, less
/// the name's dividend payout under `dividend_buyback_substitution`), `eps`
/// is the earnings the valuation holds before the buyback factor and `price`
/// is the close.
///
/// This is the exact form [`buyback_scale`]'s own docstring names: a buyback
/// retires shares at the price paid, so `dN/N = -payout * EPS_now / P dt`,
/// and EPS_now is `eps * exp(L)` because per-share earnings rise as the
/// share count falls. The cap, when set, bounds one session's increment. A
/// loss-maker (`eps <= 0`) neither retires nor issues, as in
/// [`buyback_scale`]. Zero when the switch or the payout share is off.
pub fn buyback_accrual_step(p: &ModelParams, share: f64, eps: Option<f64>, price: f64,
                            log_shares: f64) -> f64 {
    if p.buyback_accrual == 0.0 || p.buyback_payout_share == 0.0 || share == 0.0 {
        return 0.0;
    }
    let eps = match eps {
        Some(e) if e > 0.0 && e.is_finite() => e,
        _ => return 0.0,
    };
    if !(price > 0.0) || !price.is_finite() {
        return 0.0;
    }
    let per_share = if log_shares == 0.0 { eps } else { eps * mathx::exp(log_shares) };
    let b = share * per_share / price;
    let b = if p.buyback_yield_cap == 0.0 { b } else { mathx::min(b, p.buyback_yield_cap) };
    b / MARKET_DAYS_PER_YEAR
}

/// The sector draw's DAILY sigma, which follows VIX when coupled, on the
/// market factor's own target shape: variance scales with (VIX / anchor)^2,
/// so sigma scales with its square root. A branch at zero keeps every
/// preset before the coupling bit-identical; at the anchor the ratio is
/// exactly 1.0 at any coupling. The draw count is unchanged, so the tape
/// is too. Shared by the tick and the overnight move.
pub fn sector_sigma_for(p: &ModelParams, economy: &EconomyState) -> f64 {
    sector_sigma_at(p, economy, p.market_vol_vix_anchor)
}

/// [`sector_sigma_for`] against an EXPLICIT anchor, for the same reason
/// `factor_vol::update_market_variance_at` takes one: under
/// `vix_level_identity` the anchor is derived from the index's own
/// unconditional variance rather than read from the dial. At
/// `p.market_vol_vix_anchor` this is the arithmetic that stood here, to the
/// bit.
pub fn sector_sigma_at(p: &ModelParams, economy: &EconomyState, vix_anchor: f64) -> f64 {
    if p.sector_vix_coupling == 0.0 {
        p.sector_factor_sigma
    } else {
        let ratio = economy.vix / vix_anchor;
        p.sector_factor_sigma
            * mathx::sqrt(1.0 - p.sector_vix_coupling + p.sector_vix_coupling * (ratio * ratio))
    }
}

/// The crisis blend's spike, `0.0` below [`ModelParams::crisis_vix_threshold`]
/// and rising to [`ModelParams::crisis_blend_cap`] on the ramp above it.
///
/// A DETERMINISTIC FUNCTION OF THE STATE the close already holds — today's
/// VIX and the remembered universe stress — and no draw. That is what lets
/// [`crate::market::index_var`] price the blend's contribution to the index's
/// conditional variance rather than leave it as an unmodelled tail: the spike
/// is not a random variable, so the blend's injection is a known multiple of
/// the market factor and its second moment is the factor's own.
///
/// Lifted out of [`simulate_market_tick`], where it stood inline, for the reason
/// `sector_sigma_at` was: the read-back and the tick must not be able to
/// disagree about when a crisis is on. The arithmetic is the arithmetic that
/// stood there, branch for branch, so every preset is bit-identical.
///
/// # Universe memory
///
/// Without it this blend is a lookup on today's VIX and nothing else: the
/// tick VIX drops back under the threshold and the whole cross-section
/// decouples in the same tick, so a crisis leaves no trace. With it,
/// remembered stress from earlier days holds the blend up while it decays,
/// which is what real correlation does after a panic. The branch keeps every
/// earlier preset bit-identical — at weight zero this is the instant stress
/// and no arithmetic has touched it.
pub fn crisis_spike_for(p: &ModelParams, vix: f64, universe_stress: f64) -> f64 {
    // Today's stress, in VIX points above the crisis threshold.
    let instant_stress = if vix > p.crisis_vix_threshold {
        vix - p.crisis_vix_threshold
    } else {
        0.0
    };
    let effective_stress = if p.universe_stress_weight == 0.0 {
        instant_stress
    } else {
        instant_stress
            + p.universe_stress_weight * mathx::max(universe_stress - instant_stress, 0.0)
    };
    if effective_stress > 0.0 {
        mathx::min(p.crisis_blend_cap, effective_stress / p.crisis_blend_ramp)
    } else {
        0.0
    }
}

/// The factor the valuation's fundamentals are restated by, from the
/// economy's own integrated nominal output.
///
/// `1.0` whenever `earnings_nominal_growth` is 0.0, through a BRANCH rather
/// than through arithmetic that happens to be neutral, so every preset
/// before pt-v18 reaches `compute_fair_value` with the fundamentals it was
/// built with and reproduces bit for bit.
///
/// # The quantity
///
/// `N = gdp * cpi`, nominal output, which the economy compounds daily at
/// `gdp_growth / 100 / 365` and `inflation_rate / 100 / 365` in
/// [`crate::economy::daily`]. `base` is `N` when the engine was built, so
/// the ratio is exactly 1.0 on day 0 and the opening valuation is
/// unchanged. The economy advances once per market day and the market
/// annualises by 252, so a certified year carries `252 / 365` of both
/// annual rates.
///
/// # The guard
///
/// A base that is not finite and positive gives 1.0. `gdp` and `cpi` are
/// levels the economy never takes to zero, so this reaches nothing the
/// engine builds; it is here because a caller may construct
/// [`TickInputs`] directly, and a NaN entering the valuation would freeze
/// every book downstream with no indication of where it came from.
pub fn nominal_scale(p: &ModelParams, economy: &EconomyState, base: f64) -> f64 {
    let scale = nominal_scale_output(p, economy, base);
    // The aggregate earnings cycle rides on the same common multiplier, so
    // every reader of the restated earnings -- the valuation, the market
    // P/E, the overnight open, the opening -- reads it with no second path.
    // A branch at zero depth: every preset through pt-v19 never sees it.
    // Under `earnings_anticipation_half_life` the valuation prices the
    // earnings path it expects, not only today's point on it.
    let level = economy.earnings_cycle + economy.earnings_anticipation;
    let scale = if p.earnings_cycle_depth == 0.0 || level == 0.0 {
        scale
    } else {
        scale * mathx::exp(level)
    };
    // The look-through of the written earnings
    // (`earnings_lookthrough_half_life`): a branch at exactly zero, which it
    // is with the dial off and in any run that never wrote `market.earnings`.
    let look = economy.earnings_lookthrough;
    if look == 0.0 {
        scale
    } else {
        scale * mathx::exp(look)
    }
}

/// The nominal-output part of [`nominal_scale`], the arithmetic that stood.
fn nominal_scale_output(p: &ModelParams, economy: &EconomyState, base: f64) -> f64 {
    if p.earnings_nominal_growth == 0.0 {
        return 1.0;
    }
    if !(base > 0.0) || !base.is_finite() {
        return 1.0;
    }
    let ratio = economy.gdp * economy.cpi / base;
    // Linear in the dial, so a share of the term is a share of the level
    // the term adds, which is the shape every other dial in this era has.
    1.0 + p.earnings_nominal_growth * (ratio - 1.0)
}

/// Valuation inputs with the fundamentals restated in the price level and
/// output the economy has reached.
///
/// `scale` is `1 + earnings_nominal_growth * (N_t / N_0 - 1)`, from
/// [`nominal_scale`]. Both fundamentals move together, so the valuation
/// stays homogeneous of degree one in nominal terms on the earnings path
/// and on the book path alike, and a loss-maker valued at
/// `book * LOSS_MAKING_PRICE_TO_BOOK` grows with the same output a
/// profitable company does. The sector anchor is a multiple and the
/// revenue growth is a rate, so both are already nominal-neutral and
/// neither moves.
pub fn scale_valuation(
    company: CompanyValuationInputs,
    scale: f64,
) -> CompanyValuationInputs {
    CompanyValuationInputs {
        sector_avg_pe: company.sector_avg_pe,
        eps: company.eps.map(|v| v * scale),
        book_value_per_share: company.book_value_per_share.map(|v| v * scale),
        revenue_growth: company.revenue_growth,
    }
}

impl TickCompany {
    /// The valuation inputs as the tick reads them; `pub(crate)` so the
    /// overnight move prices the open from the same figures.
    pub(crate) fn valuation(&self) -> CompanyValuationInputs {
        CompanyValuationInputs {
            sector_avg_pe: self.sector_avg_pe,
            eps: self.eps,
            book_value_per_share: self.book_value_per_share,
            revenue_growth: self.revenue_growth,
        }
    }

    /// Write the factor model's view of this company into `view`, every
    /// field of it, so a field added to the view fails to compile here
    /// until it is written. The tick reuses one view from name to name:
    /// building one per name per tick cloned two strings each time, 33 per
    /// cent of a pt-v21 session's allocations over 20 names, and
    /// `clone_from` keeps the strings' buffers. Allocation only.
    fn write_factor_view(&self, view: &mut FactorCompany) {
        let FactorCompany {
            id,
            sector,
            beta,
            market_cap,
            avg_volume,
            shares_outstanding,
            short_interest,
            float,
            garch_variance,
            last_daily_return,
        } = view;
        id.clone_from(&self.id);
        sector.clone_from(&self.sector);
        *beta = self.stock.beta;
        *market_cap = self.stock.market_cap;
        *avg_volume = self.stock.avg_volume;
        *shares_outstanding = self.stock.shares_outstanding;
        *short_interest = self.stock.short_interest;
        *float = self.stock.float;
        *garch_variance = self.stock.garch_variance;
        *last_daily_return = self.stock.last_daily_return;
    }

    /// The microstructure view of this company at a given price.
    ///
    /// Public so an embedder can build the executable book for an instrument
    /// and trade against it. The book a caller sees is therefore the same one
    /// the tick settles through -- displayed depth IS executable depth, which
    /// is the property that makes slippage emergent rather than modelled.
    pub fn micro_view(&self, price: f64) -> CompanyMicrostructure {
        let mut view = CompanyMicrostructure::new(String::new(), price, 0.0);
        self.write_micro_view(price, &mut view);
        view
    }

    /// [`TickCompany::micro_view`] written into a view the tick reuses from
    /// name to name, for the reason [`TickCompany::write_factor_view`]
    /// gives: one string a name a tick, 18 per cent of the allocations.
    fn write_micro_view(&self, price: f64, view: &mut CompanyMicrostructure) {
        let CompanyMicrostructure {
            id,
            sector_volatility,
            price: at,
            market_cap,
            beta,
            float,
            short_interest,
            avg_volume,
            volume,
            shares_outstanding,
            maker_inventory,
        } = view;
        id.clone_from(&self.id);
        *sector_volatility = self.sector_volatility;
        *at = price;
        *market_cap = self.stock.market_cap;
        *beta = self.stock.beta;
        *float = Some(self.stock.float);
        *short_interest = Some(self.stock.short_interest);
        *avg_volume = Some(self.stock.avg_volume);
        *volume = Some(self.stock.volume);
        *shares_outstanding = Some(self.stock.shares_outstanding);
        *maker_inventory = self.stock.maker_inventory;
    }
}

/// Pending order volume for one ticker.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub struct OrderVolume {
    pub buy: f64,
    pub sell: f64,
}

impl OrderVolume {
    pub const fn new(buy: f64, sell: f64) -> Self {
        OrderVolume { buy, sell }
    }
}

/// A live news-impact entry, for the volume amplifier.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct NewsImpactEntry {
    pub company_id: Option<String>,
    pub sector: Option<String>,
    pub sectors: Vec<String>,
    pub remaining_impact: f64,
    pub reversal_phase: bool,
}

/// How settlement consumes its four uniforms — the 2026-08 era's fixed
/// schedule, or the reference's conditional one.
///
/// `settle_price_through_book` takes four draws or zero, and WHICH of the
/// two depends on price-and-state guards: a volume that floors to zero, an
/// empty book. That made the draw schedule a function of the trajectory —
/// any perturbation that flipped one settle guard (a trade's impact, a
/// macro path moving a price) shifted every subsequent draw for every
/// consumer, which is exactly the coupling the counterfactual surfaces
/// (`tca`, `scenario.compare`) exist to avoid. It was measured at zero on
/// current builds and observed at -4 draws on an older one: real, rare,
/// and impossible to rule out while the consumption is conditional.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SettleDrawPolicy {
    /// Four uniforms are drawn per active company on every open tick,
    /// whether or not the settle uses them. The draw schedule becomes a
    /// pure function of (market status, active set, sector count) — no
    /// price, no macro value, no order flow can move it. This is the
    /// era's generated schedule and what `Engine::tick` uses.
    FourAlways,
    /// Four or zero, exactly as the guards decide — the reference's
    /// schedule. For replaying a RECORDED stream, where the tape holds
    /// precisely the draws the reference consumed and drawing four
    /// unconditionally would misalign it.
    FourOrZero,
}

/// Everything the tick needs that is not a company.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TickInputs<'a> {
    pub economy: &'a EconomyState,
    pub market_status: MarketStatus,
    /// Fraction of the session elapsed, from `hours::intraday_fraction`.
    pub intraday_t: f64,
    pub volatility_multiplier: f64,
    pub news: &'a [NewsEvent],
    pub news_impact_queue: &'a [NewsImpactEntry],
    /// Keyed by ticker.
    pub order_volumes: &'a [(String, OrderVolume)],
    /// Sector keys in the order `SECTOR_CONFIGS` enumerates them. The ORDER
    /// is contractual: one normal is drawn per key, in this order.
    pub sector_keys: &'a [String],
    /// One DAILY sigma per sector key from the engine's per-sector variance
    /// state (`sector_vol_alpha` / `_beta`), or EMPTY, which is the stateless
    /// draw at `sector_sigma_at` every preset up to pt-v19 runs.
    pub sector_sigmas: &'a [f64],
    /// The per-name idiosyncratic variance state
    /// (`ModelParams::idio_vol_alpha`): one RATIO per company slot,
    /// multiplying the variance of the name's own draw, or EMPTY when
    /// `idio_vol_alpha`, `_beta` and `_jump_bump` are all 0.0, which is the draw every
    /// preset runs and multiplies nothing.
    pub idio_vol_ratios: &'a [f64],
    /// Whether yesterday's session accumulated a DOWN market factor.
    /// Read only by the lagged transmission wire
    /// (`market_beta_down_asym_lag`); false everywhere that dial is 0.0,
    /// including every recorded reference stream.
    pub prev_day_down: bool,
    /// Yesterday's whole-session accumulated market factor -- the signed
    /// quantity `prev_day_down` is the sign of. Read ONLY when
    /// `market_beta_down_asym_lag_live` is nonzero; at 0.0 nothing looks
    /// at it and every shipped preset is bit-identical whatever it holds.
    pub prev_day_factor: f64,
    /// TODAY's running accumulated market factor BEFORE this tick's own
    /// draw. Read ONLY when `market_beta_down_asym_lag_live` is nonzero.
    pub day_factor: f64,
    /// Fraction of the forced-flow segment's budget remaining, 1.0 when
    /// the reservoir dial is off. See `ModelParams::forced_flow_reservoir`.
    pub forced_flow_eff: f64,
    /// Today's market-factor sigma at DAILY scale — the conditional level
    /// of the factor's variance process ([`super::factor_vol`]), fixed for
    /// the whole session at the previous close's update.
    ///
    /// The engine passes its `MarketVarianceState`'s current sigma on the
    /// generated schedule, and the constant [`MARKET_FACTOR_SIGMA`] when
    /// replaying a recorded reference stream, whose era drew the factor at
    /// constant sigma. A caller building `TickInputs` directly and wanting
    /// the old constant-sigma behaviour passes the constant.
    pub market_sigma_daily: f64,
    /// The factor by which `fair_value_market_vol_cap`'s ceiling is
    /// scaled: exactly 1.0 unless `market_vol_cycle_cap_relative` is set
    /// and the cycle's volatility multiplier is over one, where the ceiling
    /// is read against the phase's normal volatility. See
    /// `ModelParams::market_vol_cycle_cap_relative`.
    pub market_permanent_ceiling_scale: f64,
    /// The session's market mean from today's VIX pins
    /// (`ModelParams::pinned_vix_return`), in log points at a beta of one
    /// over the whole session: each open tick moves every name by its beta
    /// times this over 390, outside the intraday curve. 0.0 on every
    /// unpinned session and with the dial off, where nothing is added.
    pub pinned_mean: f64,
    /// The VIX at which every variance coupling reads ONE.
    ///
    /// `params.market_vol_vix_anchor` under every preset before pt-v19,
    /// which is what `sector_sigma_for` reads it from; under
    /// `vix_level_identity` the engine DERIVES it from the index's own
    /// unconditional variance and passes that instead. Carried rather
    /// than recomputed for the same reason `market_sigma_daily` is: the
    /// draw must read the reference the engine actually ran with.
    pub vix_anchor: f64,
    /// The universe's remembered stress, in VIX points above the crisis
    /// threshold, carried from previous days. Zero under every preset
    /// before pt-v4 and under any preset with the memory disabled, which
    /// is what makes the correlation blend below reproduce exactly.
    pub universe_stress: f64,
    /// Shared log-scale volume multiplier state, from the engine's daily
    /// AR(1). 0.0 means a multiplier of exactly 1.0.
    pub volume_state: f64,
    /// Per-NAME volume state, indexed by company (§107). Empty means the
    /// mechanism is off, which every preset before it is.
    pub volume_idio: &'a [f64],
    /// The log jump each name's `s` took at the LAST close, indexed by
    /// company. Empty, or all zeros, means the volume scale reads the
    /// whole of the day's move, which is every preset: see
    /// [`crate::params::ModelParams::volume_move_jump_share`].
    pub jump_move: &'a [f64],
    /// Each name's volume multiple on an earnings reaction session
    /// (`earnings_volume_multiple`), in roster order; EMPTY off the
    /// calendar, which every preset is, and then nothing is read.
    pub earnings_volume: &'a [f64],
    /// See [`SettleDrawPolicy`]. `FourAlways` unless replaying a recorded
    /// reference stream.
    pub settle_draws: SettleDrawPolicy,
    /// Settle each open tick a second time against unbounded depth, and
    /// report what the difference was.
    ///
    /// Off by default and inert to the market: the second settlement runs on
    /// its own book, its result reaches no company field, and it takes no
    /// draw. It is served the four uniforms the real settlement was served,
    /// rewound, so it requires [`SettleDrawPolicy::FourAlways`] and is
    /// skipped under `FourOrZero`, where the settlement draws from the
    /// caller's recorded source and there is no buffer to rewind.
    pub settle_depth_counterfactual: bool,
    /// Agents' resting orders, per company slot, in arrival order: the
    /// orders the settlement book carries beside the maker's ladder
    /// (`ModelParams::book_resting`). EMPTY, which is every caller but an
    /// engine holding such orders, settles exactly as before: a slot with
    /// no entry, or an empty one, takes the shipped settlement untouched.
    pub resting_orders: &'a [Vec<crate::microstructure::RestingOrder>],
    /// A one-off change to each company's `s` this tick, in log units, per
    /// slot: agents' fills under `ModelParams::fill_impact_coefficient`,
    /// added to the drift and recorded in the order-flow slot. EMPTY, or a
    /// zero entry, adds nothing and is bit-identical to its absence.
    pub fill_impact: &'a [f64],
    /// Nominal output when the run opened: `gdp * cpi` at construction.
    ///
    /// Read only by [`nominal_scale`], and only when
    /// `earnings_nominal_growth` is nonzero, which is pt-v18 and no preset
    /// before it. A caller building `TickInputs` directly passes the
    /// opening `economy.gdp * economy.cpi` of the run it is simulating; a
    /// single-tick caller passes this tick's own, which makes the ratio
    /// 1.0 and the valuation the one every earlier preset computes.
    pub nominal_output_base: f64,
    /// Trading days this run has closed, which is the buyback factor's
    /// clock.
    ///
    /// Read only by [`buyback_scale`], and only when
    /// `buyback_payout_share` is nonzero, which is pt-v18 and no preset
    /// before it. A single-tick caller passes 0, which makes the factor
    /// 1.0 and the valuation the one every earlier preset computes.
    /// The sector at the epicentre of the crisis episode this session is
    /// inside, or `None`.
    ///
    /// The engine's episode state, resolved at `open_market` and fixed for
    /// the whole session. `None` on every preset before pt-v19. See
    /// [`crate::params::ModelParams::crisis_epicentre_extra`] and
    /// `SharedFactors::crisis_epicentre`, which this is copied onto.
    pub crisis_epicentre: Option<&'a str>,
    pub elapsed_days: i64,
    /// The model coefficients (the runtime seam). The
    /// engine passes its own; a caller building `TickInputs` directly
    /// passes [`crate::params::PT_V1`] for the shipped model, which is
    /// bit-identical to the const build.
    pub params: &'a ModelParams,
}

impl<'a> TickInputs<'a> {
    /// A single open-market tick at mid-session over `economy`: volatility
    /// multiplier 1.0, no news, orders, sectors, resting orders or jumps,
    /// the market factor at its baseline sigma
    /// ([`MARKET_FACTOR_SIGMA`]), the preset's VIX anchor, the generated
    /// draw schedule, and this tick's own nominal output as the base, so
    /// the nominal growth ratio is 1.0. Set any other field on the value.
    pub fn new(economy: &'a EconomyState, params: &'a ModelParams) -> Self {
        TickInputs {
            economy,
            market_status: MarketStatus::Open,
            intraday_t: 0.5,
            volatility_multiplier: 1.0,
            news: &[],
            news_impact_queue: &[],
            order_volumes: &[],
            sector_keys: &[],
            sector_sigmas: &[],
            idio_vol_ratios: &[],
            prev_day_down: false,
            prev_day_factor: 0.0,
            day_factor: 0.0,
            forced_flow_eff: 1.0,
            market_sigma_daily: MARKET_FACTOR_SIGMA,
            market_permanent_ceiling_scale: 1.0,
            pinned_mean: 0.0,
            vix_anchor: params.market_vol_vix_anchor,
            universe_stress: 0.0,
            volume_state: 0.0,
            volume_idio: &[],
            jump_move: &[],
            earnings_volume: &[],
            settle_draws: SettleDrawPolicy::FourAlways,
            settle_depth_counterfactual: false,
            resting_orders: &[],
            fill_impact: &[],
            nominal_output_base: economy.gdp * economy.cpi,
            crisis_epicentre: None,
            elapsed_days: 0,
            params,
        }
    }
}

/// What one tick produced, beyond the mutations applied to the companies.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct TickOutcome {
    /// Indices into the input slice, in the order the tick processed them.
    pub active_indices: Vec<usize>,
    /// Fair value per active company — the book's anchor, NOT a price.
    ///
    /// Named for its ROLE in phase 4. It is `fundamental_values * exp(s)`, so
    /// it already contains the mispricing; the valuation itself is
    /// `fundamental_values`. Dividing a print by this gives the
    /// microstructure residual, not the mispricing.
    pub fair_values: Vec<f64>,
    /// The valuation per active company, straight from `compute_fair_value` —
    /// earnings, sector anchor, rates. No mispricing in it.
    pub fundamental_values: Vec<f64>,
    /// Every contribution to this tick's change in `s`, per active company, in
    /// [`S_COMPONENT_KEYS`](crate::market::factors::S_COMPONENT_KEYS) order.
    ///
    /// The reason the whole library exists. `factors` below says what the four
    /// shock drivers were; this says what each of them, plus the reversion and
    /// the crowd, actually DID to the mispricing on this tick. They sum to
    /// `Δs` -- so a consumer can verify the label against the outcome rather
    /// than trusting it.
    pub s_components: Vec<[f64; crate::market::factors::TICK_COMPONENT_COUNT]>,
    /// The `random_noise` slot of `s_components` split into market, sector
    /// and idiosyncratic, per active company, at the same scale the slot
    /// carries. The three sum to that slot up to the order the sum above is
    /// written in, and the slot is still what moved `s`.
    pub noise_parts: Vec<[f64; 3]>,
    /// The square of the scale the idiosyncratic part was drawn at, with
    /// the name's own daily sigma divided out, at the same tick scale. Summed
    /// over a day this is `kappa^2`: how far the day's own-noise variance
    /// sits from the `h` the per-name GJR carries. See
    /// [`crate::params::ModelParams::garch_innovation_commensurate`].
    pub noise_own_scale2: Vec<f64>,
    /// Volume printed per active company.
    pub volumes: Vec<f64>,
    /// The live factor decomposition per active company, in `active_indices`
    /// order.
    ///
    /// This is the labelled-dataset output: the simulator knows WHY each price
    /// moved, which no historical dataset can tell you. Retained rather than
    /// discarded after the drift is summed -- the components cost nothing to
    /// carry and cannot be recovered afterwards.
    pub factors: Vec<LiveFactors>,
    pub shared_factors: SharedFactors,
    /// The shock that arrived, per active company, in log units.
    ///
    /// `log(fair_value / the last print)`: the distance the price model put
    /// between the tape and this tick's anchor, before the book covered any
    /// of it. Phase 4 reports it whether or not the market is open, because
    /// a closed tick still moves fair value and prints the model price.
    pub shock: Vec<f64>,
    /// The depth that absorbed it, per active company, in log units.
    ///
    /// `log(the print / fair_value)`, against the print the tape carries --
    /// so it includes the second circuit breaker, which lands between the
    /// book's last trade and what is published. `shock + absorbed` is the
    /// print's log move away from the last print.
    pub absorbed: Vec<f64>,
    /// How far the second circuit breaker moved the print, per active
    /// company, in log units.
    ///
    /// `log(the print / what the book settled)`, so zero on every tick the
    /// breaker left alone. `absorbed - clamp` is the book's own share of the
    /// distance from the model price to the tape.
    ///
    /// Separate because the two cancel. On every clamped row measured the
    /// book and the breaker pull opposite ways, and on roughly three fifths
    /// of them they cancel to the last bit, so `absorbed` reads exactly zero
    /// on a name the breaker had just moved 513 basis points -- the same
    /// value it takes on a tick that never settled at all.
    pub clamp: Vec<f64>,
    /// What the same tick would have printed against unbounded depth, per
    /// active company.
    ///
    /// Empty unless [`TickInputs::settle_depth_counterfactual`] was set and
    /// the schedule was [`SettleDrawPolicy::FourAlways`]. Same draws, same
    /// book state, same breaker; the only difference is how many resting
    /// levels a slice could walk.
    pub unbounded_print: Vec<f64>,
    /// Liquidity's share of the print's move, per active company.
    ///
    /// `log(print / unbounded_print) / log(print / the last print)`: how far
    /// the depth bound moved the print, as a multiple of the move the print
    /// actually made. Zero when the two prints coincide, which covers every
    /// tick that did not settle, and NaN when the print did not move and the
    /// deeper book would have moved it. Empty alongside `unbounded_print`.
    ///
    /// # It is normally NEGATIVE, and it is not a percentage
    ///
    /// The bound TRUNCATES a walk. A market order that exhausts a shallow
    /// book stops there; against every resting level it keeps filling and
    /// prints further from where it started. So the real print sits between
    /// the last print and the unbounded print, the numerator opposes the
    /// denominator, and the share comes out below zero. Measured on
    /// `Universe.random(12, seed=111)` at seed 42 over three days of pt-v16:
    /// 1,351 rows negative against 72 positive, of 1,436 where the bound
    /// moved the print at all. It read 1,409 against 100 of 1,516 on the
    /// roster the universe generator produced before it was reconciled to
    /// open at fair value, which re-drew the roster and so the market.
    ///
    /// Read it through the identity it satisfies: the unbounded book's move
    /// away from the last print is `1 - share` times the printed move. A
    /// share of -1 means the deeper book would have moved the price twice as
    /// far. Nothing bounds it by one, so a small printed move against a large
    /// truncation gives a large ratio.
    pub liquidity_share: Vec<f64>,
    /// Fills of agents' resting orders in this tick's settlement, with the
    /// company slot each belongs to. Empty unless `resting_orders` held any.
    pub agent_fills: Vec<(usize, crate::microstructure::SettledAgentFill)>,
}

/// Run one simulated market minute.
/// Volume's response to the market factor's variance.
///
/// Returns exactly `1.0` when [`crate::params::ModelParams::volume_variance_gain`]
/// is zero, so every preset before pt-v4 prints the volume it always did --
/// `x * 1.0` is `x` for every f64, which the known-answer digest checks on
/// every build.
///
/// The ratio is taken in VARIANCE rather than sigma because the quantity
/// with the documented persistence is the variance, and squaring the sigma
/// ratio is how the rest of this model spells that (see
/// `factor_vol::update_market_variance_with`'s VIX target).
///
/// Clamped to [0.25, 4.0]: volume is a count, and a multiplier that reached
/// zero would print an empty tape.
/// The persistent volume multiplier, `exp(volume_state)`.
///
/// Returns exactly `1.0` at state 0.0 -- by BRANCH, not by evaluating
/// `exp(0.0)`. The two agree in IEEE-754, but the branch says the intent
/// out loud and owes nothing to an argument about a library function.
fn persistent_volume_multiplier(inputs: &TickInputs) -> f64 {
    if inputs.volume_state == 0.0 {
        return 1.0;
    }
    // Clamped for the same reason the variance multiplier is: volume is a
    // count, and an unbounded multiplier turns a plausible process into a
    // number nobody can defend.
    mathx::clamp(mathx::exp(inputs.volume_state), 0.25, 4.0)
}

fn variance_volume_multiplier(inputs: &TickInputs) -> f64 {
    let gain = inputs.params.volume_variance_gain;
    if gain == 0.0 {
        return 1.0;
    }
    let base_sigma = inputs.params.market_factor_sigma;
    if !(base_sigma > 0.0) {
        return 1.0;
    }
    let sigma_ratio = inputs.market_sigma_daily / base_sigma;
    let raw = 1.0 + gain * (sigma_ratio * sigma_ratio - 1.0);
    mathx::max(mathx::min(raw, 4.0), 0.25)
}

/// The share of a market shock that moves fair value for good at the
/// market's current daily sigma: `fair_value_market_share`, scaled down by
/// `fair_value_market_vol_cap` once the sigma is above that multiple of
/// `market_factor_sigma`, times `ceiling_scale` (exactly 1.0 unless
/// `market_vol_cycle_cap_relative` is set; a branch at 1.0). The share
/// itself at a cap of 0.0, bit for bit.
///
/// Above the ceiling, `fair_value_market_excess_share` of what the ceiling
/// took off the share is put back: `capped + e * (share - capped)`. At 0.0,
/// every preset's value, that is the capped share bit for bit (a branch);
/// at 1.0 it is the share itself, as a cap of 0.0 gives.
pub fn market_permanent_share(
    p: &crate::params::ModelParams,
    market_sigma_daily: f64,
    ceiling_scale: f64,
) -> f64 {
    let share = p.fair_value_market_share;
    if p.fair_value_market_vol_cap == 0.0 {
        return share;
    }
    let ceiling = p.fair_value_market_vol_cap * p.market_factor_sigma;
    let ceiling = if ceiling_scale == 1.0 { ceiling } else { ceiling * ceiling_scale };
    if market_sigma_daily > ceiling {
        let capped = share * (ceiling / market_sigma_daily);
        if p.fair_value_market_excess_share == 0.0 {
            capped
        } else {
            capped + p.fair_value_market_excess_share * (share - capped)
        }
    } else {
        share
    }
}

pub fn simulate_market_tick(
    companies: &mut [TickCompany],
    inputs: &TickInputs,
    rng: &mut impl Rng,
) -> TickOutcome {
    // A closed market changes NOTHING and costs ZERO draws — the guard sits
    // before the shared-factor draws, so a weekend or an overnight hour does
    // not advance the stream at all. Reproducing that position matters as
    // much as reproducing the return: drawing here would desynchronise every
    // consumer on every closed tick, which is most of the clock.
    if inputs.market_status == MarketStatus::Closed {
        return TickOutcome {
            active_indices: Vec::new(),
            fair_values: Vec::new(),
            fundamental_values: Vec::new(),
            s_components: Vec::new(),
            noise_parts: Vec::new(),
            noise_own_scale2: Vec::new(),
            volumes: Vec::new(),
            factors: Vec::new(),
            shared_factors: SharedFactors {
                market_factor: 0.0,
                sector_factors: Vec::new(),
                crisis_spike: 0.0,
                prev_day_down: false,
                // No tick ran, so no draw had a sigma. Zero rather than
                // the constant: a reader of a closed market's factors
                // should not find a plausible sigma there.
                market_sigma_tick: 0.0,
                // No tick ran, so nothing carried the epicentre either.
                crisis_epicentre: None,
            },
            shock: Vec::new(),
            absorbed: Vec::new(),
            clamp: Vec::new(),
            unbounded_print: Vec::new(),
            liquidity_share: Vec::new(),
            agent_fills: Vec::new(),
        };
    }

    let tick_scale_factor = 1.0 / 390.0;
    let tick_scale = 1.0 / mathx::sqrt(390.0);
    let economy = inputs.economy;
    let open = inputs.market_status == MarketStatus::Open;
    let p = inputs.params;
    // THE SESSION'S SHARE OF THE DAY under a night split
    // (`overnight_market_share`, `overnight_idio_share`): the open drew the
    // night at `sqrt(w)`, so the session draws at `sqrt(1 - w)` and the two
    // sum to the day. Branches, so at 0.0 every scale is the one that stood.
    let tick_scale_market = if p.overnight_market_share == 0.0 {
        tick_scale
    } else {
        tick_scale * mathx::sqrt(1.0 - p.overnight_market_share)
    };
    let (tick_scale_own, volatility_multiplier) = if p.overnight_idio_share == 0.0 {
        (tick_scale, inputs.volatility_multiplier)
    } else {
        let k = mathx::sqrt(1.0 - p.overnight_idio_share);
        (tick_scale * k, inputs.volatility_multiplier * k)
    };

    // ── Shared factors: 1 normal, then one per sector ─────────────────────
    // Drawn at PER-TICK scale directly, so the noise is not divided by 390
    // again later. The sigma is the CONDITIONAL level from the factor's
    // variance process, not the constant; when the caller passes the
    // baseline (`MARKET_FACTOR_SIGMA`) this line is bit-identical to the
    // constant-sigma era's spelling, association included.
    rng.site(crate::rng::Site::MarketFactorZ, 0);
    let market_factor = rng.next_normal() * inputs.market_sigma_daily * tick_scale_market;

    // Crisis correlation: above the crisis threshold, sector factors blend
    // toward the market factor, so diversification stops working exactly
    // when it is most wanted.
    //
    // Re-sited at the 2026-08 era boundary, in step with the economy's
    // crisis gates. The reference's trigger was `vix > 40` with a `/30`
    // ramp, and both halves were dead: endogenous VIX has a measured hard
    // ceiling of 26.57 (zero days above 30 in 42,336; the reference's own
    // economy goldens top out at 29.09, so the gates never fired upstream
    // either), and even a pinned VIX at the old trigger bought a blend of
    // at most 0.25 by the ramp. `CRISIS_VIX_THRESHOLD` (25.5, the P94 of
    // the long-run endogenous distribution — rare and real in this
    // model's own units) makes the trigger reachable, and the /1.4 ramp
    // makes crossing it MEAN something: the blend saturates at its 0.8
    // cap by VIX ≈ 26.6, the ceiling of what the macro chain can produce,
    // instead of asking for a VIX of 64 that cannot exist.
    let vix_correlation_spike = crisis_spike_for(p, economy.vix, inputs.universe_stress);

    // The sector draw's sigma is `sector_sigma_for`, shared with the
    // overnight move; the arithmetic is the one that stood here.
    let sector_sigma = sector_sigma_at(p, economy, inputs.vix_anchor);
    let mut sector_factors = Vec::with_capacity(inputs.sector_keys.len());
    for (sector_index, sector) in inputs.sector_keys.iter().enumerate() {
        rng.site(crate::rng::Site::SectorZ, sector_index as u32);
        // The sector's own variance state when one is running, else the
        // shared VIX-coupled sigma -- the same multiply in the same order
        // when `sector_sigmas` is empty.
        let sector_sigma = match inputs.sector_sigmas.get(sector_index) {
            Some(s) => *s,
            None => sector_sigma,
        };
        let idiosyncratic = rng.next_normal() * sector_sigma * tick_scale_own;
        // Where the blend takes from. At source 0.0 the sector draw is
        // attenuated and the market factor injected through this slot, the
        // reference behaviour. At 1.0 the draw is kept whole and the same
        // injection is applied in factors.rs to the market component, scaled
        // by the source weight; in between, proportionally.
        let kept = if p.crisis_blend_source == 0.0 {
            idiosyncratic * (1.0 - vix_correlation_spike) + market_factor * vix_correlation_spike
        } else {
            let consumed = idiosyncratic * (1.0 - vix_correlation_spike)
                + market_factor * vix_correlation_spike;
            consumed * (1.0 - p.crisis_blend_source) + idiosyncratic * p.crisis_blend_source
        };
        sector_factors.push((sector.clone(), kept));
    }
    // THE LAGGED WIRE'S CONDITION, and WHERE it is sampled is the dial.
    //
    // At `market_beta_down_asym_lag_live` 0.0 this is exactly the bit the
    // engine read at the open and nothing below runs -- the same boolean,
    // by the same comparison, so every preset through pt-v19 is
    // bit-identical. At 1.0 the SAME condition ("the market has fallen
    // over the last session") is evaluated against the state as it stands
    // at this tick: yesterday's total decayed by the fraction of the
    // session already elapsed, plus today's own running sum. That is
    // `E[sum of the last 390 tick factors]` given the two numbers the
    // variance state already holds, and it needs no new state and no draw.
    //
    // `inputs.day_factor` is the accumulator BEFORE this tick's factor
    // lands (the engine accumulates after `simulate_market_tick` returns),
    // so the multiplier is a function of strictly earlier draws and the
    // day's delivered factor keeps its zero mean. See
    // `ModelParams::market_beta_down_asym_lag_live`.
    let lag_condition = if p.market_beta_down_asym_lag_live == 0.0 {
        inputs.prev_day_down
    } else {
        let c = inputs.prev_day_factor * (1.0 - inputs.intraday_t) + inputs.day_factor;
        // 2.0 is the registered SIGN CONTROL (F4), not a shipping value.
        if p.market_beta_down_asym_lag_live >= 2.0 {
            c > 0.0
        } else {
            c < 0.0
        }
    };
    let shared = SharedFactors {
        market_factor,
        sector_factors,
        crisis_spike: vix_correlation_spike,
        prev_day_down: lag_condition,
        // The same expression the draw above multiplied the normal by, so
        // the recentring reads the sigma that was actually used rather
        // than one recomputed from the constant.
        market_sigma_tick: inputs.market_sigma_daily * tick_scale_market,
        // Resolved once at `open_market` and carried, not recomputed: the
        // episode's epicentre is a property of the SESSION, and a tick that
        // re-read the engine's state mid-day would let an episode start
        // between two ticks of one day.
        crisis_epicentre: inputs.crisis_epicentre.map(|s| s.to_string()),
    };

    let intraday_vol_mult = intraday_vol(inputs.intraday_t);
    let intraday_volume_mult = intraday_volume(inputs.intraday_t, inputs.market_status);

    // ── Phase 1: factors ──────────────────────────────────────────────────
    // Sized for the roster once rather than grown name by name: allocation
    // only, so no arithmetic or draw moves.
    let roster = companies.len();
    let mut active_indices: Vec<usize> = Vec::with_capacity(roster);
    let mut all_factors: Vec<LiveFactors> = Vec::with_capacity(roster);
    let mut all_drifts: Vec<f64> = Vec::with_capacity(roster);
    let mut all_noises: Vec<f64> = Vec::with_capacity(roster);
    let mut all_news_vol_mults: Vec<f64> = Vec::with_capacity(roster);
    let mut all_randoms: Vec<f64> = Vec::with_capacity(roster);
    // One view for the whole roster, rewritten for each name.
    let mut view = FactorCompany::new(String::new(), String::new());

    for (idx, company) in companies.iter().enumerate() {
        if company.is_bankrupt || !company.is_public {
            continue;
        }
        active_indices.push(idx);

        let vol = inputs
            .order_volumes
            .iter()
            .find(|(t, _)| t == &company.ticker)
            .map(|(_, v)| *v)
            .unwrap_or_default();
        // `_with`, so `order_flow_impact_law` selects the participation
        // law. At 0.0 it delegates to `order_imbalance` unchanged, and a
        // name with no injected flow reads a default `OrderVolume` and
        // gets `+0.0` under either law.
        let imbalance =
            order_imbalance_with(p, vol.buy, vol.sell, company.stock.avg_volume);

        // DRAW SITE: one normal, inside the factor computation.
        rng.site(crate::rng::Site::FactorIdioZ, idx as u32);
        // The idiosyncratic variance state scales the name's own draw
        // through the one multiplier that reaches only that draw (and its
        // unit, so `noise_own_scale2` carries it). EMPTY is a branch. It
        // scales the session's share under a night split, which the
        // multiplier above already carries.
        let volatility_multiplier = match inputs.idio_vol_ratios.get(idx) {
            Some(&r) => volatility_multiplier * mathx::sqrt(r),
            None => volatility_multiplier,
        };
        company.write_factor_view(&mut view);
        let factors = calculate_live_factors(
            &view,
            inputs.news,
            imbalance,
            volatility_multiplier,
            &shared,
            p,
            rng,
        );

        // Only the SHOCK factors reach the price. Every driver lives in fair
        // value now, and every anchor is replaced by `s`'s own reversion.
        let (drift, noise) = if open {
            (
                (factors.company_news + factors.order_flow_impact + factors.short_squeeze_effect)
                    * tick_scale_factor,
                factors.random_noise,
            )
        } else {
            (
                (factors.company_news + factors.order_flow_impact) * tick_scale_factor,
                factors.random_noise * 0.15,
            )
        };
        // An agent's fills under the linear law land here, whole, on the
        // tick after the fills. A branch on the slot, so a caller with no
        // entry adds nothing rather than `+ 0.0`.
        let drift = match inputs.fill_impact.get(idx) {
            Some(&x) if x != 0.0 => drift + x,
            _ => drift,
        };
        all_drifts.push(drift);
        all_noises.push(noise);
        all_factors.push(factors);

        // News amplifies volume, capped at 10x.
        let mut news_volume_mult = 1.0;
        let mut impact_sum = 0.0;
        for entry in inputs.news_impact_queue {
            if entry.reversal_phase {
                continue;
            }
            let matches = entry.company_id.as_deref() == Some(company.id.as_str())
                || entry.sector.as_deref() == Some(company.sector.as_str())
                || entry.sectors.iter().any(|s| s == &company.sector);
            if matches {
                impact_sum += entry.remaining_impact;
            }
        }
        if impact_sum > 0.0 {
            news_volume_mult = 1.0 + mathx::min(9.0, impact_sum / 0.01);
        }
        all_news_vol_mults.push(news_volume_mult);

        // DRAW SITE: one uniform, STASHED. It is consumed in phase 3, and
        // drawing it there instead would give the same count on a different
        // stream.
        rng.site(crate::rng::Site::StashU, idx as u32);
        all_randoms.push(rng.next_f64());
    }

    let active_count = active_indices.len();
    let previous_closes: Vec<f64> = active_indices
        .iter()
        .map(|&i| companies[i].stock.previous_close)
        .collect();
    let current_prices: Vec<f64> = active_indices
        .iter()
        .map(|&i| companies[i].stock.price)
        .collect();

    // ── Phase 2: the s-process ────────────────────────────────────────────
    let econ_view = EconomyValuationInputs {
        corporate_bond_yield: Some(economy.corporate_bond_yield),
        federal_funds_rate: economy.federal_funds_rate,
        qe_pe_boost: Some(economy.qe_pe_boost),
        qe_assets_ratio: Some(economy.qe_assets_ratio),
    };

    let mut new_prices = vec![0.0; active_count];
    let mut fundamentals = vec![f64::NAN; active_count];
    let vix_exposure = vix_feedback_exposure(p, economy);
    let mut s_components = vec![[0.0f64; crate::market::factors::TICK_COMPONENT_COUNT]; active_count];
    let mut noise_parts = vec![[0.0f64; 3]; active_count];
    let mut noise_own_scale2 = vec![0.0f64; active_count];
    let mut crowd_leans = vec![0.0; active_count];

    // The fundamentals restated in the economy's current price level and
    // output, once for the whole tick because it is a macro quantity.
    // Exactly 1.0 under every preset before pt-v18, by the branch in
    // `nominal_scale`, and 1.0 on day 0 under pt-v18 as well.
    let nominal = nominal_scale(p, economy, inputs.nominal_output_base);

    for i in 0..active_count {
        let idx = active_indices[i];
        // A BRANCH rather than a multiply by 1.0. The two agree on every
        // finite value, and the branch is what the preset contract rests
        // on rather than on an argument about how floats behave.
        let grown = if nominal == 1.0 {
            companies[idx].valuation()
        } else {
            scale_valuation(companies[idx].valuation(), nominal)
        };
        // The name's own fair-value level: the published fundamentals
        // scaled by what its permanent news has done to them. A BRANCH at
        // zero, so every preset through pt-v19, where nothing writes the
        // level, values the published figures exactly as before. Read at
        // the START of the tick; this tick's own news reaches the price
        // below, through `fv_moved`.
        let v_level = companies[idx].stock.fair_value_offset.unwrap_or(0.0);
        let grown = if v_level == 0.0 {
            grown
        } else {
            scale_valuation(grown, mathx::exp(v_level))
        };
        // Per NAME, unlike the growth term above: the yield is this
        // company's own earnings over its own price. A BRANCH at 1.0 for
        // the same reason as the one above.
        let buyback = buyback_factor(
            p, crate::market::dividends::buyback_share(p, &companies[idx]),
            grown.eps, current_prices[i], inputs.elapsed_days,
            companies[idx].stock.buyback_log_shares);
        let valuation = if buyback == 1.0 {
            grown
        } else {
            scale_valuation(grown, buyback)
        };
        let breakdown = crate::fair_value::compute_fair_value_at(
            &valuation, &econ_view, p.fair_value_book_floor,
            p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity);
        let fv = with_vix_discount(p, breakdown.fair_value, vix_exposure, companies[idx].stock.beta);
        // The dividend accrued since the last ex-date, in price units. A
        // branch inside: no state, or no accrual, is `fv` bit for bit.
        let fv = crate::market::dividends::with_accrual(fv, &companies[idx]);

        // Lazy init: adopt the current premium/discount as the starting `s`,
        // so enabling the model — or loading an old save — causes no level
        // jump.
        if companies[idx].stock.mispricing_s.is_none() {
            let s0 = clamp_s(p, mathx::log(mathx::max(0.01, current_prices[i]) / fv));
            companies[idx].stock.mispricing_s = Some(s0);
            companies[idx].stock.mispricing_s_prev_close = Some(s0);
            companies[idx].stock.mispricing_momentum = Some(0.0);
        }

        let mut s_val = companies[idx].stock.mispricing_s.unwrap();
        let momentum = companies[idx].stock.mispricing_momentum.unwrap_or(0.0);
        fundamentals[i] = fv;

        // Forced flow: the stress-activated COMMON lean (params docstring).
        // Computed once, applied AND recorded in the crowd's slot -- the
        // attribution contract is "recorded as applied". A branch, not
        // arithmetic, so 0.0 is bit-identical.
        let forced = if p.forced_flow_gain != 0.0 {
            let common = -p.forced_flow_gain
                * mathx::max(0.0, economy.vix - p.forced_flow_threshold)
                * inputs.forced_flow_eff;
            // beta^0 through a branch, so screen one's uniform lean and
            // every recorded run reproduce bit for bit.
            if p.forced_flow_beta_exponent != 0.0 {
                let beta = companies[idx].stock.beta.unwrap_or(1.0);
                common * mathx::pow(mathx::max(beta, 0.1), p.forced_flow_beta_exponent)
            } else {
                common
            }
        } else {
            0.0
        };

        // Each contribution recorded as it is applied, in the same spelling
        // the update uses. Reported, never fed back: the update below is
        // written exactly as the source writes it, because `s*phi` and
        // `s + s*(phi-1)` round differently and the benched trajectories were
        // produced by that spelling. Summing these to advance `s` instead
        // would be a different market.
        let raw = &all_factors[i];
        let scale = 1.0 / 390.0;
        // The market's next-session reversal (`market_factor_reversal`): on
        // each open tick the name takes -k * beta * F_{d-1} / 390, where
        // F_{d-1} is yesterday's whole accumulated market factor. Booked to
        // the crowd's slot (it is the liquidity the crowd provides against
        // yesterday's market-wide move) and moved whole into the fair-value
        // level below, so it does not revert. A branch: 0.0 adds nothing.
        // Under `market_factor_reversal_vix_power` q the share is
        // k * (X / 20)^q, X the economy's VIX at the last close (a branch:
        // q = 0.0 is k as it stands).
        let reversal = if open && p.market_factor_reversal != 0.0 {
            let k = if p.market_factor_reversal_vix_power != 0.0 {
                p.market_factor_reversal
                    * mathx::pow(mathx::max(economy.vix, 0.0) / 20.0, p.market_factor_reversal_vix_power)
            } else {
                p.market_factor_reversal
            };
            -k * companies[idx].stock.beta.unwrap_or(1.0) * inputs.prev_day_factor / 390.0
        } else {
            0.0
        };
        // THE PINNED SESSION'S MEAN (`pinned_vix_return`): this name's beta
        // times the session's conditional mean over its 390 open ticks,
        // outside the intraday curve, so the session's sum is the mean the
        // pins set. Exactly 0.0 off a pinned session, and every use below is
        // a branch on it, so nothing is added.
        let pin_mean = if open && inputs.pinned_mean != 0.0 {
            companies[idx].stock.beta.unwrap_or(1.0) * inputs.pinned_mean / 390.0
        } else {
            0.0
        };
        s_components[i] = if open {
            [
                s_val * (p.s_phi_tick - 1.0),
                (p.momentum_theta * momentum) / 390.0,
                if reversal != 0.0 {
                    (if p.forced_flow_gain != 0.0 {
                        crowd_lean_with(p, s_val, momentum) + forced
                    } else {
                        crowd_lean_with(p, s_val, momentum)
                    }) / 390.0
                        + reversal
                } else {
                    (if p.forced_flow_gain != 0.0 {
                        crowd_lean_with(p, s_val, momentum) + forced
                    } else {
                        crowd_lean_with(p, s_val, momentum)
                    }) / 390.0
                },
                raw.company_news * scale,
                with_fill_impact(raw.order_flow_impact * scale, inputs.fill_impact.get(idx)),
                raw.short_squeeze_effect * scale,
                if pin_mean != 0.0 {
                    all_noises[i] * intraday_vol_mult + pin_mean
                } else {
                    all_noises[i] * intraday_vol_mult
                },
                // The breaker's slot, filled below if it binds.
                0.0,
                // The fair-value shift's, filled below under the permanent share.
                0.0,
            ]
        } else {
            // Closed: no reversion, no crowd, and the squeeze term is not
            // applied -- `all_drifts` dropped it. Zeros here are the honest
            // report of that, not missing data.
            [
                0.0,
                0.0,
                0.0,
                raw.company_news * scale,
                with_fill_impact(raw.order_flow_impact * scale, inputs.fill_impact.get(idx)),
                0.0,
                all_noises[i],
                0.0,
                0.0,
            ]
        };

        // The noise slot's three parts and the scale its own part was drawn
        // at, both at the scale the slot above carries: `all_noises` already
        // holds the closed tick's 0.15, and the open tick's
        // `intraday_vol_mult` multiplies once more. Read off `raw` rather
        // than recomputed, so these cannot drift from the draw. Nothing here
        // touches `s_val` below; the close reads them, and only when
        // `garch_innovation_commensurate` is non-zero.
        let noise_scale = if open { intraday_vol_mult } else { 0.15 };
        noise_parts[i] = [
            if pin_mean != 0.0 { raw.noise_market * noise_scale + pin_mean } else { raw.noise_market * noise_scale },
            raw.noise_sector * noise_scale,
            raw.noise_idio * noise_scale,
        ];
        let own_scale = raw.noise_idio_unit * noise_scale;
        noise_own_scale2[i] = own_scale * own_scale;

        if open {
            // The crowd reacts to the mispricing it can SEE — the pre-update
            // state — so there is no same-tick feedback loop.
            let lean = crowd_lean_with(p, s_val, momentum);
            crowd_leans[i] = lean;
            // Written exactly as the source writes it. `s*φ` and
            // `s + s*(φ-1)` round differently, and the benched trajectories
            // were produced by this spelling.
            s_val = s_val * p.s_phi_tick
                + (p.momentum_theta * momentum) / 390.0
                + (if p.forced_flow_gain != 0.0 { lean + forced } else { lean }) / 390.0
                + all_drifts[i]
                + all_noises[i] * intraday_vol_mult;
            if reversal != 0.0 {
                s_val += reversal;
            }
            if pin_mean != 0.0 {
                s_val += pin_mean;
            }
        } else {
            s_val = s_val + all_drifts[i] + all_noises[i];
        }
        // THE PERMANENT SHARE of the name's own shocks. `psi` of this tick's
        // idiosyncratic and sector noise and of the news naming this company,
        // its peers or its sector leaves `s`
        // for the fair-value level, with an Ito term so `exp(v)` is a
        // martingale. The price moves by the whole shock either way; only
        // what later reverts changes. A branch, so 0.0 is the arithmetic
        // that stood, bit for bit.
        let mut fv_moved = fv;
        if p.fair_value_news_share != 0.0 || p.fair_value_market_share != 0.0 || reversal != 0.0 {
            let psi = p.fair_value_news_share;
            let noise_scale = if open { intraday_vol_mult } else { 0.15 };
            let own_noise = psi * ((raw.noise_idio + raw.noise_sector) * noise_scale);
            let own_news = psi * ((raw.company_news - raw.company_news_market) * scale);
            // The market-wide part, on its own share: the name's loading on
            // the market factor's draw and the market-wide news. A branch at
            // zero, so the stock-level share alone is the arithmetic above.
            let dv = if p.fair_value_market_share == 0.0 {
                own_noise + own_news
            } else {
                let psim = market_permanent_share(
                    p, inputs.market_sigma_daily, inputs.market_permanent_ceiling_scale);
                // Under `fair_value_market_linear` only the plain loading on
                // the draw is permanent; the tilt, the lagged wire, the
                // crisis injection and the amplifier stay in `s`.
                let market_draw = if p.fair_value_market_linear == 0.0 {
                    raw.noise_market
                } else {
                    raw.noise_market_linear
                };
                let dv = own_noise + own_news
                    + psim * (market_draw * noise_scale)
                    + psim * (raw.company_news_market * scale);
                // The pinned mean leaves `s` on the market draw's own share,
                // as the plain loading does.
                if pin_mean != 0.0 { dv + psim * pin_mean } else { dv }
            };
            // The market's reversal is permanent whole: it leaves `s` for
            // `v` on the tick it is applied. A branch, so 0.0 is `dv` as it
            // stood. Under `market_factor_reversal_transient` tau, tau of it
            // stays in `s` (the transient mispricing) and only the rest moves
            // to `v`; a branch, so tau 0.0 is the whole reversal as it stood,
            // and tau 1.0 adds nothing to `dv`.
            let dv = if reversal != 0.0 {
                if p.market_factor_reversal_transient != 0.0 {
                    let moved = (1.0 - p.market_factor_reversal_transient) * reversal;
                    if moved != 0.0 { dv + moved } else { dv }
                } else {
                    dv + reversal
                }
            } else {
                dv
            };
            // The component slots keep the WHOLE shock, deliberately: they
            // report what moved the PRICE (the attribution an agent's
            // explanation is scored against), and the close feeds slot 6 to
            // the name's GJR as the day's innovation, which is the full
            // move whichever of `s` and `v` carries it. `fair_value_shift`
            // books what left `s` for `v`, so all the slots together sum to
            // the change in `s`, and all but that one to the change in `s + v`.
            if dv != 0.0 {
                let before = s_val;
                s_val -= dv;
                s_components[i][crate::market::factors::TICK_FAIR_VALUE] += s_val - before;
                let step = dv - 0.5 * dv * dv;
                companies[idx].stock.fair_value_offset = Some(v_level + step);
                fv_moved = fv * mathx::exp(step);
            }
        }
        s_val = clamp_s(p, s_val);
        let fv = fv_moved;
        fundamentals[i] = fv;

        let mut new_price = mathx::max(0.01, fv * mathx::exp(s_val));

        // Breaker #1 — the MODEL price. If it binds, `s` is re-derived from
        // the clamped price so state and price stay consistent. The band
        // multipliers are derived ONCE, in the params constructor (§5.3),
        // never per call site.
        let max_price = previous_closes[i] * p.breaker_up;
        let min_price = mathx::max(previous_closes[i] * p.breaker_down, 0.01);
        if new_price > max_price || new_price < min_price {
            new_price = mathx::max(min_price, mathx::min(max_price, new_price));
            let before = s_val;
            s_val = clamp_s(p, mathx::log(new_price / fv));
            // What the breaker took off the tick, booked to the breaker. The
            // columns reconstruct the move on a halted day now (§79).
            s_components[i][7] += s_val - before;
        }

        companies[idx].stock.mispricing_s = Some(s_val);
        new_prices[i] = mathx::min(new_price, p.price_hard_cap);
    }

    // ── Phase 3: volume ───────────────────────────────────────────────────
    let volume_multiplier = if open { 1.0 } else { 0.1 };
    // Volume tracks the market factor's variance, which is persistent and
    // exogenous to volume. At gain 0 this is exactly 1.0 and the product
    // below is bit-identical to the single-multiplier form.
    let volume_multiplier = volume_multiplier * variance_volume_multiplier(inputs);
    // The persistent component: exactly 1.0 at state 0.0, so the product
    // is bit-identical for every preset that does not set it.
    let volume_multiplier = volume_multiplier * persistent_volume_multiplier(inputs);
    let mut volumes = vec![0.0; active_count];
    for i in 0..active_count {
        let idx = active_indices[i];
        // The per-NAME persistent component (§107). Guarded on the slice
        // being empty AND on the state being zero, so a preset that does not
        // set it multiplies by nothing at all rather than by `exp(0.0)`.
        let volume_multiplier = match inputs.volume_idio.get(idx) {
            Some(&s) if s != 0.0 => {
                volume_multiplier * mathx::clamp(mathx::exp(s), 0.25, 4.0)
            }
            _ => volume_multiplier,
        };
        // Volume that follows the NAME's own conditional variance (§112).
        //
        // §111 measured why the per-name state of §107 could not be used: it
        // fixes `volume_change_acf1` and takes `volume_abs_return_corr` down
        // with it, exactly as the COMMON component does. The cause is not
        // common-versus-per-name, which is what §107 assumed. It is that
        // volume variance unrelated to a name's own returns dilutes a
        // statistic measuring how well volume tracks the size of that name's
        // move, and per-name noise is as unrelated as market-wide noise.
        //
        // This is the return-RELATED version, and the per-name analogue of
        // `volume_variance_gain`, which does the same thing with the MARKET
        // factor's variance and nothing else. The reference is the sector's
        // base daily variance, a static table lookup, so no plumbing and no
        // new state.
        let volume_multiplier = if inputs.params.volume_idio_variance_gain == 0.0 {
            volume_multiplier
        } else {
            match crate::sectors::by_key(&companies[idx].sector)
                .map(|s| s.base_daily_variance())
            {
                Some(base) if base > 0.0 => {
                    let ratio = companies[idx].stock.garch_variance / base;
                    let raw = 1.0
                        + inputs.params.volume_idio_variance_gain * (ratio - 1.0);
                    volume_multiplier * mathx::clamp(raw, 0.25, 4.0)
                }
                _ => volume_multiplier,
            }
        };
        let stock = &companies[idx].stock;
        // Zero-guard: a newly listed company before `resetDailyPrices` seeds
        // `open` would divide by zero and propagate NaN into the batch.
        let daily_change = if stock.open > 0.0 {
            let move_from_open = (new_prices[i] - stock.open) / stock.open;
            // The whole move, jumps included -- the shipped spelling, and a
            // BRANCH rather than a multiply by one, so every preset that
            // leaves the share alone takes the arithmetic that was here.
            //
            // Off 1.0 the day is measured from the open the name would have
            // had if `(1 - share)` of the last close's jump had gapped
            // overnight instead of trading in through the book. A jump is
            // booked into `mispricing_s` at the close and `open` is set from
            // the price before it, so at share 1.0 a gap counts as a day the
            // name travelled that far. See
            // `ModelParams::volume_move_jump_share`.
            //
            // Under a night split the day is measured from the last close
            // (`previous_close`, which the open then leaves at the close):
            // the session carries only part of the day's move, and a real
            // day's volume answers the whole of it.
            if p.overnight_market_share != 0.0 || p.overnight_idio_share != 0.0 {
                if stock.previous_close > 0.0 {
                    ((new_prices[i] - stock.previous_close) / stock.previous_close).abs()
                } else {
                    move_from_open.abs()
                }
            } else if inputs.params.volume_move_jump_share == 1.0 {
                move_from_open.abs()
            } else {
                match inputs.jump_move.get(idx) {
                    Some(&j) if j != 0.0 => {
                        let open_eff = stock.open
                            * mathx::exp((1.0 - inputs.params.volume_move_jump_share) * j);
                        ((new_prices[i] - open_eff) / open_eff).abs()
                    }
                    _ => move_from_open.abs(),
                }
            }
        } else {
            0.0
        };
        let base_volume = stock.avg_volume / 390.0;
        let price_magnitude = daily_change / 0.01;
        // The stashed uniform from phase 1, consumed here.
        // Four literals until 0.3.0, shipped at their old values so this is
        // bit-identical wherever a preset leaves them alone. `volume_move_cap`
        // is the one that mattered: at 4.0 every move past four percent
        // trades the same, so no crisis day contributes any covariance to
        // `volume_abs_return_corr`. See ModelParams::volume_move_cap.
        let p = inputs.params;
        let volume_scale = p.volume_move_floor
            + p.volume_move_response * mathx::min(price_magnitude, p.volume_move_cap)
            + all_randoms[i] * p.volume_move_noise;
        volumes[i] = (base_volume
            * volume_multiplier
            * volume_scale
            * intraday_volume_mult
            * all_news_vol_mults[i])
            .floor();
        // A reaction session's multiple (`earnings_volume_multiple`), read
        // only where the engine passed one: empty off the calendar.
        if let Some(&m) = inputs.earnings_volume.get(idx) {
            if m != 1.0 {
                volumes[i] = (volumes[i] * m).floor();
            }
        }
    }

    // ── Phase 4: settlement ───────────────────────────────────────────────
    //
    // The decomposition columns are filled here rather than derived
    // afterwards, because `shock` is measured against the LAST print and a
    // consumer reading a finished table has already lost it at the first tick
    // of a day.
    let mut shock_col = vec![0.0; active_count];
    let mut absorbed_col = vec![0.0; active_count];
    let mut clamp_col = vec![0.0; active_count];
    // The counterfactual arm needs the buffered uniforms, which exist only on
    // the engine's own generated schedule. Under `FourOrZero` the settlement
    // draws lazily from the caller's recorded stream and a second settlement
    // would take draws off it, so the arm does not run and its columns stay
    // empty rather than being filled with the real print twice.
    let depth_arm = inputs.settle_depth_counterfactual
        && inputs.settle_draws == SettleDrawPolicy::FourAlways;
    let mut unbounded_col = if depth_arm { vec![0.0; active_count] } else { Vec::new() };
    let mut share_col = if depth_arm { vec![0.0; active_count] } else { Vec::new() };
    let mut agent_fills: Vec<(usize, crate::microstructure::SettledAgentFill)> = Vec::new();
    // One view for the whole roster, rewritten for each name before it
    // settles.
    let mut micro = CompanyMicrostructure::new(String::new(), 0.0, 0.0);

    for i in 0..active_count {
        let idx = active_indices[i];
        let fair_value = new_prices[i];
        let volume = volumes[i].floor();
        // The tape's last print, read before this tick overwrites it at the
        // foot of the loop. `micro` below is built from the same field.
        let last_print = companies[idx].stock.price;
        // The breaker's band for this company, hoisted so the counterfactual
        // print is clamped by the same bounds as the real one. Comparing a
        // clamped print against an unclamped one would book the breaker to
        // liquidity.
        let print_max = previous_closes[i] * p.breaker_up;
        let print_min = mathx::max(previous_closes[i] * p.breaker_down, 0.01);
        let breaker = |price: f64| {
            if price > print_max || price < print_min {
                mathx::max(print_min, mathx::min(print_max, price))
            } else {
                price
            }
        };
        // NaN until the arm runs, and never read unless it does.
        let mut unbounded_price = f64::NAN;

        let mut new_price = fair_value;
        if open {
            // DRAW SITE: four uniforms. Under `FourAlways` they are drawn
            // HERE, unconditionally, and the settle is served from the
            // buffer — an early return leaves drawn values unused rather
            // than draws untaken, so the stream's position cannot depend on
            // which guard fired. Under `FourOrZero` the settle draws
            // lazily from the shared source, four or zero, matching what a
            // recorded reference stream actually holds.
            rng.site(crate::rng::Site::SettleU, idx as u32);
            let mut predrawn = match inputs.settle_draws {
                SettleDrawPolicy::FourAlways => Some(PredrawnUniforms::new([
                    rng.next_f64(),
                    rng.next_f64(),
                    rng.next_f64(),
                    rng.next_f64(),
                ])),
                SettleDrawPolicy::FourOrZero => None,
            };
            // Quote revision on public news. The maker quotes around the
            // last print, so a model price that jumps on news reaches the
            // tape only as fast as the tick's flow can walk the book: an
            // event priced whole in one tick printed a seventh of it after
            // that tick and under half after five. Public news moves quotes
            // without a trade (dealers re-quote on the wire), so with
            // `news_quote_revision` on, the book is quoted around the last
            // print moved by this tick's news term, and the flow trades
            // from there. At 0.0 -- every preset -- or on a tick with no
            // news term, the branch is not taken and the book is the one
            // that always stood.
            //
            // `quote_model_weight` generalises that from news to every move:
            // the book is centred on the tick's model price (1.0), or on the
            // geometric blend of the last print and the model price in
            // between. At 0.0 -- every preset through pt-v19 -- the branch
            // is not taken and the news rule above is the one that stands.
            let quote_from = if p.quote_model_weight != 0.0 {
                if p.quote_model_weight == 1.0 {
                    fair_value
                } else {
                    let last = companies[idx].stock.price;
                    last * mathx::exp(p.quote_model_weight * mathx::log(fair_value / last))
                }
            } else if p.news_quote_revision == 0.0 || s_components[i][3] == 0.0 {
                companies[idx].stock.price
            } else {
                companies[idx].stock.price * mathx::exp(s_components[i][3])
            };
            companies[idx].write_micro_view(quote_from, &mut micro);
            let options = SettleOptions {
                // From the params, so a preset that smooths the size curve
                // smooths it in settlement too rather than only in the book.
                spread_size_smoothness: inputs.params.spread_size_smoothness,
                spread_size_exponent: inputs.params.spread_size_exponent,
                vix: economy.vix,
                difficulty: None,
                flow_lean: Some(crowd_leans[i]),
                // The shipped bound. `settle_price_through_book` returns it
                // untouched at 1.0, so this line moves no trajectory.
                depth_multiplier: 1.0,
            };
            // Agents' resting orders for this name, if any. With none, the
            // settlement is the shipped call, untouched.
            let resting = match inputs.resting_orders.get(idx) {
                Some(orders) if !orders.is_empty() => orders.as_slice(),
                _ => &[],
            };
            let settled = if resting.is_empty() {
                match predrawn.as_mut() {
                    Some(buffer) => {
                        settle_price_through_book(&micro, fair_value, volume, &options, buffer)
                    }
                    None => settle_price_through_book(&micro, fair_value, volume, &options, rng),
                }
            } else {
                let (settled, fills) = match predrawn.as_mut() {
                    Some(buffer) => settle_price_through_book_with_orders(
                        &micro, fair_value, volume, &options, resting, buffer),
                    None => settle_price_through_book_with_orders(
                        &micro, fair_value, volume, &options, resting, rng),
                };
                agent_fills.extend(fills.into_iter().map(|f| (idx, f)));
                settled
            };
            new_price = settled.price;
            // THE CLOSING CROSS. The session's final regular tick (15:59,
            // `intraday_t` = 389/390, the same division `intraday_fraction`
            // makes) prints at the model price, as a closing auction clears
            // at the efficient price and not at whichever side of the book
            // the last minute's flow hit. The settlement above still ran,
            // so the tick costs the same draws; its fills are the book's
            // and not the auction's, so they do not move the maker's
            // inventory. A switch at 0.0 on every preset through pt-v19,
            // where the branch is not taken.
            let auction = p.closing_auction != 0.0 && inputs.intraday_t == 389.0 / 390.0;
            if auction {
                new_price = fair_value;
            }

            // The depth counterfactual: this tick again, from the same state,
            // against every level the maker quotes.
            //
            // It runs HERE, between the settlement and the maker-inventory
            // carry below, for two reasons. The book it quotes against is
            // built from `micro`, which was taken before the settlement, so
            // the arm sees the state the real settlement saw rather than the
            // state it left. And it takes NO draw: the buffer is rewound and
            // serves the same four uniforms a second time, which is why the
            // stream position after this block is what it was without it.
            if depth_arm {
                if let Some(buffer) = predrawn.as_mut() {
                    buffer.rewind();
                    // A second build rather than a clone of the real book,
                    // and the two are the same thing here: `build_live_book`
                    // is a pure function of the company and the options, and
                    // the only option that differs is the depth multiplier.
                    // The arm's book IS the first one with more levels.
                    // The agents' orders go in the arm's book too, so the
                    // arm differs from the real settlement by the depth and
                    // nothing else. Their fills are discarded with the rest.
                    let (deep, _) = settle_price_through_book_with_orders(
                        &micro,
                        fair_value,
                        volume,
                        &SettleOptions {
                            depth_multiplier: f64::INFINITY,
                            ..options
                        },
                        resting,
                        buffer,
                    );
                    // The maker inventory this returns is DISCARDED, along
                    // with everything else about it except the price. An arm
                    // that fed its fills back would be a second market, and
                    // the next tick would no longer be the one that actually
                    // ran.
                    unbounded_price = breaker(deep.price);
                }
            }

            // Breaker #2 — the PRINT. See the module header for why this one
            // is the load-bearing clamp.
            //
            // The settled price is kept so the clamp can be reported apart
            // from the book. They pull opposite ways on every clamped row
            // and cancel exactly on most of them, so one column carrying
            // both says a halted name absorbed nothing.
            let settled_price = new_price;
            new_price = breaker(new_price);
            clamp_col[i] = mathx::log(new_price / settled_price);

            // Carry maker inventory forward. This is what makes impact
            // PERSIST: a large buy leaves the maker short, so it keeps quoting
            // higher until opposing flow lets it unwind.
            if settled.maker_inventory_delta != 0.0 && !auction {
                companies[idx].stock.maker_inventory = Some(
                    companies[idx].stock.maker_inventory.unwrap_or(0.0)
                        + settled.maker_inventory_delta,
                );
            }
        }

        // The decomposition, against the print the tape carries. `absorbed`
        // therefore holds the breaker as well as the book, which is the
        // honest reading of "what stood between the model price and the
        // print" -- on a halted name the breaker IS what absorbed the shock.
        let (shock, absorbed) = decompose(last_print, fair_value, new_price);
        shock_col[i] = shock;
        absorbed_col[i] = absorbed;
        if depth_arm {
            // A tick that never settled leaves the arm unrun, and the honest
            // reading of that is that unbounded depth would have printed the
            // same price. `mathx::log` of a ratio of one is zero, so the
            // share below is zero without a special case.
            let unbounded = if unbounded_price.is_nan() { new_price } else { unbounded_price };
            unbounded_col[i] = unbounded;
            let moved = mathx::log(new_price / last_print);
            share_col[i] = if unbounded == new_price {
                // The two prints coincide, so liquidity's share is zero
                // whatever the move was -- including a move of zero, where
                // the ratio below would be 0/0.
                0.0
            } else if moved == 0.0 {
                // The print did not move and the deeper book would have
                // moved it. There is no move to apportion, so the share is
                // undefined and says so. Dividing anyway gives an infinity
                // that survives into every mean taken over the column;
                // measured at 7 rows in 14,040 on a three-day run of twelve
                // names, so it is rare and it is real.
                f64::NAN
            } else {
                mathx::log(new_price / unbounded) / moved
            };
        }

        let stock = &mut companies[idx].stock;
        stock.previous_tick_price = Some(stock.price);
        stock.price = new_price;
        stock.high = mathx::max(stock.high, new_price);
        stock.low = mathx::min(stock.low, new_price);
        stock.volume += volume;
        stock.market_cap = new_price * stock.shares_outstanding;
    }

    TickOutcome {
        active_indices,
        fair_values: new_prices,
        fundamental_values: fundamentals,
        s_components,
        noise_parts,
        noise_own_scale2,
        volumes,
        factors: all_factors,
        shared_factors: shared,
        shock: shock_col,
        absorbed: absorbed_col,
        clamp: clamp_col,
        unbounded_print: unbounded_col,
        liquidity_share: share_col,
        agent_fills,
    }
}

/// The order-flow slot of a tick's components, with an agent fill's one-off
/// impact added when there is one. A branch, so a slot with none is the
/// shipped value to the bit.
fn with_fill_impact(slot: f64, fill: Option<&f64>) -> f64 {
    match fill {
        Some(&x) if x != 0.0 => slot + x,
        _ => slot,
    }
}

/// The log excess of the VIX over `fair_value_vix_knee`, floored at zero.
pub fn vix_excess(p: &ModelParams, vix: f64) -> f64 {
    if !(p.fair_value_vix_knee > 0.0) || !(vix > p.fair_value_vix_knee) {
        return 0.0;
    }
    mathx::log(vix / p.fair_value_vix_knee)
}

/// What a PINNED VIX moves the volatility feedback's exposure toward
/// (`pinned_vix_feedback`): its log excess over the knee, or, with
/// `pinned_vix_calm_knee` and `pinned_vix_calm_share` both set, the larger
/// of that and the calm line `share * ln(vix / calm_knee)`, so a pin below
/// the knee is priced too. The knee's excess, bit for bit, with either dial
/// at 0.0.
pub fn pinned_vix_excess(p: &ModelParams, vix: f64) -> f64 {
    let excess = vix_excess(p, vix);
    if p.pinned_vix_calm_share == 0.0 || !(p.pinned_vix_calm_knee > 0.0) || !(vix > p.pinned_vix_calm_knee) {
        return excess;
    }
    mathx::max(excess, p.pinned_vix_calm_share * mathx::log(vix / p.pinned_vix_calm_knee))
}

/// What the volatility-feedback discount reads (`fair_value_vix_discount`):
/// the VIX's log excess over the knee as it stands, or, with
/// `fair_value_vix_half_life` set, its smoothed level the close carries
/// (`EconomyState::vix_feedback`). 0.0 at a gain of 0.0, reading nothing.
pub fn vix_feedback_exposure(p: &ModelParams, economy: &EconomyState) -> f64 {
    if p.fair_value_vix_discount == 0.0 {
        return 0.0;
    }
    if p.fair_value_vix_half_life == 0.0 {
        vix_excess(p, economy.vix)
    } else {
        economy.vix_feedback
    }
}

/// A fair value scaled by the volatility-feedback discount,
/// `exp(-gain * beta * exposure)`: the value itself, bit for bit, at a gain
/// of 0.0 or an exposure of zero. A function of the VIX (or its smoothed
/// level) alone, so the discount goes as fear does.
pub fn with_vix_discount(p: &ModelParams, fv: f64, exposure: f64, beta: Option<f64>) -> f64 {
    if p.fair_value_vix_discount == 0.0 || !(exposure > 0.0) {
        fv
    } else {
        fv * mathx::exp(-p.fair_value_vix_discount * beta.unwrap_or(1.0) * exposure)
    }
}

/// A name's fair value on its PUBLISHED fundamentals, as the tick's phase 2
/// computes it for a name whose fair-value level is zero: the nominal
/// restatement, the buyback term at the current price, then the valuation.
/// Used by the stationary opening (`Engine::apply_opening`) to read the
/// day-zero premium the lazy opening would have adopted.
pub fn published_fair_value(
    p: &ModelParams,
    economy: &EconomyState,
    nominal_output_base: f64,
    elapsed_days: i64,
    company: &TickCompany,
) -> f64 {
    let nominal = nominal_scale(p, economy, nominal_output_base);
    let grown = if nominal == 1.0 {
        company.valuation()
    } else {
        scale_valuation(company.valuation(), nominal)
    };
    let buyback = buyback_factor(
        p, crate::market::dividends::buyback_share(p, company), grown.eps,
        company.stock.price, elapsed_days, company.stock.buyback_log_shares);
    let valuation = if buyback == 1.0 { grown } else { scale_valuation(grown, buyback) };
    let econ_view = EconomyValuationInputs {
        corporate_bond_yield: Some(economy.corporate_bond_yield),
        federal_funds_rate: economy.federal_funds_rate,
        qe_pe_boost: Some(economy.qe_pe_boost),
        qe_assets_ratio: Some(economy.qe_assets_ratio),
    };
    let fv = crate::fair_value::compute_fair_value_at(
        &valuation, &econ_view, p.fair_value_book_floor,
        p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity)
    .fair_value;
    let fv = with_vix_discount(p, fv, vix_feedback_exposure(p, economy), company.stock.beta);
    crate::market::dividends::with_accrual(fv, company)
}

/// A name's fair value as the tick's phase 2 computes it: the nominal
/// restatement, the name's own fair-value level, the buyback term at
/// `price`, then the valuation. The same operations in the same order, so
/// on the state a tick starts from it is the tick's `fundamental` to the
/// bit (`tests` below and `Engine::reprice_to_published_macro`, which reads
/// it before and after the close's macro step at one price and one day).
pub fn tick_fair_value(
    p: &ModelParams,
    economy: &EconomyState,
    nominal_output_base: f64,
    elapsed_days: i64,
    company: &TickCompany,
    price: f64,
) -> f64 {
    let nominal = nominal_scale(p, economy, nominal_output_base);
    let grown = if nominal == 1.0 {
        company.valuation()
    } else {
        scale_valuation(company.valuation(), nominal)
    };
    let v_level = company.stock.fair_value_offset.unwrap_or(0.0);
    let grown = if v_level == 0.0 {
        grown
    } else {
        scale_valuation(grown, mathx::exp(v_level))
    };
    let buyback = buyback_factor(
        p, crate::market::dividends::buyback_share(p, company), grown.eps, price, elapsed_days,
        company.stock.buyback_log_shares);
    let valuation = if buyback == 1.0 { grown } else { scale_valuation(grown, buyback) };
    let econ_view = EconomyValuationInputs {
        corporate_bond_yield: Some(economy.corporate_bond_yield),
        federal_funds_rate: economy.federal_funds_rate,
        qe_pe_boost: Some(economy.qe_pe_boost),
        qe_assets_ratio: Some(economy.qe_assets_ratio),
    };
    let fv = crate::fair_value::compute_fair_value_at(
        &valuation, &econ_view, p.fair_value_book_floor,
        p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity)
    .fair_value;
    let fv = with_vix_discount(p, fv, vix_feedback_exposure(p, economy), company.stock.beta);
    crate::market::dividends::with_accrual(fv, company)
}

/// The opening print of a name whose mispricing stands at `s`: the price
/// `P = fv(P) exp(s)`, fair value read as the tick reads it
/// ([`tick_fair_value`]). Fair value reads the price through the buyback
/// term (the yield is earnings over price), so the first step, at the last
/// price, is exact only with `buyback_payout_share` at 0.0; with it on the
/// fixed point is iterated as the close's re-mark iterates it
/// (`Engine::reprice_to_published_macro`), a contraction because the term's
/// elasticity is the buyback yield times the years elapsed, well under one
/// (and capped by `buyback_yield_cap`). Stops when a step moves nothing, or
/// at sixteen, and takes no draw.
pub fn opening_print(
    p: &ModelParams,
    economy: &EconomyState,
    nominal_output_base: f64,
    elapsed_days: i64,
    company: &TickCompany,
    s: f64,
) -> f64 {
    let clamp = |x: f64| mathx::min(mathx::max(x, 0.01), p.price_hard_cap);
    let level = mathx::exp(s);
    let last = company.stock.price;
    let mut price = clamp(
        tick_fair_value(p, economy, nominal_output_base, elapsed_days, company, last) * level);
    if p.buyback_payout_share != 0.0 {
        for _ in 0..16 {
            let fv = tick_fair_value(p, economy, nominal_output_base, elapsed_days, company, price);
            let next = clamp(fv * level);
            if next == price {
                break;
            }
            price = next;
        }
    }
    price
}

pub fn clamp_s(params: &ModelParams, s: f64) -> f64 {
    // `Math.max(-CAP, Math.min(CAP, s))` — the min/max spelling, not the
    // ternary, matching the source.
    mathx::max(-params.mispricing_cap, mathx::min(params.mispricing_cap, s))
}

/// Serves settlement's four pre-drawn uniforms under
/// [`SettleDrawPolicy::FourAlways`].
///
/// Overrunning the budget panics rather than wrapping or re-drawing: the
/// settle's four-draw ceiling is a hard contract
/// (`microstructure::settle_price_through_book`), and a fifth request means
/// that contract broke — silently serving anything would convert a schedule
/// bug into a plausible-looking different market. `next_normal` panics for
/// the same reason: settlement draws uniforms only, and a normal request
/// here is a routing error, not a need.
struct PredrawnUniforms {
    draws: [f64; 4],
    at: usize,
}

impl PredrawnUniforms {
    fn new(draws: [f64; 4]) -> Self {
        Self { draws, at: 0 }
    }

    /// Serve the same four uniforms again, from the start.
    ///
    /// This is what makes the depth counterfactual free: the second
    /// settlement is fed the numbers the first one was fed, so the shared
    /// stream is not touched and the tick's draw count is what it was. The
    /// buffer is per-company and per-tick, so a rewind cannot reach any
    /// settlement but the one it belongs to.
    fn rewind(&mut self) {
        self.at = 0;
    }
}

impl Rng for PredrawnUniforms {
    fn next_f64(&mut self) -> f64 {
        let value = self.draws[self.at];
        self.at += 1;
        value
    }
    fn next_normal(&mut self) -> f64 {
        unreachable!("settlement draws uniforms only; a normal request here is a routing bug")
    }
}

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

    #[test]
    fn the_excess_share_is_a_floor_under_the_share_above_the_ceiling() {
        let mut p = crate::params::PT_V20;
        let base = p.fair_value_market_vol_cap * p.market_factor_sigma;
        // Off: the ceiling as it stood, bit for bit, above and below it.
        assert_eq!(p.fair_value_market_excess_share, 0.0);
        assert_eq!(market_permanent_share(&p, 0.5 * base, 1.0), p.fair_value_market_share);
        assert_eq!(market_permanent_share(&p, 4.0 * base, 1.0), p.fair_value_market_share / 4.0);
        // On: below the ceiling nothing moves; above it, capped + e (share - capped).
        p.fair_value_market_excess_share = 0.5;
        assert_eq!(market_permanent_share(&p, 0.5 * base, 1.0), p.fair_value_market_share);
        let capped = p.fair_value_market_share / 4.0;
        let want = capped + 0.5 * (p.fair_value_market_share - capped);
        assert!((market_permanent_share(&p, 4.0 * base, 1.0) - want).abs() < 1e-15);
        // However turbulent the market, at least e of the share stays.
        assert!(market_permanent_share(&p, 1e6 * base, 1.0) >= 0.5 * p.fair_value_market_share);
        // At 1.0 it is no ceiling.
        p.fair_value_market_excess_share = 1.0;
        assert_eq!(market_permanent_share(&p, 4.0 * base, 1.0), p.fair_value_market_share);
    }

    #[test]
    fn buyback_accrual_is_inert_off_and_does_not_read_the_price_on() {
        let mut p = crate::params::PT_V1;
        p.buyback_payout_share = 0.75;
        // Off: the factor is the term that stood, and the step is zero.
        assert_eq!(buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, Some(0.3)),
                   buyback_scale(&p, Some(2.0), 40.0, 500));
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, 0.0), 0.0);
        // On: exp(L), whatever the price and the day.
        p.buyback_accrual = 1.0;
        let a = buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, Some(0.3));
        let b = buyback_factor(&p, p.buyback_payout_share, Some(2.0), 20.0, 9000, Some(0.3));
        assert_eq!(a, b);
        assert_eq!(a, mathx::exp(0.3));
        assert_eq!(buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, None), 1.0);
    }

    #[test]
    fn buyback_accrual_step_is_the_capped_yield_on_the_grown_earnings() {
        let mut p = crate::params::PT_V1;
        p.buyback_payout_share = 0.5;
        p.buyback_accrual = 1.0;
        let l = 0.2;
        let want = 0.5 * 2.0 * mathx::exp(l) / 40.0 / MARKET_DAYS_PER_YEAR;
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), want);
        // The cap bounds one session's increment.
        p.buyback_yield_cap = 0.01;
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), 0.01 / MARKET_DAYS_PER_YEAR);
        // A loss-maker, a missing figure and a bad price accrue nothing.
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(-1.0), 40.0, l), 0.0);
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, None, 40.0, l), 0.0);
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 0.0, l), 0.0);
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), f64::NAN, l), 0.0);
        // No payouts, nothing to accrue.
        p.buyback_payout_share = 0.0;
        assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), 0.0);
    }

    #[test]
    fn s_phi_tick_matches_the_recorded_v8_bits() {
        assert_eq!(S_PHI_TICK.to_bits(), 0x3FEF_FFC1_E138_5E9E);
    }

    #[test]
    fn market_factor_sigma_is_the_2026_08_sweep_calibration() {
        // Not a tautology: a gate. This constant is the measured answer of
        // `tools/calibration/sweep_market_factor_vol.py` — the BASELINE of
        // the factor's variance process, chosen jointly with
        // `IDIO_SIGMA_SCALE` and the `factor_vol.rs` shape; the doc
        // comment on it records what the vector bought (correlation and
        // kurtosis in band together). Moving it by hand un-measures it;
        // whoever fails this test should re-run the sweep (one command)
        // and update the constant, its documentation and this pin
        // together. The sweep must also be re-run after any change that
        // re-orders RNG draws, because that re-rolls every statistic the
        // value rests on.
        assert_eq!(MARKET_FACTOR_SIGMA, 0.016);
    }

    #[test]
    fn s_phi_tick_compounds_to_the_daily_phi_across_a_session() {
        // 390 ticks of the per-tick decay must reproduce one day of the daily
        // decay. That relationship is the whole reason the constant exists.
        let mut compounded = 1.0f64;
        for _ in 0..390 {
            compounded *= S_PHI_TICK;
        }
        assert!(
            (compounded - crate::mispricing::MISPRICING_PHI).abs() < 1e-12,
            "390 ticks compounded to {compounded}, daily phi is {}",
            crate::mispricing::MISPRICING_PHI
        );
    }

    #[test]
    fn universe_memory_holds_correlation_up_after_the_shock_passes() {
        // The property this state exists for. Real correlation spikes with
        // a panic and unwinds over weeks; without memory this model's blend
        // is a lookup on today's VIX, so the cross-section re-decouples in
        // the same tick the VIX falls back. Here: shock the memory, then
        // ask what the blend does on a CALM day.
        let base = crate::params::PT_V1;
        let mut remembering = base.clone();
        remembering.universe_stress_weight = 1.0;
        remembering.universe_stress_decay = 0.97;

        let calm_vix = crate::economy::CRISIS_VIX_THRESHOLD - 5.0;
        let carried = 8.0; // VIX points of remembered stress

        let forgetful = blend_for(&base, calm_vix, carried);
        let remembers = blend_for(&remembering, calm_vix, carried);

        assert_eq!(forgetful, 0.0, "without memory a calm day decouples");
        assert!(remembers > 0.0,
                "with memory the blend survives the day the panic ended");
        assert!(remembers <= base.crisis_blend_cap);
    }

    #[test]
    fn universe_memory_is_inert_at_its_legacy_weight() {
        // Bit-identity for every preset before pt-v4: at weight zero the
        // blend must be exactly the today's-VIX lookup, whatever the
        // universe happens to be remembering.
        let base = crate::params::PT_V1;
        assert_eq!(base.universe_stress_weight, 0.0);
        for vix in [5.0, 15.0, 22.0, 30.0, 65.0] {
            for carried in [0.0, 3.0, 25.0] {
                assert_eq!(
                    blend_for(&base, vix, carried),
                    blend_for(&base, vix, 0.0),
                    "vix {vix} carried {carried}"
                );
            }
        }
    }

    /// The blend as `simulate_market_tick` computes it, extracted so the
    /// two tests above can ask about it without driving a whole market.
    fn blend_for(p: &crate::params::ModelParams, vix: f64, carried: f64) -> f64 {
        // The PARAMETER, as `simulate_market_tick` reads it. This helper takes
        // `p` and then read the constant, so it would have stopped mirroring
        // production the moment a test moved the threshold.
        let threshold = p.crisis_vix_threshold;
        let instant = if vix > threshold { vix - threshold } else { 0.0 };
        let effective = if p.universe_stress_weight == 0.0 {
            instant
        } else {
            instant + p.universe_stress_weight * mathx::max(carried - instant, 0.0)
        };
        if effective > 0.0 {
            mathx::min(p.crisis_blend_cap, effective / p.crisis_blend_ramp)
        } else {
            0.0
        }
    }

    /// The economy the scale is read off, at a stated nominal output.
    fn economy_at(gdp: f64, cpi: f64) -> EconomyState {
        let mut e = crate::economy::create_initial_economy_state(
            &crate::economy::InitialEconomyOptions::default());
        e.gdp = gdp;
        e.cpi = cpi;
        e
    }

    fn with_dial(value: f64) -> crate::params::ModelParams {
        let mut p = crate::params::PT_V16;
        p.earnings_nominal_growth = value;
        p
    }

    #[test]
    fn the_scale_is_one_wherever_the_dial_is_off() {
        // The branch, not the arithmetic: an output ten times the base
        // still returns a literal 1.0, so no preset before pt-v18 reaches
        // a multiply at all.
        let p = with_dial(0.0);
        for (gdp, cpi) in [(25000.0, 100.0), (250000.0, 100.0),
                           (25000.0, 1000.0), (0.0, 100.0)] {
            let e = economy_at(gdp, cpi);
            assert_eq!(nominal_scale(&p, &e, 2_500_000.0), 1.0);
        }
    }

    #[test]
    fn the_scale_is_the_output_ratio_when_the_dial_is_full() {
        let p = with_dial(1.0);
        let base = 2_500_000.0;
        assert_eq!(nominal_scale(&p, &economy_at(25000.0, 100.0), base), 1.0);
        assert_eq!(nominal_scale(&p, &economy_at(50000.0, 100.0), base), 2.0);
        assert_eq!(nominal_scale(&p, &economy_at(25000.0, 200.0), base), 2.0);
        // Down as well as up, which is what a contraction reaches and what
        // a flat premium could not do.
        assert_eq!(nominal_scale(&p, &economy_at(20000.0, 100.0), base), 0.8);
    }

    #[test]
    fn a_share_of_the_dial_is_a_share_of_the_level() {
        // Linear in the dial, so half the dial adds half of what the whole
        // of it adds. Stated on the level rather than on the log, which is
        // the shape every other dial in this era has.
        let base = 2_500_000.0;
        let e = economy_at(50000.0, 100.0);
        assert_eq!(nominal_scale(&with_dial(0.5), &e, base), 1.5);
        assert_eq!(nominal_scale(&with_dial(0.25), &e, base), 1.25);
    }

    #[test]
    fn a_base_that_is_not_a_positive_number_gives_one() {
        // Nothing the engine builds reaches this, because `gdp` and `cpi`
        // are levels the economy never takes to zero. A caller building
        // `TickInputs` by hand can, and a NaN entering the valuation would
        // freeze every book downstream with nothing to say where it came
        // from.
        let p = with_dial(1.0);
        let e = economy_at(25000.0, 100.0);
        for base in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            assert_eq!(nominal_scale(&p, &e, base), 1.0);
        }
    }

    #[test]
    fn the_scaled_valuation_moves_both_fundamentals_and_nothing_else() {
        let company = CompanyValuationInputs {
            sector_avg_pe: Some(18.0),
            eps: Some(4.0),
            book_value_per_share: Some(20.0),
            revenue_growth: Some(0.05),
        };
        let scaled = scale_valuation(company, 1.25);
        assert_eq!(scaled.eps, Some(5.0));
        assert_eq!(scaled.book_value_per_share, Some(25.0));
        // A rate and a multiple, both already nominal-neutral.
        assert_eq!(scaled.revenue_growth, Some(0.05));
        assert_eq!(scaled.sector_avg_pe, Some(18.0));
        // An absent fundamental stays absent rather than becoming zero,
        // which is the difference between a company the valuation prices
        // off book and one it prices at nothing.
        let empty = scale_valuation(CompanyValuationInputs {
            sector_avg_pe: None, eps: None,
            book_value_per_share: None, revenue_growth: None,
        }, 1.25);
        assert_eq!(empty.eps, None);
        assert_eq!(empty.book_value_per_share, None);
    }
}