behaviorsim-rs 0.7.0

Domain-agnostic specification for modeling individual psychology and social dynamics
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
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
//! State query API for timestamp-based state access.
//!
//! This module provides `EntityQueryHandle` for querying entity state at
//! any timestamp, and `ComputedState` as the result type.

use crate::context::apply_context_effects;
use crate::entity::Entity;
use crate::enums::{AlertTrigger, Direction, Emotion, HexacoPath, LifeDomain, LifeStage, StatePath};
use crate::memory::{
    apply_memory_consolidation, create_memory_from_event, MemoryEntry, MemoryLayer, MemoryLayers,
};
use crate::processor::{
    advance_state, apply_developmental_effects, apply_interpreted_event_to_state,
    compute_trust_modulation_factor, interpret_event, regress_state,
    reverse_interpreted_event_from_state, InterpretedEvent,
};
use crate::relationship::{TrustContext, TrustDecision};
use crate::simulation::{RegressionQuality, Simulation, TimestampedEvent};
use crate::state::{
    apply_formative_modifiers, effective_base_at, BaseShiftRecord, IndividualState,
    StateInterpreter,
};
use crate::types::{Alert, Duration, EntityId, Timestamp};
use std::collections::HashMap;

/// A handle for querying entity state at different timestamps.
///
/// This handle provides the `state_at()` method, which is the primary
/// consumer API for getting entity state at any point in time.
///
pub struct EntityQueryHandle<'a> {
    simulation: &'a Simulation,
    entity_id: EntityId,
}

impl<'a> EntityQueryHandle<'a> {
    /// Creates a new query handle.
    pub(crate) fn new(simulation: &'a Simulation, entity_id: EntityId) -> Self {
        EntityQueryHandle {
            simulation,
            entity_id,
        }
    }

    /// Returns the entity ID.
    #[must_use]
    pub fn entity_id(&self) -> &EntityId {
        &self.entity_id
    }

    /// Returns the anchor timestamp for this entity.
    #[must_use]
    pub fn anchor_timestamp(&self) -> Option<Timestamp> {
        self.simulation
            .get_anchored_entity(&self.entity_id)
            .map(|a| a.anchor_timestamp())
    }

    /// Computes the entity's state at the given timestamp.
    ///
    /// This is the primary consumer API. It computes state by:
    /// 1. Starting from the anchor state
    /// 2. Applying decay forward or reversing backward
    /// 3. Applying events in the time range
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The time at which to compute state
    ///
    /// # Returns
    ///
    /// The computed state, or `None` if the entity doesn't exist.
    ///
    #[must_use]
    pub fn state_at(&self, timestamp: Timestamp) -> ComputedState {
        let anchored = self
            .simulation
            .get_anchored_entity(&self.entity_id)
            .expect("EntityQueryHandle created for non-existent entity - use Simulation::entity() to check existence");
        let anchor_timestamp = anchored.anchor_timestamp();
        let entity = anchored.entity();

        // Clone the individual state as our starting point
        let mut state = entity.individual_state().clone();
        let species = entity.species().clone();

        // Short-circuit: if querying at anchor timestamp, return anchor state
        if timestamp == anchor_timestamp {
            let age_at_timestamp = self.compute_age_at_timestamp(entity, timestamp);
            let life_stage =
                LifeStage::from_age_years_for_species(&species, age_at_timestamp.as_years() as f64);

            let pad_bounds = entity.context().compute_pad_bounds();
            state
                .mood_mut()
                .valence_mut()
                .set_bounds(pad_bounds.valence_min, pad_bounds.valence_max);
            state
                .mood_mut()
                .arousal_mut()
                .set_bounds(pad_bounds.arousal_min, pad_bounds.arousal_max);
            state
                .mood_mut()
                .dominance_mut()
                .set_bounds(pad_bounds.dominance_min, pad_bounds.dominance_max);

            let interpreter = StateInterpreter::from_state(&state);
            return ComputedState {
                individual_state: state,
                age_at_timestamp,
                life_stage,
                regression_quality: RegressionQuality::Exact,
                alerts: std::cell::OnceCell::new(),
                interpretations: interpreter.interpretations().clone(),
                summary: interpreter.summary().to_string(),
                delta_summary: None,
            };
        }

        // Determine direction: forward or backward
        let is_forward = timestamp > anchor_timestamp;

        // Get events targeting this entity in the relevant time range
        // Forward: (anchor, target] - exclude anchor, include target
        // Backward: [target, anchor) - include target, exclude anchor
        let events = self.get_sorted_events_for_range(anchor_timestamp, timestamp, is_forward);

        // Compute regression quality based on events
        let regression_quality = if is_forward {
            RegressionQuality::Exact
        } else {
            self.determine_regression_quality(&events)
        };

        // Interpret events once using the anchor entity's personality
        // Personality (HEXACO) is stable, so using anchor state is appropriate
        let interpreted_events: Vec<InterpretedEvent> = events
            .iter()
            .map(|te| interpret_event(te.event(), entity))
            .collect();

        // Collect base shift records from events that have formative shifts
        // These represent permanent personality changes from significant life events
        let base_shift_records: Vec<BaseShiftRecord> =
            collect_base_shift_records(&events, entity, timestamp, is_forward);

        // Helper to compute age at a given timestamp for developmental effects
        let compute_age_at = |ts: Timestamp| -> Duration {
            if let Some(birth_date) = entity.birth_date() {
                if ts >= birth_date {
                    ts - birth_date
                } else {
                    Duration::zero()
                }
            } else {
                // Without birth_date, age is constant at anchor age
                entity.age()
            }
        };

        // Computed memories from events (only for forward projection)
        let mut computed_memories = MemoryLayers::new();

        if is_forward {
            // Forward: use cursor pattern to track current time position
            // This avoids compounding decay by advancing in deltas between events
            let mut cursor = anchor_timestamp;

            for (te, interpreted) in events.iter().zip(interpreted_events.iter()) {
                // Advance from cursor to this event's timestamp
                let delta = te.timestamp() - cursor;
                state = advance_state(state, delta);

                // Apply developmental effects to scale event impact
                // Compute entity's age at the time of this event
                let age_at_event = compute_age_at(te.timestamp());
                let age_days = age_at_event.as_days();
                let dev_factor =
                    apply_developmental_effects(entity, te.event(), 1.0, age_days, te.timestamp());

                // Apply trust modulation for interpersonal events
                // If the event has a source with whom we have a relationship, prior trust
                // amplifies the impact (betrayal from trusted person hurts more)
                let trustor_propensity = state.disposition().trustor_propensity_effective();
                let trust_factor = self.compute_trust_factor_for_event(
                    entity,
                    te.event(),
                    te.timestamp(),
                    trustor_propensity,
                );

                // Combine developmental and trust modulation factors
                let combined_factor = dev_factor * trust_factor;

                // Scale the interpreted event by the combined factor
                let scaled_interpreted = interpreted.scaled_by(combined_factor);

                // Apply the scaled interpreted event deltas
                state = apply_interpreted_event_to_state(state, &scaled_interpreted);

                // Create memory from this event (AFTER state is updated to capture
                // the emotional context at encoding time)
                let memory = create_memory_from_event(
                    &scaled_interpreted,
                    &state,
                    age_at_event,
                    Some(&self.entity_id),
                );
                computed_memories.add(MemoryLayer::Immediate, memory);

                // Move cursor forward
                cursor = te.timestamp();
            }

            // Advance remaining time from cursor to target timestamp
            let remaining = timestamp - cursor;
            state = advance_state(state, remaining);
        } else {
            // Backward: use cursor pattern in reverse
            // Start at anchor and work backward through events in reverse order
            let mut cursor = anchor_timestamp;

            // Events are sorted chronologically, so iterate in reverse
            // Use indices to access both events and interpreted events in sync
            for i in (0..events.len()).rev() {
                let te = &events[i];
                let interpreted = &interpreted_events[i];

                // Regress from cursor to this event's timestamp
                let delta = cursor - te.timestamp();
                state = regress_state(state, delta);

                // Apply developmental effects to scale event impact for reversal
                // Compute entity's age at the time of this event
                let age_at_event = compute_age_at(te.timestamp());
                let age_days = age_at_event.as_days();
                let dev_factor =
                    apply_developmental_effects(entity, te.event(), 1.0, age_days, te.timestamp());

                // Apply trust modulation for interpersonal events (same as forward)
                let trustor_propensity = state.disposition().trustor_propensity_effective();
                let trust_factor = self.compute_trust_factor_for_event(
                    entity,
                    te.event(),
                    te.timestamp(),
                    trustor_propensity,
                );

                // Combine developmental and trust modulation factors
                let combined_factor = dev_factor * trust_factor;

                // Scale the interpreted event by the combined factor
                let scaled_interpreted = interpreted.scaled_by(combined_factor);

                // Reverse the scaled interpreted event using its actual deltas
                state = reverse_interpreted_event_from_state(state, &scaled_interpreted);
                // Move cursor backward
                cursor = te.timestamp();
            }

            // Regress remaining time from cursor to target timestamp
            let remaining = cursor - timestamp;
            state = regress_state(state, remaining);
        }

        // Apply hook points AFTER decay and events, in order:
        // 1. Context effects (ecological systems)
        // 2. Memory consolidation (salience decay, layer transfer)
        //
        // Developmental effects (plasticity, sensitive periods) are applied above
        // during event processing via apply_developmental_effects().
        let total_duration = if is_forward {
            timestamp - anchor_timestamp
        } else {
            anchor_timestamp - timestamp
        };
        let relationship_quality = estimate_relationship_quality(entity);
        let age_at_timestamp = self.compute_age_at_timestamp(entity, timestamp);
        let life_stage =
            LifeStage::from_age_years_for_species(&species, age_at_timestamp.as_years() as f64);
        state = apply_context_effects(
            state,
            entity.context(),
            relationship_quality,
            total_duration,
            life_stage,
            age_at_timestamp.as_years() as f64,
            timestamp,
        );

        // Merge anchor memories with computed memories for consolidation
        // For forward projection, we combine entity's anchor memories with
        // memories computed from events processed in this query.
        // For backward regression, we only use anchor memories (events being
        // reversed haven't happened yet at the query timestamp).
        let merged_memories = if is_forward {
            merge_memory_layers(entity.memories(), &computed_memories)
        } else {
            entity.memories().clone()
        };
        state = apply_memory_consolidation(state, &merged_memories, total_duration);

        // Apply formative base shifts to HEXACO personality traits
        // This computes effective base values for each trait based on accumulated shifts
        state = apply_base_shifts_to_state(state, &base_shift_records, timestamp);

        // Apply context-dependent PAD bounds for emotional expression
        let pad_bounds = entity.context().compute_pad_bounds();
        state
            .mood_mut()
            .valence_mut()
            .set_bounds(pad_bounds.valence_min, pad_bounds.valence_max);
        state
            .mood_mut()
            .arousal_mut()
            .set_bounds(pad_bounds.arousal_min, pad_bounds.arousal_max);
        state
            .mood_mut()
            .dominance_mut()
            .set_bounds(pad_bounds.dominance_min, pad_bounds.dominance_max);

        let baseline_state = entity.individual_state();
        let interpreter = StateInterpreter::from_state_with_baseline(&state, baseline_state);
        ComputedState {
            individual_state: state,
            age_at_timestamp,
            life_stage,
            regression_quality,
            alerts: std::cell::OnceCell::new(),
            interpretations: interpreter.interpretations().clone(),
            summary: interpreter.summary().to_string(),
            delta_summary: interpreter.delta_summary().map(|s| s.to_string()),
        }
    }

    /// Gets events in the time range, sorted chronologically.
    ///
    /// # Boundary Rules
    ///
    /// - Forward projection: (anchor, target] - excludes anchor, includes target
    /// - Backward regression: (target, anchor] - excludes target, includes anchor
    ///
    /// The anchor state already reflects events that occurred at anchor time,
    /// so for forward projection we exclude anchor. For backward regression,
    /// we include anchor events (which need to be reversed) but exclude target
    /// events (which should not exist in the pre-event state).
    fn get_sorted_events_for_range(
        &self,
        anchor: Timestamp,
        target: Timestamp,
        is_forward: bool,
    ) -> Vec<&'a TimestampedEvent> {
        let mut events: Vec<_> = self
            .simulation
            .events_for(&self.entity_id)
            .into_iter()
            .filter(|te| {
                let ts = te.timestamp();
                if is_forward {
                    // Forward: (anchor, target] - after anchor, up to and including target
                    ts > anchor && ts <= target
                } else {
                    // Backward: (target, anchor] - after target, up to and including anchor
                    ts > target && ts <= anchor
                }
            })
            .collect();

        events.sort_by_key(|te| te.timestamp());
        events
    }

    /// Determines regression quality based on events.
    ///
    /// Regression is approximate when:
    /// - Trauma events are present (AC increases are not reversible)
    fn determine_regression_quality(&self, events: &[&TimestampedEvent]) -> RegressionQuality {
        for te in events {
            let event = te.event();
            let spec = event.spec();

            // Trauma events (AC > 0) have non-reversible Acquired Capability increases
            if spec.impact.acquired_capability > 0.0 {
                return RegressionQuality::Approximate;
            }

        }

        RegressionQuality::Exact
    }

    /// Computes the entity's age at a given timestamp.
    ///
    /// If the entity has a birth_date set, computes age as:
    /// `timestamp - birth_date`
    ///
    /// If no birth_date is set, returns the anchor age (constant) since we cannot
    /// compute age progression without knowing when the entity was born.
    fn compute_age_at_timestamp(
        &self,
        entity: &crate::entity::Entity,
        timestamp: Timestamp,
    ) -> Duration {
        // If entity has a birth date, compute age from that directly
        if let Some(birth_date) = entity.birth_date() {
            if timestamp >= birth_date {
                return timestamp - birth_date;
            } else {
                // Before birth - return zero
                return Duration::zero();
            }
        }

        // Fallback: without birth_date, age remains constant at anchor age.
        // We cannot compute age progression without knowing when the entity was born.
        entity.age()
    }

    /// Computes the trust modulation factor for an interpersonal event.
    ///
    /// If the event has a source with whom the target entity has a relationship,
    /// the prior trust level modulates the event's psychological impact.
    ///
    /// Per Mayer's trust model:
    /// - High trust + betrayal = amplified harm (vulnerability was exploited)
    /// - Low trust + betrayal = expected/buffered (wasn't vulnerable to them)
    ///
    /// # Arguments
    ///
    /// * `event` - The event to check for trust modulation
    /// * `event_timestamp` - When the event occurred (for relationship lookup)
    ///
    /// # Returns
    ///
    /// A scaling factor for the event's impact (1.0 = no modulation)
    fn compute_trust_factor_for_event(
        &self,
        entity: &Entity,
        event: &crate::event::Event,
        event_timestamp: Timestamp,
        trustor_propensity: f32,
    ) -> f64 {
        // No source = no interpersonal trust modulation
        let Some(source_id) = event.source() else {
            return 1.0;
        };

        // Find relationship between target (self.entity_id) and source
        let relationships = self.simulation.relationships_for(&self.entity_id);
        let relevant_rel = relationships.iter().find(|tr| {
            // Relationship must exist before the event occurred
            tr.formed_timestamp() <= event_timestamp && tr.involves(source_id)
        });

        let Some(timestamped_rel) = relevant_rel else {
            // No relationship with source = stranger, no modulation
            return 1.0;
        };

        // Determine direction: target is trustor, source is trustee
        let direction = if timestamped_rel.entity_a() == &self.entity_id {
            Direction::AToB
        } else {
            Direction::BToA
        };

        let context = self.build_trust_context(entity, event);
        let life_domain = event
            .payload()
            .life_domain()
            .unwrap_or(LifeDomain::Relationship);
        compute_trust_modulation_factor(
            event,
            Some(timestamped_rel.relationship()),
            direction,
            trustor_propensity,
            &context,
            life_domain,
        )
    }

    fn build_trust_context(&self, entity: &Entity, event: &crate::event::Event) -> TrustContext {
        let ecology = entity.context();
        let macrosystem = ecology.macrosystem();
        let exosystem = ecology.exosystem();
        let historical = ecology.chronosystem().historical_period();

        let mut social_norms = 1.0 - macrosystem.cultural_stress;
        let institutional_safeguards = macrosystem.institutional_structure.rule_of_law
            * (1.0 - macrosystem.institutional_structure.corruption_level);
        let institutional_support = exosystem.institutional_support;
        let cultural_expectations = (historical.institutional_trust * 0.6
            + (1.0 - macrosystem.cultural_stress) * 0.4)
            .clamp(0.0, 1.0);
        let mut time_pressure = 0.5;

        if let Some(context_id) = event.microsystem_context() {
            if let Some(micro) = ecology.get_microsystem(context_id) {
                let warmth = micro.warmth();
                let hostility = micro.hostility();
                social_norms += (warmth - hostility) * 0.2;
                time_pressure = ((micro.interaction_frequency() + micro.interaction_complexity())
                    / 2.0)
                    .clamp(0.0, 1.0);
            }
        }

        TrustContext::new()
            .with_social_norms(social_norms.clamp(0.0, 1.0) as f32)
            .with_institutional_safeguards(institutional_safeguards.clamp(0.0, 1.0) as f32)
            .with_time_pressure(time_pressure as f32)
            .with_institutional_support(institutional_support.clamp(0.0, 1.0) as f32)
            .with_cultural_expectations(cultural_expectations as f32)
    }

    /// Computes the trust decision for this entity (trustor) toward a trustee at a timestamp.
    ///
    /// This wires together the trustor's dispositional propensity at the time,
    /// the current relationship state, the provided situational context,
    /// and the relevant life domain for competence.
    /// `stakes` optionally scales perceived risk based on consequence severity.
    #[must_use]
    pub fn trust_decision_for(
        &self,
        trustee: &EntityId,
        timestamp: Timestamp,
        context: &TrustContext,
        life_domain: LifeDomain,
        stakes: Option<crate::enums::ActionStakes>,
    ) -> Option<TrustDecision> {
        let relationships = self.simulation.relationships_for(&self.entity_id);
        let relevant = relationships
            .iter()
            .find(|tr| tr.formed_timestamp() <= timestamp && tr.involves(trustee))?;

        let direction = if relevant.entity_a() == &self.entity_id {
            Direction::AToB
        } else {
            Direction::BToA
        };

        let trustor_propensity = self
            .state_at(timestamp)
            .individual_state()
            .disposition()
            .trustor_propensity_effective();

        Some(
            relevant
                .relationship()
                .compute_trust_decision(
                    direction,
                    trustor_propensity,
                    context,
                    life_domain,
                    stakes,
                ),
        )
    }

    /// Returns memories that exist at the given timestamp.
    ///
    /// A memory "exists" at a timestamp if it was formed before or at that time.
    /// This method returns all memories from the entity's memory layers that
    /// were formed at or before the specified timestamp.
    ///
    /// # Arguments
    ///
    /// * `timestamp` - The time at which to query existing memories
    ///
    /// # Returns
    ///
    /// A vector of cloned memory entries that exist at the timestamp.
    /// Returns an empty vector if the entity doesn't exist.
    ///
    #[must_use]
    pub fn memories_at(&self, timestamp: Timestamp) -> Vec<MemoryEntry> {
        let Some(anchored) = self.simulation.get_anchored_entity(&self.entity_id) else {
            return Vec::new();
        };

        let entity = anchored.entity();
        let anchor_timestamp = anchored.anchor_timestamp();
        let anchor_age = entity.age();

        // Compute the entity's age at the query timestamp
        let age_at_timestamp = if timestamp >= anchor_timestamp {
            let elapsed = timestamp - anchor_timestamp;
            anchor_age + elapsed
        } else {
            let elapsed = anchor_timestamp - timestamp;
            if elapsed < anchor_age {
                anchor_age - elapsed
            } else {
                Duration::zero()
            }
        };

        // Get all memories and filter by those formed at or before the computed age
        // MemoryEntry.timestamp() returns the entity's age when the memory was formed
        entity
            .memories()
            .all_memories()
            .filter(|memory: &&MemoryEntry| memory.timestamp() <= age_at_timestamp)
            .cloned()
            .collect()
    }
}

fn estimate_relationship_quality(entity: &Entity) -> f64 {
    let attached_count = entity
        .relationship_slots()
        .iter()
        .filter(|slot| slot.is_attached())
        .count();

    if attached_count > 0 {
        0.5 + 0.1 * (attached_count as f64).min(5.0)
    } else {
        0.3
    }
}

/// Merges two memory layer structures into a new combined structure.
///
/// This is used to combine anchor memories (from entity creation) with
/// computed memories (from events processed during state_at). All memories
/// from both sources are copied into the new structure, preserving their
/// layer assignments.
fn merge_memory_layers(anchor: &MemoryLayers, computed: &MemoryLayers) -> MemoryLayers {
    let mut merged = MemoryLayers::new();

    // Copy all anchor memories
    for memory in anchor.immediate() {
        merged.add(MemoryLayer::Immediate, memory.clone());
    }
    for memory in anchor.short_term() {
        merged.add(MemoryLayer::ShortTerm, memory.clone());
    }
    for memory in anchor.long_term() {
        merged.add(MemoryLayer::LongTerm, memory.clone());
    }
    for memory in anchor.legacy() {
        merged.add(MemoryLayer::Legacy, memory.clone());
    }

    // Copy all computed memories
    for memory in computed.immediate() {
        merged.add(MemoryLayer::Immediate, memory.clone());
    }
    for memory in computed.short_term() {
        merged.add(MemoryLayer::ShortTerm, memory.clone());
    }
    for memory in computed.long_term() {
        merged.add(MemoryLayer::LongTerm, memory.clone());
    }
    for memory in computed.legacy() {
        merged.add(MemoryLayer::Legacy, memory.clone());
    }

    merged
}

/// The computed state of an entity at a specific timestamp.
///
/// This is the result of calling `state_at()` on an `EntityQueryHandle`.
/// It contains the computed individual state, age, life stage, and
/// regression quality indicator.
///
#[derive(Debug)]
pub struct ComputedState {
    /// The computed individual state.
    pub individual_state: IndividualState,
    /// The entity's age at the queried timestamp.
    pub age_at_timestamp: Duration,
    /// The entity's life stage at the queried timestamp.
    pub life_stage: LifeStage,
    /// Quality indicator for backward regression.
    regression_quality: RegressionQuality,
    /// Cached alerts (lazy computed with interior mutability).
    alerts: std::cell::OnceCell<Vec<Alert>>,
    /// Human-readable interpretations of psychological dimensions.
    pub interpretations: HashMap<String, String>,
    /// Condensed plain-English summary paragraph.
    pub summary: String,
    /// Delta emphasis summary showing changes from baseline.
    pub delta_summary: Option<String>,
}

impl ComputedState {
    /// Returns a reference to the individual state.
    #[must_use]
    pub fn individual_state(&self) -> &IndividualState {
        &self.individual_state
    }

    /// Returns graded emotion membership based on the current PAD state.
    #[must_use]
    pub fn emotion_membership(&self) -> HashMap<Emotion, f64> {
        self.individual_state.mood().emotion_membership()
    }

    /// Returns the age at the queried timestamp.
    #[must_use]
    pub fn age_at_timestamp(&self) -> Duration {
        self.age_at_timestamp
    }

    /// Returns the life stage at the queried timestamp.
    #[must_use]
    pub fn life_stage(&self) -> LifeStage {
        self.life_stage
    }

    /// Returns the regression quality indicator.
    ///
    /// This indicates whether the state was computed exactly or approximately.
    /// Forward projections are always Exact. Backward regressions may be
    /// Approximate if the time range contains spiral-triggering events.
    #[must_use]
    pub fn regression_quality(&self) -> RegressionQuality {
        self.regression_quality
    }

    /// Returns alerts generated during state computation.
    ///
    /// This is lazily computed on first access. Alerts include threshold
    /// violations and feedback loop detections.
    ///
    /// Returns a cloned vector of alerts per the spec API.
    #[must_use]
    pub fn alerts(&self) -> Vec<Alert> {
        self.alerts.get_or_init(|| self.compute_alerts()).clone()
    }

    /// Computes alerts for this state.
    fn compute_alerts(&self) -> Vec<Alert> {
        let state = &self.individual_state;
        let social = state.social_cognition();
        let mental = state.mental_health();
        let timestamp = self.age_at_timestamp;
        let mut alerts = Vec::new();

        let desire = mental.compute_suicidal_desire(social);
        if desire >= 0.8 {
            alerts.push(Alert::critical(
                AlertTrigger::threshold(
                    StatePath::MentalHealth(crate::enums::MentalHealthPath::SuicidalDesire),
                    desire as f64,
                ),
                timestamp,
                "High suicidal desire detected",
            ));
        } else if desire >= 0.5 {
            alerts.push(Alert::warning(
                AlertTrigger::threshold(
                    StatePath::MentalHealth(crate::enums::MentalHealthPath::SuicidalDesire),
                    desire as f64,
                ),
                timestamp,
                "Elevated suicidal desire detected",
            ));
        }

        let attempt_risk = mental.compute_attempt_risk(social);
        if attempt_risk >= 0.7 {
            alerts.push(Alert::critical(
                AlertTrigger::threshold(
                    StatePath::MentalHealth(crate::enums::MentalHealthPath::AttemptRisk),
                    attempt_risk as f64,
                ),
                timestamp,
                "High attempt risk detected",
            ));
        } else if attempt_risk >= 0.4 {
            alerts.push(Alert::warning(
                AlertTrigger::threshold(
                    StatePath::MentalHealth(crate::enums::MentalHealthPath::AttemptRisk),
                    attempt_risk as f64,
                ),
                timestamp,
                "Elevated attempt risk detected",
            ));
        }

        let stress = state.needs().stress_effective();
        let fatigue = state.needs().fatigue_effective();
        let impulse_control = state.disposition().impulse_control_effective();
        if stress > 0.8 && fatigue > 0.7 && impulse_control < 0.3 {
            alerts.push(Alert::warning(
                AlertTrigger::spiral(crate::enums::SpiralType::Stress),
                timestamp,
                "Stress spiral indicators detected",
            ));
        }

        let depression = mental.depression_effective();
        let loneliness = social.loneliness_effective();
        if depression > 0.7 && loneliness > 0.7 {
            alerts.push(Alert::warning(
                AlertTrigger::spiral(crate::enums::SpiralType::Depression),
                timestamp,
                "Depression-loneliness spiral indicators detected",
            ));
        }

        alerts
    }

    /// Gets the effective value for a state path.
    ///
    /// This is a convenience method that delegates to the individual state.
    ///
    /// # Arguments
    ///
    /// * `path` - The state path to query
    ///
    /// # Returns
    ///
    /// The effective value (base + delta) for stored paths,
    /// or the computed value for derived paths.
    ///
    #[must_use]
    pub fn get_effective(&self, path: StatePath) -> f64 {
        use crate::enums::{
            DispositionPath, HexacoPath, MentalHealthPath, MoodPath, NeedsPath,
            PersonCharacteristicsPath, SocialCognitionPath,
        };

        let state = &self.individual_state;

        let value: f32 = match path {
            StatePath::Hexaco(p) => match p {
                HexacoPath::HonestyHumility => state.hexaco().honesty_humility(),
                HexacoPath::Neuroticism => state.hexaco().neuroticism(),
                HexacoPath::Extraversion => state.hexaco().extraversion(),
                HexacoPath::Agreeableness => state.hexaco().agreeableness(),
                HexacoPath::Conscientiousness => state.hexaco().conscientiousness(),
                HexacoPath::Openness => state.hexaco().openness(),
            },
            StatePath::Mood(p) => match p {
                MoodPath::Valence => state.mood().valence_effective(),
                MoodPath::Arousal => state.mood().arousal_effective(),
                MoodPath::Dominance => state.mood().dominance_effective(),
            },
            StatePath::Needs(p) => match p {
                NeedsPath::Stress => state.needs().stress_effective(),
                NeedsPath::Fatigue => state.needs().fatigue_effective(),
                NeedsPath::Purpose => state.needs().purpose_effective(),
            },
            StatePath::SocialCognition(p) => match p {
                SocialCognitionPath::Loneliness => state.social_cognition().loneliness_effective(),
                SocialCognitionPath::PerceivedReciprocalCaring => state
                    .social_cognition()
                    .perceived_reciprocal_caring_effective(),
                SocialCognitionPath::PerceivedLiability => {
                    state.social_cognition().perceived_liability_effective()
                }
                SocialCognitionPath::SelfHate => state.social_cognition().self_hate_effective(),
                SocialCognitionPath::PerceivedCompetence => {
                    state.social_cognition().perceived_competence_effective()
                }
            },
            StatePath::MentalHealth(p) => match p {
                MentalHealthPath::Depression => state.mental_health().depression_effective(),
                MentalHealthPath::AcquiredCapability => {
                    state.mental_health().acquired_capability_effective()
                }
                MentalHealthPath::InterpersonalHopelessness => {
                    state.mental_health().interpersonal_hopelessness_effective()
                }
                MentalHealthPath::ThwartedBelongingness => state.compute_thwarted_belongingness(),
                MentalHealthPath::PerceivedBurdensomeness => {
                    state.compute_perceived_burdensomeness()
                }
                MentalHealthPath::SuicidalDesire => state.compute_suicidal_desire(),
                MentalHealthPath::AttemptRisk => state.compute_attempt_risk(),
                MentalHealthPath::SelfWorth => state.mental_health().self_worth_effective(),
                MentalHealthPath::Hopelessness => state.mental_health().hopelessness_effective(),
            },
            StatePath::Disposition(p) => match p {
                DispositionPath::Empathy => state.disposition().empathy_effective(),
                DispositionPath::Aggression => state.disposition().aggression_effective(),
                DispositionPath::Grievance => state.disposition().grievance_effective(),
                DispositionPath::ImpulseControl => state.disposition().impulse_control_effective(),
                DispositionPath::Reactance => state.disposition().reactance_effective(),
                DispositionPath::TrustorPropensity => {
                    state.disposition().trustor_propensity_effective()
                }
            },
            StatePath::PersonCharacteristics(p) => match p {
                PersonCharacteristicsPath::SocialCapital => {
                    state.person_characteristics().social_capital_effective()
                }
                PersonCharacteristicsPath::CognitiveAbility => {
                    state.person_characteristics().cognitive_ability_effective()
                }
                PersonCharacteristicsPath::EmotionalRegulationAssets => state
                    .person_characteristics()
                    .emotional_regulation_assets_effective(),
                PersonCharacteristicsPath::MaterialSecurity => {
                    state.person_characteristics().material_security_effective()
                }
                PersonCharacteristicsPath::ExperienceDiversity => state
                    .person_characteristics()
                    .experience_diversity_effective(),
                PersonCharacteristicsPath::BaselineMotivation => state
                    .person_characteristics()
                    .baseline_motivation_effective(),
                PersonCharacteristicsPath::PersistenceTendency => state
                    .person_characteristics()
                    .persistence_tendency_effective(),
                PersonCharacteristicsPath::CuriosityTendency => state
                    .person_characteristics()
                    .curiosity_tendency_effective(),
                // Composite values
                PersonCharacteristicsPath::Resource => state.person_characteristics().resource(),
                PersonCharacteristicsPath::Force => state.person_characteristics().force(),
            },
        };

        f64::from(value)
    }
}

impl Clone for ComputedState {
    fn clone(&self) -> Self {
        ComputedState {
            individual_state: self.individual_state.clone(),
            age_at_timestamp: self.age_at_timestamp,
            life_stage: self.life_stage,
            regression_quality: self.regression_quality,
            alerts: match self.alerts.get() {
                Some(v) => {
                    let cell = std::cell::OnceCell::new();
                    let _ = cell.set(v.clone());
                    cell
                }
                None => std::cell::OnceCell::new(),
            },
            interpretations: self.interpretations.clone(),
            summary: self.summary.clone(),
            delta_summary: self.delta_summary.clone(),
        }
    }
}

/// Collects base shift records from events that have formative personality shifts.
///
/// For forward queries, collects shifts from events before the query timestamp.
/// For backward queries, we don't collect shifts (they don't exist yet in the past).
fn collect_base_shift_records(
    events: &[&TimestampedEvent],
    entity: &Entity,
    query_timestamp: Timestamp,
    is_forward: bool,
) -> Vec<BaseShiftRecord> {
    // Backward queries don't include formative events (they haven't happened yet)
    if !is_forward {
        return Vec::new();
    }

    let reference_timestamp = entity
        .birth_date()
        .unwrap_or_else(|| Timestamp::from_ymd_hms(1970, 1, 1, 0, 0, 0));

    let mut records = Vec::new();
    let mut cumulative_positive: HashMap<HexacoPath, f32> = HashMap::new();
    let mut cumulative_negative: HashMap<HexacoPath, f32> = HashMap::new();

    for te in events {
        let event = te.event();

        // Skip events without base shifts
        if !event.has_base_shifts() {
            continue;
        }

        // Skip events after query timestamp
        if te.timestamp() > query_timestamp {
            continue;
        }

        // Compute entity's age at event time for plasticity modifiers
        let age_at_event = if let Some(birth_date) = entity.birth_date() {
            if te.timestamp() >= birth_date {
                (te.timestamp() - birth_date).as_years() as u16
            } else {
                0
            }
        } else {
            entity.age().as_years() as u16
        };

        // Convert event timestamp to Duration from reference
        let event_duration = if te.timestamp() >= reference_timestamp {
            te.timestamp() - reference_timestamp
        } else {
            Duration::zero()
        };

        // Process each base shift in the event
        for (trait_path, raw_amount) in event.base_shifts() {
            // Get existing cumulative in this direction
            let existing = if *raw_amount > 0.0 {
                *cumulative_positive.get(trait_path).unwrap_or(&0.0)
            } else {
                *cumulative_negative.get(trait_path).unwrap_or(&0.0)
            };

            // Apply all modifiers: plasticity, trait stability, saturation, caps
            let modified = apply_formative_modifiers(
                *raw_amount,
                *trait_path,
                age_at_event,
                existing,
                entity.species(),
            );

            // Skip zero shifts
            if modified.abs() < f32::EPSILON {
                continue;
            }

            // Create the base shift record
            let record = BaseShiftRecord::new(event_duration, *trait_path, modified);

            // Update cumulative tracking
            if modified > 0.0 {
                *cumulative_positive.entry(*trait_path).or_insert(0.0) += modified.abs();
            } else {
                *cumulative_negative.entry(*trait_path).or_insert(0.0) += modified.abs();
            }

            records.push(record);
        }
    }

    records
}

/// Applies accumulated base shifts to HEXACO personality traits in the state.
///
/// For each HEXACO trait, computes the effective base value using all
/// applicable base shift records, then updates the state's HEXACO values.
fn apply_base_shifts_to_state(
    mut state: IndividualState,
    shift_records: &[BaseShiftRecord],
    query_timestamp: Timestamp,
) -> IndividualState {
    // If no shifts, return state unchanged
    if shift_records.is_empty() {
        return state;
    }

    // Convert query timestamp to Duration for effective_base_at computation
    // Using a fixed reference of 1970 to be consistent with collect_base_shift_records
    let reference = Timestamp::from_ymd_hms(1970, 1, 1, 0, 0, 0);
    let query_duration = if query_timestamp >= reference {
        query_timestamp - reference
    } else {
        Duration::zero()
    };

    // Process each HEXACO trait
    for trait_path in HexacoPath::all() {
        // Filter records for this trait
        let trait_records: Vec<_> = shift_records
            .iter()
            .filter(|r| r.trait_path() == trait_path)
            .cloned()
            .collect();

        // Skip if no records for this trait
        if trait_records.is_empty() {
            continue;
        }

        // Get current base value
        let current_base = match trait_path {
            HexacoPath::Openness => state.hexaco().openness(),
            HexacoPath::Conscientiousness => state.hexaco().conscientiousness(),
            HexacoPath::Extraversion => state.hexaco().extraversion(),
            HexacoPath::Agreeableness => state.hexaco().agreeableness(),
            HexacoPath::Neuroticism => state.hexaco().neuroticism(),
            HexacoPath::HonestyHumility => state.hexaco().honesty_humility(),
        };

        // Compute effective base with accumulated shifts
        let effective = effective_base_at(current_base, &trait_records, query_duration);

        // Update the trait value in state
        match trait_path {
            HexacoPath::Openness => state.hexaco_mut().set_openness(effective),
            HexacoPath::Conscientiousness => state.hexaco_mut().set_conscientiousness(effective),
            HexacoPath::Extraversion => state.hexaco_mut().set_extraversion(effective),
            HexacoPath::Agreeableness => state.hexaco_mut().set_agreeableness(effective),
            HexacoPath::Neuroticism => state.hexaco_mut().set_neuroticism(effective),
            HexacoPath::HonestyHumility => state.hexaco_mut().set_honesty_humility(effective),
        }
    }

    state
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entity::EntityBuilder;
    use crate::enums::{EventType, RelationshipSchema, Species};
    use crate::event::EventBuilder;
    use crate::memory::{MemoryEntry, MemoryLayer, MemoryLayers};

    fn create_simulation() -> Simulation {
        let reference = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        Simulation::new(reference)
    }

    fn create_human(id: &str) -> crate::entity::Entity {
        EntityBuilder::new()
            .id(id)
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap()
    }

    #[test]
    fn entity_query_handle_entity_id() {
        let sim = create_simulation();
        let handle = EntityQueryHandle::new(&sim, EntityId::new("test").unwrap());
        assert_eq!(handle.entity_id().as_str(), "test");
    }

    #[test]
    fn entity_query_handle_anchor_timestamp() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = Timestamp::from_ymd_hms(2024, 1, 15, 12, 0, 0);
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        assert_eq!(handle.anchor_timestamp(), Some(anchor));
    }

    #[test]
    fn state_at_anchor_returns_original_state() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let _state = handle.state_at(anchor);
        // state_at now returns ComputedState directly, no need to check is_some
    }

    #[test]
    fn state_at_forward_applies_decay() {
        let mut sim = create_simulation();
        let mut entity = create_human("person_001");

        // Set a non-zero delta that will decay
        entity
            .individual_state_mut()
            .mood_mut()
            .add_valence_delta(0.5);

        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Query 1 week later
        let future = anchor + Duration::weeks(1);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let computed = handle.state_at(future);

        // Valence should have decayed (6-hour half-life, so 1 week = many half-lives)
        let valence = computed.get_effective(StatePath::Mood(crate::enums::MoodPath::Valence));
        assert!(valence < 0.1); // Nearly fully decayed
    }

    #[test]
    fn trust_decision_helpers_wire_propensity_and_relationship() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let alice = create_human("alice");
        let bob = create_human("bob");
        sim.add_entity(alice, reference);
        sim.add_entity(bob, reference);

        let alice_id = EntityId::new("alice").unwrap();
        let bob_id = EntityId::new("bob").unwrap();

        let formed = reference;
        let rel_id = sim.add_relationship(
            alice_id.clone(),
            bob_id.clone(),
            RelationshipSchema::Peer,
            formed,
        );

        let support_time = reference + Duration::days(3);
        let support = EventBuilder::new(EventType::ReceiveSupportEmotional)
            .source(bob_id.clone())
            .target(alice_id.clone())
            .severity(0.7)
            .build()
            .unwrap();
        sim.add_event(support, support_time);

        let context = TrustContext::new();
        let life_domain = LifeDomain::Relationship;
        let handle = sim.entity(&alice_id).unwrap();
        let decision_from_handle = handle
            .trust_decision_for(&bob_id, support_time, &context, life_domain, None)
            .unwrap();
        let decision_from_sim = sim
            .trust_decision_at(&alice_id, &bob_id, support_time, &context, life_domain, None)
            .unwrap();

        assert_eq!(decision_from_handle, decision_from_sim);
        let support = decision_from_handle.support_willingness();
        assert!(support.is_finite());
        assert!((0.0..=1.0).contains(&support));

        let rel = sim.get_relationship(&rel_id).unwrap().relationship();
        let direct = rel.compute_trust_decision(
            Direction::AToB,
            handle
                .state_at(support_time)
                .individual_state()
                .disposition()
                .trustor_propensity_effective(),
            &context,
            life_domain,
            None,
        );
        assert_eq!(decision_from_handle, direct);
    }

    #[test]
    fn trust_decision_for_returns_none_without_relationship() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let alice = create_human("alice");
        let bob = create_human("bob");
        sim.add_entity(alice, reference);
        sim.add_entity(bob, reference);

        let alice_id = EntityId::new("alice").unwrap();
        let bob_id = EntityId::new("bob").unwrap();

        let handle = sim.entity(&alice_id).unwrap();
        let decision = handle.trust_decision_for(
            &bob_id,
            reference,
            &TrustContext::new(),
            LifeDomain::Relationship,
            None,
        );

        assert!(decision.is_none());
    }

    #[test]
    fn trust_decision_for_uses_b_to_a_direction() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let alice = create_human("alice");
        let bob = create_human("bob");
        sim.add_entity(alice, reference);
        sim.add_entity(bob, reference);

        let alice_id = EntityId::new("alice").unwrap();
        let bob_id = EntityId::new("bob").unwrap();
        sim.add_relationship(
            alice_id.clone(),
            bob_id.clone(),
            RelationshipSchema::Peer,
            reference,
        );

        let handle = sim.entity(&bob_id).unwrap();
        let decision = handle.trust_decision_for(
            &alice_id,
            reference,
            &TrustContext::new(),
            LifeDomain::Relationship,
            None,
        );

        assert!(decision.is_some());
    }

    #[test]
    fn merge_memory_layers_copies_anchor_and_computed_memories() {
        let mut anchor = MemoryLayers::new();
        let mut computed = MemoryLayers::new();

        anchor.add(
            MemoryLayer::Immediate,
            MemoryEntry::new(Duration::days(1), "anchor_immediate"),
        );
        anchor.add(
            MemoryLayer::ShortTerm,
            MemoryEntry::new(Duration::days(2), "anchor_short_term"),
        );
        anchor.add(
            MemoryLayer::LongTerm,
            MemoryEntry::new(Duration::days(3), "anchor_long_term"),
        );
        anchor.add(
            MemoryLayer::Legacy,
            MemoryEntry::new(Duration::days(4), "anchor_legacy"),
        );

        computed.add(
            MemoryLayer::Immediate,
            MemoryEntry::new(Duration::days(5), "computed_immediate"),
        );
        computed.add(
            MemoryLayer::ShortTerm,
            MemoryEntry::new(Duration::days(6), "computed_short_term"),
        );
        computed.add(
            MemoryLayer::LongTerm,
            MemoryEntry::new(Duration::days(7), "computed_long_term"),
        );
        computed.add(
            MemoryLayer::Legacy,
            MemoryEntry::new(Duration::days(8), "computed_legacy"),
        );

        let merged = merge_memory_layers(&anchor, &computed);

        assert_eq!(merged.immediate_count(), 2);
        assert_eq!(merged.short_term_count(), 2);
        assert_eq!(merged.long_term_count(), 2);
        assert_eq!(merged.legacy_count(), 2);
        assert_eq!(merged.total_count(), 8);
        assert!(merged
            .immediate()
            .iter()
            .any(|memory| memory.summary() == "anchor_immediate"));
        assert!(merged
            .immediate()
            .iter()
            .any(|memory| memory.summary() == "computed_immediate"));
    }

    #[test]
    fn state_at_backward_regresses_state() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        sim.add_entity(entity, anchor);

        // Query 1 month earlier
        let past = Timestamp::from_ymd_hms(2024, 5, 1, 0, 0, 0);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let _state = handle.state_at(past);
        // state_at now returns ComputedState directly
    }

    #[test]
    fn computed_state_accessors() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        // Check all accessors
        let _ = state.individual_state();
        let _ = state.age_at_timestamp();
        let _ = state.life_stage();
        let _ = state.regression_quality();
    }

    #[test]
    fn estimate_relationship_quality_increases_with_attachments() {
        use crate::types::RelationshipId;

        let mut entity = create_human("person_001");
        let relationship_id = RelationshipId::new("rel_001_002").unwrap();
        entity.relationship_slots_mut()[0].attach_for_test(relationship_id);

        let quality = estimate_relationship_quality(&entity);
        assert!(quality > 0.3);
    }

    #[test]
    fn computed_state_alerts_lazy() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        // First access computes alerts (immutable access via interior mutability)
        let alerts = state.alerts();
        assert!(alerts.is_empty()); // No alerts by default

        // Second access should use cached value
        let alerts2 = state.alerts();
        assert!(alerts2.is_empty());
    }

    fn computed_state_with(individual_state: IndividualState) -> ComputedState {
        ComputedState {
            individual_state,
            age_at_timestamp: Duration::days(1),
            life_stage: LifeStage::Adult,
            regression_quality: RegressionQuality::Exact,
            alerts: std::cell::OnceCell::new(),
            interpretations: HashMap::new(),
            summary: String::new(),
            delta_summary: None,
        }
    }

    #[test]
    fn computed_state_alerts_high_risk_paths() {
        let social = crate::state::SocialCognition::new()
            .with_loneliness_base(1.0)
            .with_perceived_reciprocal_caring_base(0.0)
            .with_perceived_liability_base(1.0)
            .with_self_hate_base(1.0);
        let mental = crate::state::MentalHealth::new()
            .with_interpersonal_hopelessness_base(1.0)
            .with_acquired_capability_base(1.0)
            .with_depression_base(0.2);
        let individual_state = IndividualState::new()
            .with_social_cognition(social)
            .with_mental_health(mental);

        let computed = computed_state_with(individual_state);
        let alerts = computed.alerts();

        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::ThresholdExceeded(StatePath::MentalHealth(crate::enums::MentalHealthPath::SuicidalDesire), _)
        )));
        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::ThresholdExceeded(StatePath::MentalHealth(crate::enums::MentalHealthPath::AttemptRisk), _)
        )));
    }

    #[test]
    fn computed_state_alerts_warning_paths() {
        let social = crate::state::SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);
        let mental = crate::state::MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.8)
            .with_acquired_capability_base(0.8)
            .with_depression_base(0.2);
        let individual_state = IndividualState::new()
            .with_social_cognition(social)
            .with_mental_health(mental);

        let computed = computed_state_with(individual_state);
        let alerts = computed.alerts();

        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::ThresholdExceeded(StatePath::MentalHealth(crate::enums::MentalHealthPath::SuicidalDesire), _)
        )));
        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::ThresholdExceeded(StatePath::MentalHealth(crate::enums::MentalHealthPath::AttemptRisk), _)
        )));
    }

    #[test]
    fn computed_state_alerts_detect_spirals() {
        let needs = crate::state::Needs::new()
            .with_stress_base(0.9)
            .with_fatigue_base(0.8);
        let disposition = crate::state::Disposition::new().with_impulse_control_base(0.2);
        let social = crate::state::SocialCognition::new().with_loneliness_base(0.8);
        let mental = crate::state::MentalHealth::new().with_depression_base(0.8);
        let individual_state = IndividualState::new()
            .with_needs(needs)
            .with_disposition(disposition)
            .with_social_cognition(social)
            .with_mental_health(mental);

        let computed = computed_state_with(individual_state);
        let alerts = computed.alerts();

        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::SpiralDetected(crate::enums::SpiralType::Stress)
        )));
        assert!(alerts.iter().any(|a| matches!(
            a.trigger(),
            AlertTrigger::SpiralDetected(crate::enums::SpiralType::Depression)
        )));
    }

    #[test]
    fn build_trust_context_uses_event_microsystem() {
        use crate::event::EventBuilder;
        use crate::enums::EventType;

        let mut sim = create_simulation();
        let mut entity = create_human("person_001");
        let anchor = sim.reference_date();

        let micro_id = crate::types::MicrosystemId::new("work_ctx").unwrap();
        let mut work = crate::context::WorkContext::default();
        work.warmth = 0.8;
        work.hostility = 0.1;
        work.interaction_profile.interaction_frequency = 0.9;
        work.interaction_profile.interaction_complexity = 0.9;
        entity
            .context_mut()
            .add_microsystem(micro_id.clone(), crate::context::Microsystem::new_work(work));

        sim.add_entity(entity.clone(), anchor);
        let handle = sim.entity(&entity.id()).unwrap();

        let event = EventBuilder::new(EventType::ReceiveSupportEmotional)
            .context(micro_id)
            .build()
            .unwrap();

        let context = handle.build_trust_context(&entity, &event);
        assert!(context.time_pressure() > 0.5);
        assert!(context.social_norms() > 0.5);
    }

    #[test]
    fn build_trust_context_missing_microsystem_keeps_defaults() {
        use crate::event::EventBuilder;
        use crate::enums::EventType;

        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity.clone(), anchor);
        let handle = sim.entity(&entity.id()).unwrap();

        let micro_id = crate::types::MicrosystemId::new("unknown_ctx").unwrap();
        let event = EventBuilder::new(EventType::ReceiveSupportEmotional)
            .context(micro_id)
            .build()
            .unwrap();

        let context = handle.build_trust_context(&entity, &event);
        assert!((context.time_pressure() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn computed_state_get_effective_mood() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        let valence = state.get_effective(StatePath::Mood(crate::enums::MoodPath::Valence));
        assert!(valence >= -1.0 && valence <= 1.0);

        let arousal = state.get_effective(StatePath::Mood(crate::enums::MoodPath::Arousal));
        assert!(arousal >= -1.0 && arousal <= 1.0);

        let dominance = state.get_effective(StatePath::Mood(crate::enums::MoodPath::Dominance));
        assert!(dominance >= -1.0 && dominance <= 1.0);
    }

    #[test]
    fn computed_state_emotion_membership_sums_to_one() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        let membership = state.emotion_membership();
        let total: f64 = membership.values().copied().sum();
        assert!((total - 1.0).abs() < 1e-6);
    }

    #[test]
    fn computed_state_get_effective_needs() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::{NeedsPath, SocialCognitionPath};

        // get_effective now returns f64 directly - verify values are in valid range
        let loneliness =
            state.get_effective(StatePath::SocialCognition(SocialCognitionPath::Loneliness));
        assert!(loneliness >= 0.0 && loneliness <= 1.0);

        let prc = state.get_effective(StatePath::SocialCognition(
            SocialCognitionPath::PerceivedReciprocalCaring,
        ));
        assert!(prc >= 0.0 && prc <= 1.0);

        let liability = state.get_effective(StatePath::SocialCognition(
            SocialCognitionPath::PerceivedLiability,
        ));
        assert!(liability >= 0.0 && liability <= 1.0);

        let self_hate =
            state.get_effective(StatePath::SocialCognition(SocialCognitionPath::SelfHate));
        assert!(self_hate >= 0.0 && self_hate <= 1.0);

        let perceived_competence = state.get_effective(StatePath::SocialCognition(
            SocialCognitionPath::PerceivedCompetence,
        ));
        assert!(perceived_competence >= 0.0 && perceived_competence <= 1.0);

        let stress = state.get_effective(StatePath::Needs(NeedsPath::Stress));
        assert!(stress >= 0.0 && stress <= 1.0);

        let fatigue = state.get_effective(StatePath::Needs(NeedsPath::Fatigue));
        assert!(fatigue >= 0.0 && fatigue <= 1.0);

        let purpose = state.get_effective(StatePath::Needs(NeedsPath::Purpose));
        assert!(purpose >= 0.0 && purpose <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_mental_health() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::MentalHealthPath;

        // get_effective now returns f64 directly - verify values are in valid range
        let depression = state.get_effective(StatePath::MentalHealth(MentalHealthPath::Depression));
        assert!(depression >= 0.0 && depression <= 1.0);

        let ac = state.get_effective(StatePath::MentalHealth(
            MentalHealthPath::AcquiredCapability,
        ));
        assert!(ac >= 0.0 && ac <= 1.0);

        let ih = state.get_effective(StatePath::MentalHealth(
            MentalHealthPath::InterpersonalHopelessness,
        ));
        assert!(ih >= 0.0 && ih <= 1.0);

        let tb = state.get_effective(StatePath::MentalHealth(
            MentalHealthPath::ThwartedBelongingness,
        ));
        assert!(tb >= 0.0 && tb <= 1.0);

        let pb = state.get_effective(StatePath::MentalHealth(
            MentalHealthPath::PerceivedBurdensomeness,
        ));
        assert!(pb >= 0.0 && pb <= 1.0);

        let desire = state.get_effective(StatePath::MentalHealth(MentalHealthPath::SuicidalDesire));
        assert!(desire >= 0.0 && desire <= 1.0);

        let risk = state.get_effective(StatePath::MentalHealth(MentalHealthPath::AttemptRisk));
        assert!(risk >= 0.0 && risk <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_hexaco() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::HexacoPath;

        // get_effective now returns f64 directly - HEXACO values are 0.0-1.0
        let hh = state.get_effective(StatePath::Hexaco(HexacoPath::HonestyHumility));
        assert!(hh >= 0.0 && hh <= 1.0);

        let n = state.get_effective(StatePath::Hexaco(HexacoPath::Neuroticism));
        assert!(n >= 0.0 && n <= 1.0);

        let e = state.get_effective(StatePath::Hexaco(HexacoPath::Extraversion));
        assert!(e >= 0.0 && e <= 1.0);

        let a = state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));
        assert!(a >= 0.0 && a <= 1.0);

        let c = state.get_effective(StatePath::Hexaco(HexacoPath::Conscientiousness));
        assert!(c >= 0.0 && c <= 1.0);

        let o = state.get_effective(StatePath::Hexaco(HexacoPath::Openness));
        assert!(o >= 0.0 && o <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_disposition() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::DispositionPath;

        // get_effective now returns f64 directly
        let empathy = state.get_effective(StatePath::Disposition(DispositionPath::Empathy));
        assert!(empathy >= 0.0 && empathy <= 1.0);

        let aggression = state.get_effective(StatePath::Disposition(DispositionPath::Aggression));
        assert!(aggression >= 0.0 && aggression <= 1.0);

        let grievance = state.get_effective(StatePath::Disposition(DispositionPath::Grievance));
        assert!(grievance >= 0.0 && grievance <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_person_characteristics() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::PersonCharacteristicsPath;

        // get_effective now returns f64 directly
        let sc = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::SocialCapital,
        ));
        assert!(sc >= 0.0 && sc <= 1.0);

        let ca = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::CognitiveAbility,
        ));
        assert!(ca >= 0.0 && ca <= 1.0);

        let ms = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::MaterialSecurity,
        ));
        assert!(ms >= 0.0 && ms <= 1.0);
    }

    #[test]
    fn state_at_with_event_applies_event() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let entity_id = EntityId::new("person_001").unwrap();
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Add an event 1 day after anchor
        let event = EventBuilder::new(EventType::EndRelationshipRomantic)
            .target(entity_id.clone())
            .severity(0.7)
            .build()
            .unwrap();
        let event_time = anchor + Duration::days(1);
        sim.add_event(event, event_time);

        // Query 2 days after anchor (after the event)
        let query_time = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let _state = handle.state_at(query_time);
        // Event would have affected valence (social exclusion is negative)
    }

    #[test]
    fn age_at_timestamp_forward_with_birth_date() {
        let mut sim = create_simulation();
        let anchor = sim.reference_date();
        // Entity born 25 years before anchor
        let birth_date = anchor - Duration::years(25);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .birth_date(birth_date)
            .age(Duration::years(25))
            .build()
            .unwrap();
        sim.add_entity(entity, anchor);

        // Query 10 years later - age should be 35
        let future = anchor + Duration::years(10);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(future);

        assert_eq!(state.age_at_timestamp().as_years(), 35);
    }

    #[test]
    fn age_at_timestamp_forward_without_birth_date_is_constant() {
        let mut sim = create_simulation();
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(25))
            .build()
            .unwrap();
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Query 10 years later - age should still be 25 (constant without birth_date)
        let future = anchor + Duration::years(10);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(future);

        assert_eq!(state.age_at_timestamp().as_years(), 25);
    }

    #[test]
    fn age_at_timestamp_backward_with_birth_date() {
        let mut sim = create_simulation();
        let anchor = sim.reference_date();
        // Entity born 25 years before anchor
        let birth_date = anchor - Duration::years(25);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .birth_date(birth_date)
            .age(Duration::years(25))
            .build()
            .unwrap();
        sim.add_entity(entity, anchor);

        // Query 10 years earlier - age should be 15
        let past = anchor - Duration::years(10);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(past);

        assert_eq!(state.age_at_timestamp().as_years(), 15);
    }

    #[test]
    fn age_at_timestamp_backward_without_birth_date_is_constant() {
        let mut sim = create_simulation();
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(25))
            .build()
            .unwrap();
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Query 10 years earlier - age should still be 25 (constant without birth_date)
        let past = anchor - Duration::years(10);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(past);

        assert_eq!(state.age_at_timestamp().as_years(), 25);
    }

    #[test]
    fn life_stage_at_timestamp_with_birth_date() {
        let mut sim = create_simulation();
        let anchor = sim.reference_date();
        // Entity born 10 years before anchor
        let birth_date = anchor - Duration::years(10);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .birth_date(birth_date)
            .age(Duration::years(10))
            .build()
            .unwrap();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();

        // At anchor (age 10): Child
        let state = handle.state_at(anchor);
        assert_eq!(state.life_stage(), LifeStage::Child);

        // 10 years later (age 20): YoungAdult
        let future = anchor + Duration::years(10);
        let state2 = handle.state_at(future);
        assert_eq!(state2.life_stage(), LifeStage::YoungAdult);
    }

    #[test]
    fn life_stage_at_timestamp_without_birth_date_is_constant() {
        let mut sim = create_simulation();
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(10))
            .build()
            .unwrap();
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();

        // At anchor (age 10): Child
        let state = handle.state_at(anchor);
        assert_eq!(state.life_stage(), LifeStage::Child);

        // 10 years later - without birth_date, age stays 10, still Child
        let future = anchor + Duration::years(10);
        let state2 = handle.state_at(future);
        assert_eq!(state2.life_stage(), LifeStage::Child);
    }

    #[test]
    fn regression_quality_forward_is_exact() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let future = anchor + Duration::days(30);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(future);

        assert!(state.regression_quality().is_exact());
    }

    #[test]
    fn computed_state_debug() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        let debug = format!("{:?}", state);
        assert!(debug.contains("ComputedState"));
    }

    #[test]
    fn computed_state_clone() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);
        let cloned = state.clone();

        assert_eq!(state.age_at_timestamp(), cloned.age_at_timestamp());
    }

    #[test]
    #[should_panic(expected = "EntityQueryHandle created for non-existent entity")]
    fn state_at_nonexistent_entity_panics() {
        let sim = create_simulation();
        let unknown = EntityId::new("unknown").unwrap();
        let handle = EntityQueryHandle::new(&sim, unknown);

        // This should panic because the entity doesn't exist
        let _state = handle.state_at(sim.reference_date());
    }

    #[test]
    fn anchor_timestamp_nonexistent_entity() {
        let sim = create_simulation();
        let unknown = EntityId::new("unknown").unwrap();
        let handle = EntityQueryHandle::new(&sim, unknown);

        assert!(handle.anchor_timestamp().is_none());
    }

    #[test]
    fn state_at_backward_with_events() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let entity_id = EntityId::new("person_001").unwrap();

        // Set anchor to a later date
        let anchor = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        sim.add_entity(entity, anchor);

        // Add an event before the anchor (in the past relative to anchor)
        let event = EventBuilder::new(EventType::EndRelationshipRomantic)
            .target(entity_id.clone())
            .severity(0.7)
            .build()
            .unwrap();
        let event_time = Timestamp::from_ymd_hms(2024, 3, 1, 0, 0, 0);
        sim.add_event(event, event_time);

        // Query state before the anchor (backward regression through events)
        let past = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let handle = sim.entity(&entity_id).unwrap();
        let computed = handle.state_at(past);

        // Backward regression through events should still work
        assert!(computed.regression_quality().is_exact());
    }

    #[test]
    fn computed_state_get_effective_mental_health_all_paths() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::MentalHealthPath;

        // Test all mental health paths including SelfWorth and Hopelessness
        // get_effective now returns f64 directly
        let self_worth = state.get_effective(StatePath::MentalHealth(MentalHealthPath::SelfWorth));
        assert!(self_worth >= 0.0 && self_worth <= 1.0);

        let hopelessness =
            state.get_effective(StatePath::MentalHealth(MentalHealthPath::Hopelessness));
        assert!(hopelessness >= 0.0 && hopelessness <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_disposition_all_paths() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::DispositionPath;

        // Test all disposition paths - get_effective now returns f64 directly
        let impulse = state.get_effective(StatePath::Disposition(DispositionPath::ImpulseControl));
        assert!(impulse >= 0.0 && impulse <= 1.0);

        let reactance = state.get_effective(StatePath::Disposition(DispositionPath::Reactance));
        assert!(reactance >= 0.0 && reactance <= 1.0);

        let trust = state.get_effective(StatePath::Disposition(DispositionPath::TrustorPropensity));
        assert!(trust >= 0.0 && trust <= 1.0);
    }

    #[test]
    fn computed_state_get_effective_person_characteristics_all_paths() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        use crate::enums::PersonCharacteristicsPath;

        // Test all person characteristics paths - get_effective now returns f64 directly
        let era = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::EmotionalRegulationAssets,
        ));
        assert!(era >= 0.0 && era <= 1.0);

        let ed = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::ExperienceDiversity,
        ));
        assert!(ed >= 0.0 && ed <= 1.0);

        let bm = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::BaselineMotivation,
        ));
        assert!(bm >= 0.0 && bm <= 1.0);

        let pt = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::PersistenceTendency,
        ));
        assert!(pt >= 0.0 && pt <= 1.0);

        let ct = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::CuriosityTendency,
        ));
        assert!(ct >= 0.0 && ct <= 1.0);

        // Composite values can be any f64
        let _resource = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::Resource,
        ));

        let _force = state.get_effective(StatePath::PersonCharacteristics(
            PersonCharacteristicsPath::Force,
        ));
    }

    #[test]
    fn memories_at_returns_empty_for_new_entity() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let memories = handle.memories_at(anchor);

        assert!(memories.is_empty());
    }

    #[test]
    fn memories_at_returns_empty_for_nonexistent_entity() {
        let sim = create_simulation();
        let unknown = EntityId::new("unknown").unwrap();
        let handle = EntityQueryHandle::new(&sim, unknown);

        let memories = handle.memories_at(sim.reference_date());
        assert!(memories.is_empty());
    }

    #[test]
    fn memories_at_filters_by_timestamp() {
        use crate::memory::MemoryTag;

        let mut sim = create_simulation();

        // Create entity at age 25
        let mut entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(25))
            .build()
            .unwrap();

        // Create a memory at "current" age (age 25)
        entity.create_memory(
            "First memory at age 25",
            vec![],
            vec![MemoryTag::Personal],
            0.5,
            None,
        );

        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Query at anchor time - should see the memory
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let memories_at_anchor = handle.memories_at(anchor);
        assert_eq!(memories_at_anchor.len(), 1);

        // Query in the past (before entity's current age) - should not see memory
        // Entity is age 25 at anchor. Memory formed at age 25.
        // Going back 10 years makes entity age 15, so memory shouldn't exist.
        let past = anchor - Duration::years(10);
        let memories_past = handle.memories_at(past);
        assert!(memories_past.is_empty());
    }

    #[test]
    fn memories_at_forward_in_time() {
        // Test the forward path: timestamp >= anchor_timestamp
        use crate::memory::MemoryTag;

        let mut sim = create_simulation();

        // Create entity at age 25
        let mut entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(25))
            .build()
            .unwrap();

        // Create a memory at "current" age (age 25)
        entity.create_memory(
            "Memory at age 25",
            vec![],
            vec![MemoryTag::Personal],
            0.5,
            None,
        );

        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Query 10 years in the future - entity is now 35
        // Memory formed at age 25, so it should still exist
        let future = anchor + Duration::years(10);
        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let memories_future = handle.memories_at(future);

        // Memory should still exist (formed at age 25, now age 35)
        assert_eq!(memories_future.len(), 1);
    }

    #[test]
    fn age_computed_from_birth_date() {
        let mut sim = create_simulation();

        // Entity born on June 15, 1990
        let birth = Timestamp::from_ymd_hms(1990, 6, 15, 0, 0, 0);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(birth)
            .build()
            .unwrap();

        let anchor = sim.reference_date(); // 2024-01-01
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();

        // Query at anchor date (2024-01-01)
        let state = handle.state_at(anchor);
        let age_at_anchor = state.age_at_timestamp();

        // Should be approximately 33-34 years old
        assert!(age_at_anchor.as_years() >= 33);
        assert!(age_at_anchor.as_years() <= 34);

        // Query 10 years later
        let future = anchor + Duration::years(10);
        let future_state = handle.state_at(future);
        let age_at_future = future_state.age_at_timestamp();

        // Should be approximately 43-44 years old
        assert!(age_at_future.as_years() >= 43);
        assert!(age_at_future.as_years() <= 44);
    }

    #[test]
    fn age_before_birth_returns_zero() {
        // Entity born on 2000-01-01
        let birth = Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(birth)
            .build()
            .unwrap();

        let anchor = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let mut sim = Simulation::new(Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0));
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();

        // Query before birth
        let before_birth = Timestamp::from_ymd_hms(1990, 1, 1, 0, 0, 0);
        let state = handle.state_at(before_birth);

        // Age should be zero
        assert!(state.age_at_timestamp().is_zero());
    }

    #[test]
    fn regression_through_trauma_is_approximate() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let entity_id = EntityId::new("person_001").unwrap();

        // Set anchor to a later date
        let anchor = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        sim.add_entity(entity, anchor);

        // Add a trauma event (Violence) before the anchor
        let trauma_event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.8)
            .build()
            .unwrap();
        let event_time = Timestamp::from_ymd_hms(2024, 3, 1, 0, 0, 0);
        sim.add_event(trauma_event, event_time);

        // Query state before the trauma event (backward regression through trauma)
        let past = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(past);

        // Regression through trauma should be approximate (AC not reversible)
        assert!(state.regression_quality().is_approximate());
    }

    #[test]
    fn regression_without_trauma_is_exact() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let entity_id = EntityId::new("person_001").unwrap();

        // Set anchor to a later date
        let anchor = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        sim.add_entity(entity, anchor);

        // Add a social exclusion event (not trauma) before the anchor
        let social_event = EventBuilder::new(EventType::EndRelationshipRomantic)
            .target(entity_id.clone())
            .severity(0.5)
            .build()
            .unwrap();
        let event_time = Timestamp::from_ymd_hms(2024, 3, 1, 0, 0, 0);
        sim.add_event(social_event, event_time);

        // Query state before the event (backward regression)
        let past = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(past);

        // Regression through non-trauma events should be exact
        assert!(state.regression_quality().is_exact());
    }

    #[test]
    fn estimate_relationship_quality_baseline() {
        let entity = create_human("person_001");
        let baseline = estimate_relationship_quality(&entity);
        assert!((baseline - 0.3).abs() < f64::EPSILON);
    }

    #[test]
    fn computed_state_clone_with_cached_alerts() {
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        // Compute and cache alerts first
        let alerts1 = state.alerts();
        assert!(alerts1.is_empty());

        // Clone the state with cached alerts
        let cloned = state.clone();

        // The cloned state should also have the cached alerts
        let alerts2 = cloned.alerts();
        assert!(alerts2.is_empty());
    }

    #[test]
    fn computed_state_clone_without_cached_alerts() {
        // Test cloning when alerts haven't been accessed yet (None branch)
        let mut sim = create_simulation();
        let entity = create_human("person_001");
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        let handle = sim.entity(&EntityId::new("person_001").unwrap()).unwrap();
        let state = handle.state_at(anchor);

        // Clone WITHOUT accessing alerts first
        let cloned = state.clone();

        // Both original and cloned should work independently
        let alerts1 = state.alerts();
        let alerts2 = cloned.alerts();
        assert!(alerts1.is_empty());
        assert!(alerts2.is_empty());
    }

    #[test]
    fn memories_at_before_birth_returns_empty() {
        // Test the case where query timestamp is so far in the past
        // that elapsed >= anchor_age (age would be negative, so returns zero)
        use crate::memory::MemoryTag;

        let mut sim = create_simulation();

        // Create entity at age 5 (young entity)
        let mut entity = EntityBuilder::new()
            .id("child_001")
            .species(Species::Human)
            .age(Duration::years(5))
            .build()
            .unwrap();

        // Create a memory at "current" age (age 5)
        entity.create_memory(
            "Memory at age 5",
            vec![],
            vec![MemoryTag::Personal],
            0.5,
            None,
        );

        let anchor = sim.reference_date(); // 2024-01-01
        sim.add_entity(entity, anchor);

        // Query 10 years in the past from anchor
        // Entity is age 5 at anchor, so 10 years ago they weren't born yet
        let past = anchor - Duration::years(10);
        let handle = sim.entity(&EntityId::new("child_001").unwrap()).unwrap();
        let memories = handle.memories_at(past);

        // Should return empty because age would be negative
        assert!(memories.is_empty());
    }

    #[test]
    fn developmental_effects_entity_without_birth_date_uses_anchor_age() {
        // Test that developmental effects use anchor age when no birth_date is set
        let mut sim = create_simulation();

        // Create entity with just age (no birth_date)
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(30))
            .build()
            .unwrap();

        let entity_id = EntityId::new("person_001").unwrap();
        let anchor = sim.reference_date();
        sim.add_entity(entity, anchor);

        // Add an event
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.5)
            .build()
            .unwrap();
        let event_time = anchor + Duration::days(10);
        sim.add_event(event, event_time);

        // Query state after event - developmental effects should use anchor age
        let query_time = anchor + Duration::days(20);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(query_time);

        // State should be valid (developmental effects applied correctly)
        let valence = state.get_effective(StatePath::Mood(crate::enums::MoodPath::Valence));
        assert!(valence >= -1.0 && valence <= 1.0);
    }

    #[test]
    fn developmental_effects_event_after_birth_date_uses_birth_age() {
        // Test developmental effects when event timestamp is after birth_date
        let birth_date = Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(birth_date)
            .build()
            .unwrap();

        let entity_id = EntityId::new("person_001").unwrap();
        let anchor = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let mut sim = Simulation::new(anchor);
        sim.add_entity(entity, anchor);

        let event = EventBuilder::new(EventType::AchieveGoalMajor)
            .target(entity_id.clone())
            .severity(0.5)
            .build()
            .unwrap();
        let event_time = anchor + Duration::days(10);
        sim.add_event(event, event_time);

        let query_time = anchor + Duration::days(20);
        let handle = sim.entity(&entity_id).unwrap();
        assert_eq!(
            handle
                .get_sorted_events_for_range(anchor, query_time, true)
                .len(),
            1
        );
        let state = handle.state_at(query_time);

        assert!(!state.age_at_timestamp().is_zero());
    }

    #[test]
    fn developmental_effects_event_before_birth_date() {
        // Test developmental effects when event timestamp is before birth_date
        // This is an edge case that shouldn't happen in practice but must be handled

        // Create entity with birth_date
        let birth_date = Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(birth_date)
            .build()
            .unwrap();

        let entity_id = EntityId::new("person_001").unwrap();
        let anchor = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let mut sim = Simulation::new(anchor);
        sim.add_entity(entity, anchor);

        // Add an event at a timestamp BEFORE birth_date
        // This is conceptually invalid but tests the edge case handling
        let event = EventBuilder::new(EventType::AchieveGoalMajor)
            .target(entity_id.clone())
            .severity(0.5)
            .build()
            .unwrap();
        let event_time = Timestamp::from_ymd_hms(1990, 1, 1, 0, 0, 0); // Before birth
        sim.add_event(event, event_time);

        // Query state far enough in the past so the pre-birth event is in range
        let query_time = Timestamp::from_ymd_hms(1980, 1, 1, 0, 0, 0);
        let handle = sim.entity(&entity_id).unwrap();
        assert_eq!(
            handle
                .get_sorted_events_for_range(anchor, query_time, false)
                .len(),
            1
        );
        let state = handle.state_at(query_time);

        // The age at the event should be treated as zero (floor at birth)
        // This tests the Duration::zero() branch in compute_age_at
        assert!(state.age_at_timestamp().is_zero());
    }

    // Formative events tests

    #[test]
    fn formative_event_shifts_personality() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        // Create a human with birth date 25 years before reference
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Get baseline agreeableness
        let handle = sim.entity(&entity_id).unwrap();
        let baseline_state = handle.state_at(anchor);
        let baseline_agreeableness =
            baseline_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Add a formative event with a base shift
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.9)
            .with_base_shift(HexacoPath::Agreeableness, -0.15)
            .build()
            .unwrap();
        let event_time = anchor + Duration::days(1);
        sim.add_event(event, event_time);

        // Query after the formative event
        let later = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let later_state = handle.state_at(later);
        let later_agreeableness =
            later_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Agreeableness should have decreased due to the base shift
        assert!(later_agreeableness < baseline_agreeableness);
    }

    #[test]
    fn formative_event_backward_query_no_shift() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        // Create a human with birth date 25 years before reference
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference + Duration::days(10);
        sim.add_entity(entity, anchor);

        // Add a formative event BEFORE the anchor
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.9)
            .with_base_shift(HexacoPath::Agreeableness, -0.15)
            .build()
            .unwrap();
        let event_time = reference + Duration::days(5);
        sim.add_event(event, event_time);

        // Query BEFORE the formative event (backward from anchor)
        let earlier = reference + Duration::days(1);
        let handle = sim.entity(&entity_id).unwrap();
        let earlier_state = handle.state_at(earlier);
        let earlier_agreeableness =
            earlier_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Query at anchor
        let anchor_state = handle.state_at(anchor);
        let anchor_agreeableness =
            anchor_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // For backward query, the shift hasn't happened yet
        // Both should be equal to the anchor state's agreeableness
        // (since backward query doesn't apply formative events)
        assert!((earlier_agreeableness - anchor_agreeableness).abs() < 0.1);
    }

    #[test]
    fn formative_event_multiple_shifts_same_trait() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        // Create a human with birth date 25 years before reference
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Get baseline
        let handle = sim.entity(&entity_id).unwrap();
        let baseline_state = handle.state_at(anchor);
        let baseline_agreeableness =
            baseline_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Add first formative event
        let event1 = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.8)
            .with_base_shift(HexacoPath::Agreeableness, -0.10)
            .build()
            .unwrap();
        sim.add_event(event1, anchor + Duration::days(1));

        // Add second formative event
        let event2 = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.7)
            .with_base_shift(HexacoPath::Agreeableness, -0.08)
            .build()
            .unwrap();
        sim.add_event(event2, anchor + Duration::days(2));

        // Query after both events
        let later = anchor + Duration::days(3);
        let handle = sim.entity(&entity_id).unwrap();
        let later_state = handle.state_at(later);
        let later_agreeableness =
            later_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Agreeableness should have decreased by cumulative amount (with modifiers)
        assert!(later_agreeableness < baseline_agreeableness);
    }

    #[test]
    fn formative_event_no_shift_leaves_trait_unchanged() {
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Get baseline
        let handle = sim.entity(&entity_id).unwrap();
        let baseline_state = handle.state_at(anchor);
        let baseline_openness =
            baseline_state.get_effective(StatePath::Hexaco(HexacoPath::Openness));

        // Add event WITHOUT base shift
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.8)
            .build()
            .unwrap();
        sim.add_event(event, anchor + Duration::days(1));

        // Query after the event
        let later = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let later_state = handle.state_at(later);
        let later_openness = later_state.get_effective(StatePath::Hexaco(HexacoPath::Openness));

        // Openness should be unchanged (events without base shifts don't affect personality base)
        assert!((later_openness - baseline_openness).abs() < 0.01);
    }

    #[test]
    fn collect_base_shifts_empty_for_backward_query() {
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        let records = collect_base_shift_records(
            &[],
            &entity,
            Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0),
            false, // backward query
        );

        assert!(records.is_empty());
    }

    #[test]
    fn apply_base_shifts_empty_records_returns_unchanged() {
        let state = IndividualState::new();
        let original_openness = state.hexaco().openness();

        let result =
            apply_base_shifts_to_state(state, &[], Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0));

        assert!((result.hexaco().openness() - original_openness).abs() < f32::EPSILON);
    }

    #[test]
    fn formative_event_all_hexaco_traits() {
        // Test all six HEXACO traits get shifted
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Add event with all 6 traits
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.9)
            .with_base_shift(HexacoPath::Openness, 0.10)
            .with_base_shift(HexacoPath::Conscientiousness, -0.08)
            .with_base_shift(HexacoPath::Extraversion, 0.12)
            .with_base_shift(HexacoPath::Agreeableness, -0.15)
            .with_base_shift(HexacoPath::Neuroticism, 0.20)
            .with_base_shift(HexacoPath::HonestyHumility, -0.05)
            .build()
            .unwrap();
        sim.add_event(event, anchor + Duration::days(1));

        // Query after event
        let later = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(later);

        // Verify we can access all traits (proving they were processed)
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::Openness));
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::Conscientiousness));
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::Extraversion));
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::Neuroticism));
        let _ = state.get_effective(StatePath::Hexaco(HexacoPath::HonestyHumility));
    }

    #[test]
    fn formative_event_positive_and_negative_shifts() {
        // Test both positive and negative shifts are handled
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Get baseline
        let handle = sim.entity(&entity_id).unwrap();
        let baseline_state = handle.state_at(anchor);
        let baseline_extraversion =
            baseline_state.get_effective(StatePath::Hexaco(HexacoPath::Extraversion));

        // Add event with positive shift
        let event = EventBuilder::new(EventType::AchieveGoalMajor)
            .target(entity_id.clone())
            .severity(0.7)
            .with_base_shift(HexacoPath::Extraversion, 0.15)
            .build()
            .unwrap();
        sim.add_event(event, anchor + Duration::days(1));

        // Query after event
        let later = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let later_state = handle.state_at(later);
        let later_extraversion =
            later_state.get_effective(StatePath::Hexaco(HexacoPath::Extraversion));

        // Positive shift should increase the trait
        assert!(later_extraversion > baseline_extraversion);
    }

    #[test]
    fn formative_event_entity_without_birth_date() {
        // Test entity without birth date uses anchor age
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        // Entity without birth date (uses default age)
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(Duration::years(30))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Add formative event
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.8)
            .with_base_shift(HexacoPath::Openness, -0.10)
            .build()
            .unwrap();
        sim.add_event(event, anchor + Duration::days(1));

        // Query after event (should work even without birth date)
        let later = anchor + Duration::days(2);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(later);

        // Just verify it doesn't panic and produces valid state
        let openness = state.get_effective(StatePath::Hexaco(HexacoPath::Openness));
        assert!(openness >= -1.0 && openness <= 1.0);
    }

    #[test]
    fn formative_event_after_query_timestamp_ignored() {
        // Test that events after query timestamp are not included
        let mut sim = create_simulation();
        let reference = sim.reference_date();

        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(reference - Duration::years(25))
            .build()
            .unwrap();

        let entity_id = entity.id().clone();
        let anchor = reference;
        sim.add_entity(entity, anchor);

        // Get baseline
        let handle = sim.entity(&entity_id).unwrap();
        let baseline_state = handle.state_at(anchor);
        let baseline_agreeableness =
            baseline_state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Add formative event in the future
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .target(entity_id.clone())
            .severity(0.9)
            .with_base_shift(HexacoPath::Agreeableness, -0.30)
            .build()
            .unwrap();
        sim.add_event(event, anchor + Duration::days(10));

        // Query BEFORE the event
        let before_event = anchor + Duration::days(5);
        let handle = sim.entity(&entity_id).unwrap();
        let state = handle.state_at(before_event);
        let agreeableness = state.get_effective(StatePath::Hexaco(HexacoPath::Agreeableness));

        // Should be close to baseline since event hasn't happened yet
        assert!((agreeableness - baseline_agreeableness).abs() < 0.01);
    }

    #[test]
    fn collect_base_shifts_forward_query_with_events() {
        // Direct test of collect_base_shift_records for forward query
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(1999, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        let records = collect_base_shift_records(
            &[],
            &entity,
            Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0),
            true, // forward query
        );

        // Empty events list = empty records
        assert!(records.is_empty());
    }

    #[test]
    fn apply_base_shifts_updates_all_traits() {
        use crate::state::BaseShiftRecord;

        let state = IndividualState::new();
        let original_openness = state.hexaco().openness();

        // Create a shift record directly
        let records = vec![BaseShiftRecord::new(
            Duration::days(1),
            HexacoPath::Openness,
            0.15,
        )];

        let result = apply_base_shifts_to_state(
            state.clone(),
            &records,
            Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0),
        );

        // Openness should have changed
        assert!((result.hexaco().openness() - original_openness).abs() > 0.01);
    }

    #[test]
    fn apply_base_shifts_each_hexaco_trait() {
        use crate::state::BaseShiftRecord;

        // Test each trait individually
        for trait_path in HexacoPath::all() {
            let state = IndividualState::new();
            let records = vec![BaseShiftRecord::new(Duration::days(1), trait_path, 0.10)];

            let result = apply_base_shifts_to_state(
                state,
                &records,
                Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0),
            );

            // Verify result is valid (no panic, valid state)
            let value = match trait_path {
                HexacoPath::Openness => result.hexaco().openness(),
                HexacoPath::Conscientiousness => result.hexaco().conscientiousness(),
                HexacoPath::Extraversion => result.hexaco().extraversion(),
                HexacoPath::Agreeableness => result.hexaco().agreeableness(),
                HexacoPath::Neuroticism => result.hexaco().neuroticism(),
                HexacoPath::HonestyHumility => result.hexaco().honesty_humility(),
            };
            assert!(value >= -1.0 && value <= 1.0);
        }
    }

    #[test]
    fn collect_base_shifts_event_after_query_timestamp_skipped() {
        // Direct test: event with base shift AFTER query timestamp should be skipped (line 828)
        use crate::simulation::TimestampedEvent;

        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(1999, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // Create event with base shift at day 100
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .with_base_shift(HexacoPath::Agreeableness, -0.20)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(2024, 4, 10, 0, 0, 0));

        // Query timestamp is BEFORE event timestamp
        let query_ts = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // Event after query should be skipped
        assert!(records.is_empty());
    }

    #[test]
    fn collect_base_shifts_event_before_birth_date_age_zero() {
        // Direct test: event BEFORE entity birth date (line 836 - age = 0)
        use crate::simulation::TimestampedEvent;

        // Entity born in 2010
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(2010, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // Event in 2005 - BEFORE entity was born
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .with_base_shift(HexacoPath::Neuroticism, 0.25)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(2005, 6, 1, 0, 0, 0));

        // Query in 2020 (forward query)
        let query_ts = Timestamp::from_ymd_hms(2020, 1, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // Event should still be processed with age 0 (high plasticity)
        assert_eq!(records.len(), 1);
    }

    #[test]
    fn collect_base_shifts_entity_without_birth_date_uses_anchor_age() {
        // Direct test: entity without birth_date uses entity.age() (line 839)
        use crate::simulation::TimestampedEvent;

        // Entity without birth_date, just has age
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(Duration::years(35))
            .build()
            .unwrap();

        // Event with base shift
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .with_base_shift(HexacoPath::Conscientiousness, -0.15)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(2024, 1, 15, 0, 0, 0));

        // Query after event
        let query_ts = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // Should have processed the event using entity.age() (35 years)
        assert_eq!(records.len(), 1);
    }

    #[test]
    fn collect_base_shifts_event_before_1970_reference() {
        // Direct test: event timestamp before 1970 reference (line 846)
        use crate::simulation::TimestampedEvent;

        // Entity born in 1940
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(1940, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // Event in 1960 - before 1970 reference timestamp
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .with_base_shift(HexacoPath::Extraversion, -0.20)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(1960, 6, 1, 0, 0, 0));

        // Query in 2000
        let query_ts = Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // Event before 1970 should still be processed (uses Duration::zero)
        assert_eq!(records.len(), 1);
    }

    #[test]
    fn collect_base_shifts_tiny_shift_rounds_to_zero() {
        // Direct test: shift that becomes zero after modifiers (line 869)
        use crate::simulation::TimestampedEvent;

        // Entity at age 80 (low plasticity: 0.6)
        // Extraversion has stability 0.85, so trait_modifier = 0.15
        // Very small input shift that after modifiers approaches zero
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(1940, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // Tiny shift: 1e-8 * 0.6 (age plasticity) * 0.15 (trait modifier) = ~9e-10
        // f32::EPSILON is ~1.19e-7, so result should be well below that
        let event = EventBuilder::new(EventType::ExperienceCombatMilitary)
            .with_base_shift(HexacoPath::Extraversion, 1e-8)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(2020, 6, 1, 0, 0, 0));

        // Query after event
        let query_ts = Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // The modified shift should be near zero and skipped
        assert!(records.is_empty());
    }

    #[test]
    fn collect_base_shifts_positive_cumulative_tracking() {
        // Direct test: positive shift updates cumulative_positive (line 877)
        use crate::simulation::TimestampedEvent;

        // Young entity (high plasticity)
        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // POSITIVE shift (not negative) to hit line 877
        let event = EventBuilder::new(EventType::AchieveGoalMajor)
            .with_base_shift(HexacoPath::Agreeableness, 0.25)
            .build()
            .unwrap();
        let te = TimestampedEvent::new(event, Timestamp::from_ymd_hms(2024, 1, 15, 0, 0, 0));

        let query_ts = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te], &entity, query_ts, true);

        // Should have one positive shift record
        assert_eq!(records.len(), 1);
        assert!(records[0].immediate() > 0.0);
    }

    #[test]
    fn collect_base_shifts_multiple_positive_shifts_diminishing() {
        // Test that multiple positive shifts get diminishing returns
        use crate::simulation::TimestampedEvent;

        let entity = EntityBuilder::new()
            .id("test")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(Timestamp::from_ymd_hms(2000, 1, 1, 0, 0, 0))
            .build()
            .unwrap();

        // First positive shift
        let event1 = EventBuilder::new(EventType::AchieveGoalMajor)
            .with_base_shift(HexacoPath::Agreeableness, 0.30)
            .build()
            .unwrap();
        let te1 = TimestampedEvent::new(event1, Timestamp::from_ymd_hms(2024, 1, 15, 0, 0, 0));

        // Second positive shift - should have diminishing returns
        let event2 = EventBuilder::new(EventType::AchieveGoalMajor)
            .with_base_shift(HexacoPath::Agreeableness, 0.30)
            .build()
            .unwrap();
        let te2 = TimestampedEvent::new(event2, Timestamp::from_ymd_hms(2024, 2, 15, 0, 0, 0));

        let query_ts = Timestamp::from_ymd_hms(2024, 6, 1, 0, 0, 0);
        let records = collect_base_shift_records(&[&te1, &te2], &entity, query_ts, true);

        // Both shifts should be recorded
        assert_eq!(records.len(), 2);

        // Second shift should be smaller due to diminishing returns
        assert!(records[1].immediate() < records[0].immediate());
    }

    #[test]
    fn apply_base_shifts_empty_returns_unchanged() {
        // Direct test for empty shift records (line 899-901)
        let state = IndividualState::new();
        let original_openness = state.hexaco().openness();

        let result = apply_base_shifts_to_state(
            state,
            &[], // empty records
            Timestamp::from_ymd_hms(2024, 1, 1, 0, 0, 0),
        );

        assert!((result.hexaco().openness() - original_openness).abs() < f32::EPSILON);
    }

    #[test]
    fn apply_base_shifts_query_before_1970() {
        // Direct test: query timestamp before 1970 (line 909)
        use crate::state::BaseShiftRecord;

        let state = IndividualState::new();

        let records = vec![BaseShiftRecord::new(
            Duration::days(1),
            HexacoPath::Openness,
            0.15,
        )];

        // Query timestamp before 1970
        let result = apply_base_shifts_to_state(
            state,
            &records,
            Timestamp::from_ymd_hms(1950, 1, 1, 0, 0, 0),
        );

        // Should still work (uses Duration::zero for query)
        assert!(result.hexaco().openness() >= -1.0 && result.hexaco().openness() <= 1.0);
    }
}