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
//! Ecological context system for Bronfenbrenner's bioecological model.
//!
//! This module implements the five nested ecological layers that influence
//! human development:
//!
//! - **Microsystem**: Immediate environments with face-to-face interactions
//! - **Mesosystem**: Computed linkages between microsystems (spillover, role conflict)
//! - **Exosystem**: Settings that affect the individual indirectly
//! - **Macrosystem**: Overarching cultural, societal, and ideological patterns
//! - **Chronosystem**: Temporal dimension including life transitions and historical events
//!
//! # Design
//!
//! Entity holds a single `context: EcologicalContext` field that composes all 5 layers.
//! Microsystem values are static f64 (not StateValue) - they change via explicit events,
//! not gradual decay. Mesosystem values are always computed from microsystem data.

mod chronosystem;
mod effects;
mod exosystem;
mod macrosystem;
mod mesosystem;
mod microsystem;

pub use chronosystem::{
    ChronosystemContext, CohortEffects, CriticalPeriod, CulturalShift, HistoricalPeriod,
    NonNormativeEvent, NormativeTransition, TurningPoint, TurningPointDomain,
};
pub(crate) use effects::apply_context_effects;
pub use exosystem::{ExosystemContext, ParentWorkQuality};
pub use macrosystem::{
    CulturalOrientation, InstitutionalStructure, MacrosystemConstraintSet, MacrosystemContext,
};
pub use mesosystem::{
    passes_proximal_process_gate, passes_proximal_process_gate_with_reciprocity, MesosystemCache,
    MesosystemLinkage, MesosystemState, ProximalProcessGateError,
    INTERACTION_COMPLEXITY_THRESHOLD, INTERACTION_FREQUENCY_THRESHOLD,
    INTERACTION_RECIPROCITY_THRESHOLD,
};
pub use microsystem::{
    EducationContext, FamilyContext, FamilyRole, HealthcareContext, InteractionProfile,
    Microsystem, MicrosystemType, NeighborhoodContext, ReligiousContext, SocialContext,
    WorkContext,
};

use crate::enums::{ApparentGender, ApparentRace, ContextPath, VisibleTrait};
use crate::state::DemandCharacteristics;
use crate::types::MicrosystemId;
use std::collections::HashMap;

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PadBounds {
    pub valence_min: f32,
    pub valence_max: f32,
    pub arousal_min: f32,
    pub arousal_max: f32,
    pub dominance_min: f32,
    pub dominance_max: f32,
}

/// Aggregate container for all ecological context layers.
///
/// This struct composes all five Bronfenbrenner layers and provides
/// unified access to context dimensions.
///
/// # Microsystem Storage
///
/// Microsystems are stored in a HashMap keyed by MicrosystemId. This allows:
/// - Multiple microsystems of the same type (e.g., two jobs)
/// - O(1) lookup by ID
/// - Efficient iteration for mesosystem computation
///
/// # Mesosystem Computation
///
/// Mesosystem values are computed from microsystem data and stored as a
/// derived snapshot for query. A cache is maintained for linkage computations,
/// invalidated per-simulation-step.
///
#[derive(Debug, Clone, PartialEq)]
pub struct EcologicalContext {
    /// Microsystem instances keyed by ID.
    microsystems: HashMap<MicrosystemId, Microsystem>,

    /// Exosystem context (indirect influences).
    exosystem: ExosystemContext,

    /// Macrosystem context (cultural patterns).
    macrosystem: MacrosystemContext,

    /// Chronosystem context (temporal dimension).
    chronosystem: ChronosystemContext,

    /// Cached mesosystem linkages (computed from microsystems).
    mesosystem_cache: MesosystemCache,

    /// Stored mesosystem state computed from microsystems.
    mesosystem_state: MesosystemState,
}

impl EcologicalContext {
    /// Creates a new EcologicalContext with default values.
    #[must_use]
    pub fn new() -> Self {
        EcologicalContext {
            microsystems: HashMap::new(),
            exosystem: ExosystemContext::default(),
            macrosystem: MacrosystemContext::default(),
            chronosystem: ChronosystemContext::default(),
            mesosystem_cache: MesosystemCache::new(),
            mesosystem_state: MesosystemState::default(),
        }
    }

    // --- Microsystem Management ---

    /// Adds a microsystem with the given ID.
    ///
    /// If a microsystem with the same ID already exists, it is replaced.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for this microsystem instance
    /// * `microsystem` - The microsystem to add
    pub fn add_microsystem(&mut self, id: MicrosystemId, microsystem: Microsystem) {
        self.microsystems.insert(id, microsystem);
        self.mesosystem_cache.invalidate();
    }

    /// Gets a reference to a microsystem by ID.
    #[must_use]
    pub fn get_microsystem(&self, id: &MicrosystemId) -> Option<&Microsystem> {
        self.microsystems.get(id)
    }

    /// Gets a mutable reference to a microsystem by ID.
    pub fn get_microsystem_mut(&mut self, id: &MicrosystemId) -> Option<&mut Microsystem> {
        self.microsystems.get_mut(id)
    }

    /// Removes a microsystem by ID.
    ///
    /// Returns the removed microsystem if it existed.
    pub fn remove_microsystem(&mut self, id: &MicrosystemId) -> Option<Microsystem> {
        let result = self.microsystems.remove(id);
        if result.is_some() {
            self.mesosystem_cache.invalidate();
        }
        result
    }

    /// Lists all microsystem IDs of a given type.
    #[must_use]
    pub fn list_microsystems(&self, microsystem_type: MicrosystemType) -> Vec<MicrosystemId> {
        self.microsystems
            .iter()
            .filter(|(_, m)| m.microsystem_type() == microsystem_type)
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Returns the total number of microsystems.
    #[must_use]
    pub fn microsystem_count(&self) -> usize {
        self.microsystems.len()
    }

    /// Returns true if no microsystems are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.microsystems.is_empty()
    }

    /// Returns an iterator over all microsystem entries.
    pub fn microsystems_iter(&self) -> impl Iterator<Item = (&MicrosystemId, &Microsystem)> {
        self.microsystems.iter()
    }

    // --- Layer Accessors ---

    /// Returns a reference to the exosystem context.
    #[must_use]
    pub fn exosystem(&self) -> &ExosystemContext {
        &self.exosystem
    }

    /// Returns a mutable reference to the exosystem context.
    pub fn exosystem_mut(&mut self) -> &mut ExosystemContext {
        &mut self.exosystem
    }

    /// Returns a reference to the macrosystem context.
    #[must_use]
    pub fn macrosystem(&self) -> &MacrosystemContext {
        &self.macrosystem
    }

    /// Returns a mutable reference to the macrosystem context.
    pub fn macrosystem_mut(&mut self) -> &mut MacrosystemContext {
        &mut self.macrosystem
    }

    /// Returns a reference to the chronosystem context.
    #[must_use]
    pub fn chronosystem(&self) -> &ChronosystemContext {
        &self.chronosystem
    }

    /// Returns a mutable reference to the chronosystem context.
    pub fn chronosystem_mut(&mut self) -> &mut ChronosystemContext {
        &mut self.chronosystem
    }

    // --- Mesosystem Access ---

    /// Returns a reference to the mesosystem cache.
    #[must_use]
    pub fn mesosystem_cache(&self) -> &MesosystemCache {
        &self.mesosystem_cache
    }

    /// Computes and returns the mesosystem state snapshot.
    ///
    /// This recomputes and stores mesosystem values derived from current
    /// microsystems for later query.
    #[must_use]
    pub fn mesosystem_state(&mut self) -> &MesosystemState {
        self.mesosystem_state = MesosystemState::compute(&self.microsystems);
        &self.mesosystem_state
    }

    /// Returns the last computed mesosystem state snapshot.
    #[must_use]
    pub fn mesosystem_state_cached(&self) -> &MesosystemState {
        &self.mesosystem_state
    }

    /// Invalidates the mesosystem cache.
    ///
    /// This is called internally during state computation to ensure
    /// mesosystem values are recomputed for the next query.
    pub fn invalidate_mesosystem_cache(&mut self) {
        self.mesosystem_cache.invalidate();
    }

    /// Computes spillover from one microsystem to another.
    ///
    /// Spillover represents how stress or satisfaction in one domain
    /// affects another. The direction matters: work->home differs from home->work.
    ///
    /// # Arguments
    ///
    /// * `from` - Source microsystem ID
    /// * `to` - Target microsystem ID
    ///
    /// # Returns
    ///
    /// Spillover coefficient in range [0.0, 1.0], or 0.0 if either microsystem
    /// does not exist.
    #[must_use]
    pub fn get_spillover(&self, from: &MicrosystemId, to: &MicrosystemId) -> f64 {
        self.mesosystem_cache
            .get_spillover(from, to, &self.microsystems)
    }

    /// Computes role conflict between two microsystems.
    ///
    /// Role conflict is symmetric - the conflict between work and family
    /// is the same regardless of direction.
    ///
    /// # Arguments
    ///
    /// * `context_a` - First microsystem ID
    /// * `context_b` - Second microsystem ID
    ///
    /// # Returns
    ///
    /// Role conflict score in range [0.0, 1.0], or 0.0 if either microsystem
    /// does not exist.
    #[must_use]
    pub fn get_role_conflict(&self, context_a: &MicrosystemId, context_b: &MicrosystemId) -> f64 {
        self.mesosystem_cache
            .get_role_conflict(context_a, context_b, &self.microsystems)
    }

    /// Lists all active mesosystem linkages.
    ///
    /// Returns pairs of microsystem IDs that have interactions.
    #[must_use]
    pub fn list_linkages(&self) -> Vec<(MicrosystemId, MicrosystemId)> {
        self.mesosystem_cache.list_linkages(&self.microsystems)
    }

    // --- Bidirectional Context Processing ---

    /// Computes the aggregate social warmth across all microsystems.
    ///
    /// This is used in person-to-context shaping: high extraversion entities
    /// tend to increase social warmth in their environments.
    ///
    /// Returns the average warmth across all social microsystems,
    /// or 0.5 if no social microsystems exist.
    #[must_use]
    pub fn aggregate_social_warmth(&self) -> f64 {
        let social_contexts: Vec<_> = self
            .microsystems
            .values()
            .filter_map(|m| m.social())
            .collect();

        if social_contexts.is_empty() {
            0.5
        } else {
            let sum: f64 = social_contexts.iter().map(|s| s.warmth).sum();
            sum / social_contexts.len() as f64
        }
    }

    /// Computes the aggregate stress level across all microsystems.
    ///
    /// This is used for context-to-person effects: high aggregate stress
    /// can increase the person's stress levels.
    #[must_use]
    pub fn aggregate_stress(&self) -> f64 {
        if self.microsystems.is_empty() {
            return 0.0;
        }

        let total_stress: f64 = self.microsystems.values().map(|m| m.stress_level()).sum();
        total_stress / self.microsystems.len() as f64
    }

    /// Computes the aggregate hostility across all microsystems.
    ///
    /// Returns the average hostility across all microsystems, or 0.0 if none exist.
    #[must_use]
    pub fn aggregate_hostility(&self) -> f64 {
        if self.microsystems.is_empty() {
            return 0.0;
        }

        let total_hostility: f64 = self.microsystems.values().map(|m| m.hostility()).sum();
        total_hostility / self.microsystems.len() as f64
    }

    /// Computes the average family climate across family microsystems.
    ///
    /// Returns 0.5 if no family microsystems exist.
    #[must_use]
    fn average_family_climate(&self) -> f64 {
        let family_contexts: Vec<_> = self
            .microsystems
            .values()
            .filter_map(|m| m.family())
            .collect();

        if family_contexts.is_empty() {
            return 0.5;
        }

        let sum: f64 = family_contexts
            .iter()
            .map(|family| {
                let supportive = (family.warmth
                    + (1.0 - family.hostility)
                    + family.stability
                    + family.predictability
                    + family.cohesion)
                    / 5.0;
                supportive.clamp(0.0, 1.0)
            })
            .sum();

        sum / family_contexts.len() as f64
    }

    /// Computes context-dependent PAD bounds for emotional expression.
    #[must_use]
    pub(crate) fn compute_pad_bounds(&self) -> PadBounds {
        let threat_level = self.exosystem.threat_level;
        let cultural_restrictiveness = self.macrosystem.cultural_restrictiveness;
        let health_access = self.exosystem.health_system_access;
        let family_climate = self.average_family_climate();

        let valence_limit =
            ((1.0 - 0.6 * cultural_restrictiveness) * (0.8 + 0.2 * family_climate))
                .clamp(0.4, 1.0);
        let arousal_max = (1.0 - 0.2 * threat_level - 0.4 * (1.0 - health_access)).clamp(0.4, 1.0);
        let dominance_max =
            (1.0 - 0.7 * threat_level - 0.3 * (1.0 - family_climate)).clamp(0.3, 1.0);

        PadBounds {
            valence_min: -(valence_limit as f32),
            valence_max: valence_limit as f32,
            arousal_min: -1.0,
            arousal_max: arousal_max as f32,
            dominance_min: -1.0,
            dominance_max: dominance_max as f32,
        }
    }

    /// Applies person-to-context shaping effects.
    ///
    /// High extraversion increases warmth in social microsystems.
    /// This is called SECOND in the bidirectional processing order.
    ///
    /// # Arguments
    ///
    /// * `extraversion` - The entity's extraversion level (-1.0 to 1.0)
    /// * `conscientiousness` - The entity's conscientiousness level (-1.0 to 1.0)
    /// * `agreeableness` - The entity's agreeableness level (-1.0 to 1.0)
    /// * `neuroticism` - The entity's neuroticism level (-1.0 to 1.0)
    /// * `grievance` - The entity's grievance level (0.0 to 1.0)
    pub fn apply_person_to_context_shaping(
        &mut self,
        extraversion: f32,
        conscientiousness: f32,
        agreeableness: f32,
        neuroticism: f32,
        grievance: f32,
    ) {
        // High extraversion (> 0.3) increases social warmth
        if extraversion > 0.3 {
            let boost = f64::from(extraversion - 0.3) * 0.1; // Max ~0.07 boost

            for microsystem in self.microsystems.values_mut() {
                if let Some(social) = microsystem.social_mut() {
                    social.warmth = (social.warmth + boost).min(1.0);
                }
            }
        }

        // High conscientiousness (> 0.3) increases work structure
        if conscientiousness > 0.3 {
            let boost = f64::from(conscientiousness - 0.3) * 0.1;

            for microsystem in self.microsystems.values_mut() {
                if let Some(work) = microsystem.work_mut() {
                    work.role_clarity = (work.role_clarity + boost).min(1.0);
                    work.predictability = (work.predictability + boost * 0.5).min(1.0);
                }
            }
        }

        // High agreeableness (> 0.3) increases family warmth
        if agreeableness > 0.3 {
            let boost = f64::from(agreeableness - 0.3) * 0.1;

            for microsystem in self.microsystems.values_mut() {
                if let Some(family) = microsystem.family_mut() {
                    family.warmth = (family.warmth + boost).min(1.0);
                }
            }
        }

        // High neuroticism (> 0.3) reduces tolerance for instability
        if neuroticism > 0.3 {
            let penalty = f64::from(neuroticism - 0.3) * 0.1;

            for microsystem in self.microsystems.values_mut() {
                if let Some(work) = microsystem.work_mut() {
                    work.stability = (work.stability - penalty).max(0.0);
                    work.predictability = (work.predictability - penalty).max(0.0);
                }
                if let Some(family) = microsystem.family_mut() {
                    family.stability = (family.stability - penalty).max(0.0);
                    family.predictability = (family.predictability - penalty).max(0.0);
                }
            }
        }

        // High grievance (> 0.3) increases perceived hostility
        if grievance > 0.3 {
            let boost = f64::from(grievance - 0.3) * 0.1;

            for microsystem in self.microsystems.values_mut() {
                if let Some(work) = microsystem.work_mut() {
                    work.hostility = (work.hostility + boost).min(1.0);
                }
                if let Some(family) = microsystem.family_mut() {
                    family.hostility = (family.hostility + boost).min(1.0);
                }
                if let Some(social) = microsystem.social_mut() {
                    social.hostility = (social.hostility + boost).min(1.0);
                }
            }
        }
    }

    /// Applies person-to-context modulation for stimulation seeking/avoidance.
    ///
    /// * `boldness` - Tendency to seek arousal (0-1)
    /// * `sensitivity` - Tendency to reduce stimulation (0-1)
    /// * `sociability` - Tendency to seek social contact (0-1)
    pub fn apply_person_to_context_modulation(
        &mut self,
        boldness: f32,
        sensitivity: f32,
        sociability: f32,
    ) {
        let boldness = boldness.clamp(0.0, 1.0);
        let sensitivity = sensitivity.clamp(0.0, 1.0);
        let sociability = sociability.clamp(0.0, 1.0);

        if boldness > 0.3 {
            let boost = f64::from(boldness - 0.3) * 0.08;
            for microsystem in self.microsystems.values_mut() {
                if let Some(social) = microsystem.social_mut() {
                    social.interaction_profile.interaction_frequency =
                        (social.interaction_profile.interaction_frequency + boost).min(1.0);
                    social.group_standing = (social.group_standing + boost * 0.5).min(1.0);
                }
                if let Some(work) = microsystem.work_mut() {
                    work.cognitive_stimulation =
                        (work.cognitive_stimulation + boost * 0.6).min(1.0);
                }
            }
        }

        if sociability > 0.3 {
            let boost = f64::from(sociability - 0.3) * 0.06;
            for microsystem in self.microsystems.values_mut() {
                if let Some(social) = microsystem.social_mut() {
                    social.warmth = (social.warmth + boost).min(1.0);
                    social.interaction_profile.reciprocity_balance =
                        (social.interaction_profile.reciprocity_balance + boost * 0.5).min(1.0);
                }
            }
        }

        if sensitivity > 0.3 {
            let dampening = f64::from(sensitivity - 0.3) * 0.08;
            for microsystem in self.microsystems.values_mut() {
                if let Some(social) = microsystem.social_mut() {
                    social.hostility = (social.hostility - dampening).max(0.0);
                    social.interaction_profile.interaction_frequency =
                        (social.interaction_profile.interaction_frequency - dampening).max(0.0);
                }
                if let Some(work) = microsystem.work_mut() {
                    work.cognitive_stimulation =
                        (work.cognitive_stimulation - dampening).max(0.0);
                    work.predictability = (work.predictability + dampening * 0.4).min(1.0);
                }
                if let Some(family) = microsystem.family_mut() {
                    family.hostility = (family.hostility - dampening * 0.6).max(0.0);
                    family.predictability = (family.predictability + dampening * 0.4).min(1.0);
                }
            }
        }
    }

    /// Applies demand-characteristics shaping to microsystem climates.
    pub fn apply_demand_characteristics_shaping(&mut self, demand: &DemandCharacteristics) {
        let mut bias: f64 = 0.0;

        match demand.apparent_race() {
            ApparentRace::Marginalized => bias -= 0.15,
            ApparentRace::Privileged => bias += 0.05,
            ApparentRace::Unknown => {}
        }

        match demand.apparent_gender() {
            ApparentGender::Female => bias -= 0.04,
            ApparentGender::NonBinary => bias -= 0.06,
            ApparentGender::Male => {}
            ApparentGender::Unknown => {}
        }

        for trait_marker in demand.visible_traits() {
            match trait_marker {
                VisibleTrait::StigmatizedAppearance => bias -= 0.18,
                VisibleTrait::AttractivePresentation => bias += 0.12,
                VisibleTrait::VisibleDisability => bias -= 0.1,
                VisibleTrait::ApparentPoverty => bias -= 0.08,
            }
        }

        let bias = bias.clamp(-0.4, 0.2);
        if bias.abs() <= f64::EPSILON {
            return;
        }

        for microsystem in self.microsystems.values_mut() {
            if let Some(social) = microsystem.social_mut() {
                if bias < 0.0 {
                    social.hostility = (social.hostility + bias.abs()).min(1.0);
                    social.warmth = (social.warmth - bias.abs() * 0.6).max(0.0);
                    social.group_standing = (social.group_standing - bias.abs() * 0.5).max(0.0);
                } else {
                    social.warmth = (social.warmth + bias).min(1.0);
                    social.group_standing = (social.group_standing + bias * 0.6).min(1.0);
                }
            }

            if let Some(work) = microsystem.work_mut() {
                if bias < 0.0 {
                    work.hostility = (work.hostility + bias.abs() * 0.6).min(1.0);
                    work.warmth = (work.warmth - bias.abs() * 0.4).max(0.0);
                } else {
                    work.warmth = (work.warmth + bias * 0.3).min(1.0);
                }
            }

            if let Some(neighborhood) = microsystem.neighborhood_mut() {
                if bias < 0.0 {
                    neighborhood.hostility =
                        (neighborhood.hostility + bias.abs() * 0.5).min(1.0);
                    neighborhood.warmth =
                        (neighborhood.warmth - bias.abs() * 0.4).max(0.0);
                }
            }
        }
    }

    /// Computes context effects on person state.
    ///
    /// Returns adjustments to stress and loneliness based on context.
    /// This is called FIRST in the bidirectional processing order.
    ///
    /// # Arguments
    ///
    /// * `relationship_quality` - Average relationship quality (0.0 to 1.0)
    ///
    /// # Returns
    ///
    /// Tuple of (stress_adjustment, loneliness_adjustment) to be applied to state.
    #[must_use]
    pub fn compute_context_to_person_effects(&self, relationship_quality: f64) -> (f32, f32) {
        let aggregate_stress = self.aggregate_stress();
        let social_warmth = self.aggregate_social_warmth();
        let aggregate_hostility = self.aggregate_hostility();

        // Context stress increases person stress
        // Scaled by 0.1 to avoid overwhelming individual state
        let mut stress_adjustment = (aggregate_stress * 0.1) as f32;

        // Low social warmth + low relationship quality increases loneliness
        // Scaled modestly to avoid overwhelming individual state
        let loneliness_factor = (1.0 - social_warmth) * (1.0 - relationship_quality);
        let loneliness_adjustment = (loneliness_factor * 0.1) as f32;

        // Low relationship quality increases hostility perception
        let hostility_factor = aggregate_hostility * (1.0 - relationship_quality);
        stress_adjustment += (hostility_factor * 0.05) as f32;

        (stress_adjustment, loneliness_adjustment)
    }

    // --- Context Value Access ---

    /// Gets a context value by path.
    ///
    /// # Arguments
    ///
    /// * `path` - The context path to query
    ///
    /// # Returns
    ///
    /// The value at the path, or None if the path does not exist
    /// (e.g., microsystem ID not found).
    #[must_use]
    pub fn get(&self, path: &ContextPath) -> Option<f64> {
        match path {
            ContextPath::Microsystem(id, mpath) => {
                self.microsystems.get(id).map(|m| m.get_value(mpath))
            }
            ContextPath::Exosystem(epath) => Some(self.exosystem.get_value(epath)),
            ContextPath::Macrosystem(mpath) => Some(self.macrosystem.get_value(mpath)),
            ContextPath::Chronosystem(cpath) => Some(self.chronosystem.get_value(cpath)),
        }
    }

    /// Sets a context value by path.
    ///
    /// # Arguments
    ///
    /// * `path` - The context path to modify
    /// * `value` - The new value
    ///
    /// # Returns
    ///
    /// `true` if the value was set, `false` if the path does not exist
    /// (e.g., microsystem ID not found).
    pub fn set(&mut self, path: &ContextPath, value: f64) -> bool {
        match path {
            ContextPath::Microsystem(id, mpath) => {
                if let Some(m) = self.microsystems.get_mut(id) {
                    m.set_value(mpath, value);
                    // Note: We don't invalidate cache here - that happens at end of advance()
                    true
                } else {
                    false
                }
            }
            ContextPath::Exosystem(epath) => {
                self.exosystem.set_value(epath, value);
                true
            }
            ContextPath::Macrosystem(mpath) => {
                self.macrosystem.set_value(mpath, value);
                true
            }
            ContextPath::Chronosystem(cpath) => {
                self.chronosystem.set_value(cpath, value);
                true
            }
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::enums::{
        ApparentGender, ApparentRace, ChronosystemPath, ExosystemPath, MacrosystemPath,
        MicrosystemPath, VisibleTrait,
    };
    use crate::state::DemandCharacteristics;

    #[test]
    fn ecological_context_creation_default() {
        let context = EcologicalContext::default();
        assert!(context.is_empty());
        assert_eq!(context.microsystem_count(), 0);
    }

    #[test]
    fn ecological_context_new() {
        let context = EcologicalContext::new();
        assert!(context.is_empty());
    }

    #[test]
    fn add_microsystem() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();
        let work = Microsystem::new_work(WorkContext::default());

        context.add_microsystem(work_id.clone(), work);

        assert_eq!(context.microsystem_count(), 1);
        assert!(context.get_microsystem(&work_id).is_some());
    }

    #[test]
    fn add_multiple_microsystems() {
        let mut context = EcologicalContext::default();

        let work_id = MicrosystemId::new("work_acme").unwrap();
        let family_id = MicrosystemId::new("family_primary").unwrap();

        context.add_microsystem(
            work_id.clone(),
            Microsystem::new_work(WorkContext::default()),
        );
        context.add_microsystem(
            family_id.clone(),
            Microsystem::new_family(FamilyContext::default()),
        );

        assert_eq!(context.microsystem_count(), 2);
        assert!(context.get_microsystem(&work_id).is_some());
        assert!(context.get_microsystem(&family_id).is_some());
    }

    #[test]
    fn remove_microsystem() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();

        context.add_microsystem(
            work_id.clone(),
            Microsystem::new_work(WorkContext::default()),
        );
        assert_eq!(context.microsystem_count(), 1);

        let removed = context.remove_microsystem(&work_id);
        assert!(removed.is_some());
        assert_eq!(context.microsystem_count(), 0);
    }

    #[test]
    fn remove_nonexistent_microsystem() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();

        let removed = context.remove_microsystem(&work_id);
        assert!(removed.is_none());
    }

    #[test]
    fn list_microsystems_by_type() {
        let mut context = EcologicalContext::default();

        let work1 = MicrosystemId::new("work_acme").unwrap();
        let work2 = MicrosystemId::new("work_other").unwrap();
        let family_id = MicrosystemId::new("family_primary").unwrap();

        context.add_microsystem(work1.clone(), Microsystem::new_work(WorkContext::default()));
        context.add_microsystem(work2.clone(), Microsystem::new_work(WorkContext::default()));
        context.add_microsystem(
            family_id.clone(),
            Microsystem::new_family(FamilyContext::default()),
        );

        let work_ids = context.list_microsystems(MicrosystemType::Work);
        assert_eq!(work_ids.len(), 2);

        let family_ids = context.list_microsystems(MicrosystemType::Family);
        assert_eq!(family_ids.len(), 1);
    }

    #[test]
    fn get_microsystem_mut() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();
        let mut work = WorkContext::default();
        work.workload_stress = 0.3;

        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let microsystem = context.get_microsystem_mut(&work_id).unwrap();
        let work_ref = microsystem.work_mut().unwrap();
        work_ref.workload_stress = 0.8;

        let retrieved = context.get_microsystem(&work_id).unwrap();
        assert!((retrieved.work().unwrap().workload_stress - 0.8).abs() < f64::EPSILON);
    }

    #[test]
    fn microsystems_iter() {
        let mut context = EcologicalContext::default();

        let work_id = MicrosystemId::new("work_acme").unwrap();
        let family_id = MicrosystemId::new("family_primary").unwrap();

        context.add_microsystem(work_id, Microsystem::new_work(WorkContext::default()));
        context.add_microsystem(family_id, Microsystem::new_family(FamilyContext::default()));

        let count = context.microsystems_iter().count();
        assert_eq!(count, 2);
    }

    #[test]
    fn exosystem_accessor() {
        let context = EcologicalContext::default();
        let exo = context.exosystem();
        assert!(exo.resource_availability >= 0.0 && exo.resource_availability <= 1.0);
    }

    #[test]
    fn exosystem_mut_accessor() {
        let mut context = EcologicalContext::default();
        context.exosystem_mut().resource_availability = 0.9;
        assert!((context.exosystem().resource_availability - 0.9).abs() < f64::EPSILON);
    }

    #[test]
    fn macrosystem_accessor() {
        let context = EcologicalContext::default();
        let macro_ctx = context.macrosystem();
        let _ = macro_ctx.cultural_orientation;
    }

    #[test]
    fn macrosystem_mut_accessor() {
        let mut context = EcologicalContext::default();
        context.macrosystem_mut().cultural_stress = 0.4;
        assert!((context.macrosystem().cultural_stress - 0.4).abs() < f64::EPSILON);
    }

    #[test]
    fn chronosystem_accessor() {
        let context = EcologicalContext::default();
        let chrono = context.chronosystem();
        let _ = chrono.historical_period();
    }

    #[test]
    fn chronosystem_mut_accessor() {
        let mut context = EcologicalContext::default();
        context
            .chronosystem_mut()
            .historical_period_mut()
            .stability_level = 0.3;
        assert!(
            (context.chronosystem().historical_period().stability_level - 0.3).abs() < f64::EPSILON
        );
    }

    #[test]
    fn invalidate_mesosystem_cache() {
        let mut context = EcologicalContext::default();
        // Just verify it doesn't panic
        context.invalidate_mesosystem_cache();
    }

    #[test]
    fn context_path_macrosystem_query() {
        let context = EcologicalContext::default();
        let path = ContextPath::Macrosystem(MacrosystemPath::PowerDistance);
        let value = context.get(&path);
        assert!(value.is_some());
        assert!(value.unwrap() >= 0.0 && value.unwrap() <= 1.0);
    }

    #[test]
    fn context_path_exosystem_query() {
        let context = EcologicalContext::default();
        let path = ContextPath::Exosystem(ExosystemPath::ResourceAvailability);
        let value = context.get(&path);
        assert!(value.is_some());
    }

    #[test]
    fn context_path_chronosystem_query() {
        let context = EcologicalContext::default();
        let path = ContextPath::Chronosystem(ChronosystemPath::StabilityLevel);
        let value = context.get(&path);
        assert!(value.is_some());
    }

    #[test]
    fn context_path_microsystem_query() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();
        let mut work = WorkContext::default();
        work.workload_stress = 0.7;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let path = ContextPath::Microsystem(
            work_id,
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );
        let value = context.get(&path);
        assert!(value.is_some());
        assert!((value.unwrap() - 0.7).abs() < f64::EPSILON);
    }

    #[test]
    fn context_path_microsystem_query_nonexistent() {
        let context = EcologicalContext::default();
        let work_id = MicrosystemId::new("nonexistent").unwrap();
        let path = ContextPath::Microsystem(
            work_id,
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );
        let value = context.get(&path);
        assert!(value.is_none());
    }

    #[test]
    fn context_set_macrosystem() {
        let mut context = EcologicalContext::default();
        let path = ContextPath::Macrosystem(MacrosystemPath::CulturalStress);

        let result = context.set(&path, 0.6);
        assert!(result);

        let value = context.get(&path).unwrap();
        assert!((value - 0.6).abs() < f64::EPSILON);
    }

    #[test]
    fn context_set_exosystem() {
        let mut context = EcologicalContext::default();
        let path = ContextPath::Exosystem(ExosystemPath::InstitutionalSupport);

        let result = context.set(&path, 0.8);
        assert!(result);

        let value = context.get(&path).unwrap();
        assert!((value - 0.8).abs() < f64::EPSILON);
    }

    #[test]
    fn context_set_chronosystem() {
        let mut context = EcologicalContext::default();
        let path = ContextPath::Chronosystem(ChronosystemPath::ResourceScarcity);

        let result = context.set(&path, 0.4);
        assert!(result);

        let value = context.get(&path).unwrap();
        assert!((value - 0.4).abs() < f64::EPSILON);
    }

    #[test]
    fn context_set_microsystem() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_acme").unwrap();
        context.add_microsystem(
            work_id.clone(),
            Microsystem::new_work(WorkContext::default()),
        );

        let path = ContextPath::Microsystem(
            work_id.clone(),
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );

        let result = context.set(&path, 0.9);
        assert!(result);

        let value = context.get(&path).unwrap();
        assert!((value - 0.9).abs() < f64::EPSILON);
    }

    #[test]
    fn context_set_microsystem_nonexistent() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("nonexistent").unwrap();
        let path = ContextPath::Microsystem(
            work_id,
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );

        let result = context.set(&path, 0.9);
        assert!(!result);
    }

    #[test]
    fn clone_and_equality() {
        let context1 = EcologicalContext::default();
        let context2 = context1.clone();
        assert_eq!(context1, context2);
    }

    #[test]
    fn debug_format() {
        let context = EcologicalContext::default();
        let debug = format!("{:?}", context);
        assert!(debug.contains("EcologicalContext"));
    }

    #[test]
    fn microsystem_multiple_contexts_aggregate() {
        let mut context = EcologicalContext::default();

        // Add multiple microsystems of different types
        let work_id = MicrosystemId::new("work_primary").unwrap();
        let family_id = MicrosystemId::new("family_primary").unwrap();
        let social_id = MicrosystemId::new("social_friends").unwrap();

        context.add_microsystem(work_id, Microsystem::new_work(WorkContext::default()));
        context.add_microsystem(family_id, Microsystem::new_family(FamilyContext::default()));
        context.add_microsystem(social_id, Microsystem::new_social(SocialContext::default()));

        assert_eq!(context.microsystem_count(), 3);
    }

    #[test]
    fn microsystem_id_identifies_instance_path_identifies_property() {
        let mut context = EcologicalContext::default();

        // Create two work contexts with different stress levels
        let work1_id = MicrosystemId::new("work_job1").unwrap();
        let work2_id = MicrosystemId::new("work_job2").unwrap();

        let mut work1 = WorkContext::default();
        work1.workload_stress = 0.3;
        let mut work2 = WorkContext::default();
        work2.workload_stress = 0.8;

        context.add_microsystem(work1_id.clone(), Microsystem::new_work(work1));
        context.add_microsystem(work2_id.clone(), Microsystem::new_work(work2));

        // MicrosystemId selects WHICH microsystem
        // MicrosystemPath selects WHICH dimension
        let path1 = ContextPath::Microsystem(
            work1_id,
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );
        let path2 = ContextPath::Microsystem(
            work2_id,
            MicrosystemPath::Work(crate::enums::WorkPath::WorkloadStress),
        );

        let value1 = context.get(&path1).unwrap();
        let value2 = context.get(&path2).unwrap();

        assert!((value1 - 0.3).abs() < f64::EPSILON);
        assert!((value2 - 0.8).abs() < f64::EPSILON);
    }

    // --- Additional coverage tests for mesosystem methods ---

    #[test]
    fn mesosystem_cache_accessor() {
        let context = EcologicalContext::default();
        let cache = context.mesosystem_cache();
        assert!(!cache.is_valid());
    }

    #[test]
    fn mesosystem_state_accessor_recomputes() {
        let mut context = EcologicalContext::default();
        assert_eq!(
            context.mesosystem_state_cached(),
            &MesosystemState::default()
        );

        let mut work = WorkContext::default();
        work.role_clarity = 0.2;
        work.predictability = 0.3;
        work.warmth = 0.2;
        work.hostility = 0.1;
        work.workload_stress = 0.8;
        work.interaction_profile.interaction_frequency = 0.8;
        context.add_microsystem(
            MicrosystemId::new("work").unwrap(),
            Microsystem::new_work(work),
        );

        let mut social = SocialContext::default();
        social.warmth = 0.8;
        social.predictability = 0.9;
        social.hostility = 0.1;
        social.interaction_profile.interaction_frequency = 0.6;
        context.add_microsystem(
            MicrosystemId::new("social").unwrap(),
            Microsystem::new_social(social),
        );

        let state = context.mesosystem_state();
        assert!((state.work_social_conflict - 0.3).abs() < f64::EPSILON);
        assert!(
            (context.mesosystem_state_cached().work_social_conflict - 0.3).abs() < f64::EPSILON
        );
    }

    #[test]
    fn ecological_context_get_spillover() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let family_id = MicrosystemId::new("family").unwrap();

        let mut work = WorkContext::default();
        work.workload_stress = 0.8;
        work.interaction_profile.interaction_frequency = 0.7;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let mut family = FamilyContext::default();
        family.predictability = 0.3;
        family.stability = 0.3;
        context.add_microsystem(family_id.clone(), Microsystem::new_family(family));

        let spillover = context.get_spillover(&work_id, &family_id);
        assert!(spillover >= 0.0 && spillover <= 1.0);
    }

    #[test]
    fn ecological_context_get_role_conflict() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let family_id = MicrosystemId::new("family").unwrap();

        let mut work = WorkContext::default();
        work.workload_stress = 0.8;
        work.interaction_profile.interaction_frequency = 0.8;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let mut family = FamilyContext::default();
        family.caregiving_burden = 0.8;
        family.interaction_profile.interaction_frequency = 0.8;
        context.add_microsystem(family_id.clone(), Microsystem::new_family(family));

        let conflict = context.get_role_conflict(&work_id, &family_id);
        assert!(conflict >= 0.0 && conflict <= 1.0);
    }

    #[test]
    fn ecological_context_list_linkages() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let family_id = MicrosystemId::new("family").unwrap();

        context.add_microsystem(
            work_id.clone(),
            Microsystem::new_work(WorkContext::default()),
        );
        context.add_microsystem(
            family_id.clone(),
            Microsystem::new_family(FamilyContext::default()),
        );

        let linkages = context.list_linkages();
        // Should have 1 linkage between work and family
        assert_eq!(linkages.len(), 1);
    }

    // --- Bidirectional processing tests ---

    #[test]
    fn aggregate_social_warmth_no_social_microsystems() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        context.add_microsystem(work_id, Microsystem::new_work(WorkContext::default()));

        // No social microsystems -> returns default 0.5
        let warmth = context.aggregate_social_warmth();
        assert!((warmth - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn aggregate_social_warmth_with_social_microsystems() {
        let mut context = EcologicalContext::default();

        let social1_id = MicrosystemId::new("social1").unwrap();
        let social2_id = MicrosystemId::new("social2").unwrap();

        let mut social1 = SocialContext::default();
        social1.warmth = 0.8;
        let mut social2 = SocialContext::default();
        social2.warmth = 0.4;

        context.add_microsystem(social1_id, Microsystem::new_social(social1));
        context.add_microsystem(social2_id, Microsystem::new_social(social2));

        let warmth = context.aggregate_social_warmth();
        // (0.8 + 0.4) / 2 = 0.6
        assert!((warmth - 0.6).abs() < f64::EPSILON);
    }

    #[test]
    fn aggregate_stress_empty_context() {
        let context = EcologicalContext::default();
        let stress = context.aggregate_stress();
        assert!((stress - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn aggregate_stress_with_microsystems() {
        let mut context = EcologicalContext::default();

        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.workload_stress = 0.8;
        context.add_microsystem(work_id, Microsystem::new_work(work));

        let stress = context.aggregate_stress();
        // Work stress = 0.8
        assert!(stress > 0.0 && stress <= 1.0);
    }

    #[test]
    fn aggregate_hostility_empty_context() {
        let context = EcologicalContext::default();
        let hostility = context.aggregate_hostility();
        assert!((hostility - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn aggregate_hostility_with_microsystems() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.hostility = 0.7;
        context.add_microsystem(work_id, Microsystem::new_work(work));

        let hostility = context.aggregate_hostility();
        assert!((hostility - 0.7).abs() < f64::EPSILON);
    }

    #[test]
    fn compute_pad_bounds_defaults_without_family() {
        let context = EcologicalContext::default();
        let bounds = context.compute_pad_bounds();

        assert!(bounds.valence_max <= 1.0 && bounds.valence_max >= 0.4);
        assert!(bounds.arousal_max <= 1.0 && bounds.arousal_max >= 0.4);
        assert!(bounds.dominance_max <= 1.0 && bounds.dominance_max >= 0.3);
    }

    #[test]
    fn compute_pad_bounds_clamps_for_threat_and_restrictiveness() {
        let mut context = EcologicalContext::default();
        let family_id = MicrosystemId::new("family").unwrap();

        let mut family = FamilyContext::default();
        family.warmth = 0.1;
        family.hostility = 0.9;
        family.stability = 0.1;
        family.predictability = 0.1;
        context.add_microsystem(family_id, Microsystem::new_family(family));

        context.exosystem.threat_level = 1.0;
        context.exosystem.health_system_access = 0.0;
        context.macrosystem.cultural_restrictiveness = 1.0;

        let bounds = context.compute_pad_bounds();

        assert!((bounds.dominance_max - 0.3).abs() < f32::EPSILON);
        assert!((bounds.valence_max - 0.4).abs() < f32::EPSILON);
        assert!((bounds.arousal_max - 0.4).abs() < f32::EPSILON);
    }

    #[test]
    fn apply_person_to_context_shaping_high_extraversion() {
        let mut context = EcologicalContext::default();

        let social_id = MicrosystemId::new("social").unwrap();
        let mut social = SocialContext::default();
        social.warmth = 0.5;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        // High extraversion should boost warmth
        context.apply_person_to_context_shaping(0.7, 0.0, 0.0, 0.0, 0.0);

        let updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();
        assert!(updated.warmth > 0.5);
    }

    #[test]
    fn apply_person_to_context_shaping_low_extraversion() {
        let mut context = EcologicalContext::default();

        let social_id = MicrosystemId::new("social").unwrap();
        let mut social = SocialContext::default();
        social.warmth = 0.5;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        // Low extraversion should not change warmth
        context.apply_person_to_context_shaping(0.2, 0.0, 0.0, 0.0, 0.0);

        let updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();
        assert!((updated.warmth - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn apply_person_to_context_shaping_skips_non_social_microsystems() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        context.add_microsystem(work_id.clone(), Microsystem::new_work(WorkContext::default()));

        context.apply_person_to_context_shaping(0.8, 0.0, 0.0, 0.0, 0.0);

        let work = context.get_microsystem(&work_id).unwrap();
        assert!(work.social().is_none());
    }

    #[test]
    fn apply_person_to_context_modulation_boldness_increases_social_frequency() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let mut social = SocialContext::default();
        social.interaction_profile.interaction_frequency = 0.4;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        context.apply_person_to_context_modulation(0.8, 0.0, 0.0);

        let updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();
        assert!(updated.interaction_profile.interaction_frequency > 0.4);
    }

    #[test]
    fn apply_person_to_context_modulation_sensitivity_dampens_stimulation() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.cognitive_stimulation = 0.7;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_modulation(0.0, 0.8, 0.0);

        let updated = context
            .get_microsystem(&work_id)
            .unwrap()
            .work()
            .unwrap();
        assert!(updated.cognitive_stimulation < 0.7);
    }

    #[test]
    fn apply_demand_characteristics_shaping_increases_hostility_for_stigma() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let mut social = SocialContext::default();
        social.hostility = 0.3;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        let demand = DemandCharacteristics::new(
            22,
            ApparentGender::Female,
            ApparentRace::Marginalized,
            vec![VisibleTrait::StigmatizedAppearance],
        );

        context.apply_demand_characteristics_shaping(&demand);

        let updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();
        assert!(updated.hostility > 0.3);
    }

    #[test]
    fn high_conscientiousness_increases_work_clarity() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.role_clarity = 0.4;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_shaping(0.0, 0.7, 0.0, 0.0, 0.0);

        let updated = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated.role_clarity > 0.4);
    }

    #[test]
    fn conscientiousness_ignores_non_work_microsystems() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let mut social = SocialContext::default();
        social.warmth = 0.6;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        context.apply_person_to_context_shaping(0.0, 0.7, 0.0, 0.0, 0.0);

        let updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();
        assert!((updated.warmth - 0.6).abs() < f64::EPSILON);
    }

    #[test]
    fn high_neuroticism_reduces_stability_tolerance() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.stability = 0.8;
        work.predictability = 0.8;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_shaping(0.0, 0.0, 0.0, 0.7, 0.0);

        let updated = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated.stability < 0.8);
        assert!(updated.predictability < 0.8);
    }

    #[test]
    fn neuroticism_and_grievance_affect_family_context() {
        let mut context = EcologicalContext::default();
        let family_id = MicrosystemId::new("family").unwrap();
        let mut family = FamilyContext::default();
        family.stability = 0.8;
        family.predictability = 0.8;
        family.hostility = 0.2;
        context.add_microsystem(family_id.clone(), Microsystem::new_family(family));

        context.apply_person_to_context_shaping(0.0, 0.0, 0.0, 0.7, 0.8);

        let updated = context
            .get_microsystem(&family_id)
            .unwrap()
            .family()
            .unwrap();
        assert!(updated.stability < 0.8);
        assert!(updated.predictability < 0.8);
        assert!(updated.hostility > 0.2);
    }

    #[test]
    fn high_agreeableness_increases_family_warmth() {
        let mut context = EcologicalContext::default();
        let family_id = MicrosystemId::new("family").unwrap();
        let mut family = FamilyContext::default();
        family.warmth = 0.4;
        context.add_microsystem(family_id.clone(), Microsystem::new_family(family));

        context.apply_person_to_context_shaping(0.0, 0.0, 0.7, 0.0, 0.0);

        let updated = context
            .get_microsystem(&family_id)
            .unwrap()
            .family()
            .unwrap();
        assert!(updated.warmth > 0.4);
    }

    #[test]
    fn agreeableness_ignores_non_family_microsystems() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.role_clarity = 0.4;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_shaping(0.0, 0.0, 0.7, 0.0, 0.0);

        let updated = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!((updated.role_clarity - 0.4).abs() < f64::EPSILON);
    }

    #[test]
    fn high_grievance_increases_perceived_hostility() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let social_id = MicrosystemId::new("social").unwrap();

        let mut work = WorkContext::default();
        work.hostility = 0.2;
        let mut social = SocialContext::default();
        social.hostility = 0.2;

        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        context.apply_person_to_context_shaping(0.0, 0.0, 0.0, 0.0, 0.8);

        let work_updated = context.get_microsystem(&work_id).unwrap().work().unwrap();
        let social_updated = context
            .get_microsystem(&social_id)
            .unwrap()
            .social()
            .unwrap();

        assert!(work_updated.hostility > 0.2);
        assert!(social_updated.hostility > 0.2);
    }

    #[test]
    fn compute_context_to_person_effects_high_stress() {
        let mut context = EcologicalContext::default();

        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.workload_stress = 0.9;
        context.add_microsystem(work_id, Microsystem::new_work(work));

        let (stress_adj, loneliness_adj) = context.compute_context_to_person_effects(0.5);

        // High context stress should produce positive stress adjustment
        assert!(stress_adj > 0.0);
        // Loneliness adjustment depends on social warmth and relationship quality
        assert!(loneliness_adj >= 0.0);
    }

    #[test]
    fn low_relationship_quality_increases_context_hostility() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();
        let mut work = WorkContext::default();
        work.hostility = 0.8;
        context.add_microsystem(work_id, Microsystem::new_work(work));

        let (high_quality_stress, _) = context.compute_context_to_person_effects(0.9);
        let (low_quality_stress, _) = context.compute_context_to_person_effects(0.2);

        assert!(low_quality_stress > high_quality_stress);
    }

    #[test]
    fn compute_context_to_person_effects_empty_context() {
        let context = EcologicalContext::default();

        let (stress_adj, loneliness_adj) = context.compute_context_to_person_effects(0.5);

        // Empty context should produce minimal adjustments
        assert!((stress_adj - 0.0).abs() < 0.01);
        // With 0.5 relationship quality and 0.5 default social warmth
        // loneliness_factor = 0.5 * 0.5 = 0.25, adjustment = 0.025
        assert!(loneliness_adj < 0.05);
    }


    #[test]
    fn ecological_context_entity_integration() {
        // Entity.context field holds EcologicalContext
        use crate::entity::EntityBuilder;
        use crate::enums::Species;

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        // Verify entity has context field accessible
        let context = entity.context();

        // Context is EcologicalContext type - verify it's functional
        assert!(context.is_empty()); // No microsystems initially
        assert_eq!(context.microsystem_count(), 0);

        // Verify all layers are accessible
        let _ = context.exosystem();
        let _ = context.macrosystem();
        let _ = context.chronosystem();
        let _ = context.mesosystem_cache();

        // Verify mutable access works
        let mut entity = entity;
        let work_id = MicrosystemId::new("work_test").unwrap();
        entity.context_mut().add_microsystem(
            work_id.clone(),
            Microsystem::new_work(WorkContext::default()),
        );

        assert_eq!(entity.context().microsystem_count(), 1);
        assert!(entity.context().get_microsystem(&work_id).is_some());
    }

    #[test]
    fn person_modulation_boosts_social_and_work_with_boldness() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let work_id = MicrosystemId::new("work").unwrap();

        let mut social = SocialContext::default();
        social.interaction_profile.interaction_frequency = 0.4;
        social.group_standing = 0.4;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        let mut work = WorkContext::default();
        work.cognitive_stimulation = 0.4;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_modulation(0.8, 0.0, 0.0);

        let updated_social = context.get_microsystem(&social_id).unwrap().social().unwrap();
        assert!(updated_social.interaction_profile.interaction_frequency > 0.4);
        assert!(updated_social.group_standing > 0.4);

        let updated_work = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated_work.cognitive_stimulation > 0.4);
    }

    #[test]
    fn person_modulation_increases_warmth_and_reciprocity_with_sociability() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();

        let mut social = SocialContext::default();
        social.warmth = 0.4;
        social.interaction_profile.reciprocity_balance = 0.4;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        context.apply_person_to_context_modulation(0.0, 0.0, 0.8);

        let updated_social = context.get_microsystem(&social_id).unwrap().social().unwrap();
        assert!(updated_social.warmth > 0.4);
        assert!(updated_social.interaction_profile.reciprocity_balance > 0.4);
    }

    #[test]
    fn person_modulation_sociability_ignores_non_social_microsystems() {
        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work").unwrap();

        let mut work = WorkContext::default();
        work.predictability = 0.6;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        context.apply_person_to_context_modulation(0.0, 0.0, 0.8);

        let updated_work = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!((updated_work.predictability - 0.6).abs() < f64::EPSILON);
    }

    #[test]
    fn person_modulation_sensitivity_dampens_social_work_and_family() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let work_id = MicrosystemId::new("work").unwrap();
        let family_id = MicrosystemId::new("family").unwrap();

        let mut social = SocialContext::default();
        social.hostility = 0.6;
        social.interaction_profile.interaction_frequency = 0.6;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        let mut work = WorkContext::default();
        work.cognitive_stimulation = 0.7;
        work.predictability = 0.4;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let mut family = FamilyContext::default();
        family.hostility = 0.6;
        family.predictability = 0.4;
        context.add_microsystem(family_id.clone(), Microsystem::new_family(family));

        context.apply_person_to_context_modulation(0.0, 0.8, 0.0);

        let updated_social = context.get_microsystem(&social_id).unwrap().social().unwrap();
        assert!(updated_social.hostility < 0.6);
        assert!(updated_social.interaction_profile.interaction_frequency < 0.6);

        let updated_work = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated_work.cognitive_stimulation < 0.7);
        assert!(updated_work.predictability > 0.4);

        let updated_family = context.get_microsystem(&family_id).unwrap().family().unwrap();
        assert!(updated_family.hostility < 0.6);
        assert!(updated_family.predictability > 0.4);
    }

    #[test]
    fn demand_characteristics_negative_bias_applies() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let work_id = MicrosystemId::new("work").unwrap();
        let neighborhood_id = MicrosystemId::new("neighborhood").unwrap();

        let mut social = SocialContext::default();
        social.hostility = 0.2;
        social.warmth = 0.6;
        social.group_standing = 0.5;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        let mut work = WorkContext::default();
        work.hostility = 0.1;
        work.warmth = 0.6;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let mut neighborhood = NeighborhoodContext::default();
        neighborhood.hostility = 0.1;
        neighborhood.warmth = 0.7;
        context.add_microsystem(neighborhood_id.clone(), Microsystem::new_neighborhood(neighborhood));

        let demand = DemandCharacteristics::new(
            28,
            ApparentGender::NonBinary,
            ApparentRace::Marginalized,
            vec![
                VisibleTrait::StigmatizedAppearance,
                VisibleTrait::ApparentPoverty,
                VisibleTrait::VisibleDisability,
            ],
        );

        context.apply_demand_characteristics_shaping(&demand);

        let updated_social = context.get_microsystem(&social_id).unwrap().social().unwrap();
        assert!(updated_social.hostility > 0.2);
        assert!(updated_social.warmth < 0.6);
        assert!(updated_social.group_standing < 0.5);

        let updated_work = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated_work.hostility > 0.1);
        assert!(updated_work.warmth < 0.6);

        let updated_neighborhood = context
            .get_microsystem(&neighborhood_id)
            .unwrap()
            .neighborhood()
            .unwrap();
        assert!(updated_neighborhood.hostility > 0.1);
        assert!(updated_neighborhood.warmth < 0.7);
    }

    #[test]
    fn demand_characteristics_positive_bias_applies() {
        let mut context = EcologicalContext::default();
        let social_id = MicrosystemId::new("social").unwrap();
        let work_id = MicrosystemId::new("work").unwrap();

        let mut social = SocialContext::default();
        social.warmth = 0.4;
        social.group_standing = 0.4;
        context.add_microsystem(social_id.clone(), Microsystem::new_social(social));

        let mut work = WorkContext::default();
        work.warmth = 0.4;
        context.add_microsystem(work_id.clone(), Microsystem::new_work(work));

        let demand = DemandCharacteristics::new(
            35,
            ApparentGender::Male,
            ApparentRace::Privileged,
            vec![VisibleTrait::AttractivePresentation],
        );

        context.apply_demand_characteristics_shaping(&demand);

        let updated_social = context.get_microsystem(&social_id).unwrap().social().unwrap();
        assert!(updated_social.warmth > 0.4);
        assert!(updated_social.group_standing > 0.4);

        let updated_work = context.get_microsystem(&work_id).unwrap().work().unwrap();
        assert!(updated_work.warmth > 0.4);
    }

    #[test]
    fn demand_characteristics_positive_bias_skips_neighborhood_changes() {
        let mut context = EcologicalContext::default();
        let neighborhood_id = MicrosystemId::new("neighborhood").unwrap();

        let mut neighborhood = NeighborhoodContext::default();
        neighborhood.hostility = 0.2;
        neighborhood.warmth = 0.7;
        context.add_microsystem(neighborhood_id.clone(), Microsystem::new_neighborhood(neighborhood));

        let demand = DemandCharacteristics::new(
            40,
            ApparentGender::Male,
            ApparentRace::Privileged,
            vec![VisibleTrait::AttractivePresentation],
        );

        context.apply_demand_characteristics_shaping(&demand);

        let updated_neighborhood = context
            .get_microsystem(&neighborhood_id)
            .unwrap()
            .neighborhood()
            .unwrap();
        assert!((updated_neighborhood.hostility - 0.2).abs() < f64::EPSILON);
        assert!((updated_neighborhood.warmth - 0.7).abs() < f64::EPSILON);
    }
}