bevy_society 0.9.0

Living societies for Bevy: personalities, moods, needs, memories, relationships, opinions, rumors, reputation and factions; utility-AI daily lives; Rhai triggers; dialogue through bevy_speech_bubbles.
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
//! Authored definitions: the data a host hands in (needs, signals, topics, deeds, factions,
//! activities, interactions, triggers, conversation rules and node effects). `DefsFile` is the
//! RON-shaped input; `SocietyDefs` is the compiled resource the simulation reads, with ids and Rhai
//! scripts resolved. The crate never reads a file: the host passes in text it has already loaded.

use std::collections::{HashMap, HashSet};
use std::fmt;

use bevy::ecs::entity::Entity;
use bevy::ecs::query::With;
use bevy::ecs::resource::Resource;
use bevy::ecs::system::{Commands, Query, Res};
use bevy::log::error;
use bevy::reflect::Reflect;
use serde::{Deserialize, Serialize};

use crate::beliefs::{Opinion, Opinions};
use crate::core::{Person, SocietySettings};
use crate::groups::Memberships;
use crate::mind::{EmotionKind, Needs, Signals, Trait};
use crate::model::curves::Curve;
use crate::relationships::TieLabel;
use crate::script::{CompiledScript, ScriptCompiler, ScriptId};

/// Whether the `fields` feature is on. Field inputs and gradient targets need it.
const FIELDS_ENABLED: bool = cfg!(feature = "fields");

/// Name of the reserved activity every compiled `SocietyDefs` contains. Persons with no valid
/// option pick it for one game-hour.
pub const IDLE_ACTIVITY: ActivityId = ActivityId(0);

const IDLE: &str = "idle";

/// Index of a need, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NeedId(pub u16);

/// Index of a host signal, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
pub struct SignalId(pub u16);

/// Index of a good, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GoodId(pub u16);

/// Index of a skill, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SkillId(pub u16);

/// Index of a topic, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TopicId(pub u16);

/// Index of a deed, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DeedId(pub u16);

/// Index of a faction, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FactionId(pub u16);

/// Index of an activity, in definition order. `IDLE_ACTIVITY` is always `ActivityId(0)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ActivityId(pub u16);

/// Index of an interaction, in definition order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InteractionId(pub u16);

/// Everything a host hands in, as one RON document. Every list is optional.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct DefsFile {
    /// Needs persons carry; they decay per game-day.
    pub needs: Vec<NeedDef>,
    /// Signals the host writes and the crate only reads.
    pub signals: Vec<SignalDef>,
    /// Named capabilities, each read from one personality trait.
    pub skills: Vec<SkillDef>,
    /// Tradeable quantities persons hold.
    pub goods: Vec<GoodDef>,
    /// Opinion topics.
    pub topics: Vec<TopicDef>,
    /// Deeds that witnesses judge and that can become rumors.
    pub deeds: Vec<DeedDef>,
    /// Factions (groups persons belong to).
    pub factions: Vec<FactionDef>,
    /// Things persons do.
    pub activities: Vec<ActivityDef>,
    /// Social exchanges between two persons.
    pub interactions: Vec<InteractionDef>,
    /// Rhai rules that fire on simulation events.
    pub triggers: Vec<TriggerDef>,
    /// Conversation selection rules for `TalkTo`.
    pub conversations: Vec<ConversationRuleDef>,
    /// Scripts run when a dialogue node is entered.
    pub node_effects: Vec<NodeEffectDef>,
}

/// A need. Level 1 is satisfied, 0 is desperate.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NeedDef {
    /// Unique name.
    pub id: String,
    /// Loss per game-day, 0 or more.
    #[serde(default)]
    pub decay_per_day: f32,
    /// Starting level.
    #[serde(default = "one")]
    pub initial: f32,
}

/// A host signal. The crate never changes its value; the host sets it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignalDef {
    /// Unique name.
    pub id: String,
}

/// Which personality axis a skill draws on.
///
/// **A design default, measured.** Acemoglu & Autor (2010, DOI `10.3386/w16082`) separate a **task** ("a
/// unit of work activity that produces output") from a **skill** ("a worker's endowment of capabilities for
/// performing various tasks"), and that is the distinction this file needs: an activity is the task, and
/// this is the endowment. The three-way grouping of Big Five traits onto kinds of work is the crate's own
/// choice — no paper in the corpus assigns traits to trades — and each group reads exactly one trait so
/// that the mapping is inspectable in one place.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SkillGroup {
    /// Diligence: scales with conscientiousness.
    Craft,
    /// Invention: scales with openness.
    Creative,
    /// Dealing with people: scales with extraversion.
    Social,
}

impl SkillGroup {
    /// The trait this group reads, as an index into [`Personality::values`](crate::Personality).
    pub fn trait_of(self) -> crate::defs::Trait {
        match self {
            Self::Craft => Trait::Conscientiousness,
            Self::Creative => Trait::Openness,
            Self::Social => Trait::Extraversion,
        }
    }
}

/// A tradeable quantity. Not a currency: there is no exchange rate and no `Good` is worth another.
///
/// "Meat and honey are meticulously shared among the Ache, but goods purchased by money are not" —
/// Henrich et al. 2005 (DOI `10.1017/S0140525X05000142`). A good is a level a person holds, nothing more.
///
/// **`initial` is what a person holds when they are created**, the way [`NeedDef::initial`] is the level a need
/// starts at. A society that begins with every larder empty has a transient the running society does not:
/// the starter pack's village held no bread for its first 22 game-hours and spent the second game-day with 39 %
/// of its person-ticks at `food` below 0.05 (`docs/loop/runs/2026-10-30-27/research.md`). Starting in a state
/// typical of the running system is the standard remedy for that initialization bias (Murray & Kelton 1988, DOI
/// `10.1145/318123.318252`), and a household holding a store is the typical state (Winterhalder et al. 2015, DOI
/// `10.1179/1749631415y.0000000025`). The default `0.0` is what every pack that omits the field has always had.
/// A value above `Tuning::stock_ceiling` is held at the ceiling.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GoodDef {
    /// Unique name.
    pub id: String,
    /// Units of this good a new person holds, 0 or more.
    #[serde(default)]
    pub initial: f32,
}

/// A named capability. Level comes from personality, not from stored state.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SkillDef {
    /// Unique name.
    pub id: String,
    /// Which trait the level is read from.
    pub group: SkillGroup,
}

/// An opinion topic.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TopicDef {
    /// Unique name.
    pub id: String,
}

/// A deed a person can do to another. Witnesses judge it by their opinion of `topic`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeedDef {
    /// Unique name.
    pub id: String,
    /// The topic a witness's opinion judges the deed by.
    pub topic: String,
    /// Harm in [-1, 1]; positive helps the patient.
    pub harm: f32,
}

/// A faction.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FactionDef {
    /// Unique name.
    pub id: String,
    /// Extra affinity weight for members toward co-members (Tajfel et al. 1971, DOI 10.1002/ejsp.2420010202).
    #[serde(default = "default_ingroup_bias")]
    pub ingroup_bias: f32,
}

/// A rank an activity takes **while one need is low**, and only then.
///
/// Maslow (1943, DOI 10.1037/h0054346): "the most prepotent goal will monopolize consciousness ... The less
/// prepotent needs are minimized, even forgotten or denied", and a satisfied need "is not a motivator". The
/// utility-AI form is the bucket: on The Sims "motives are bucketed based on their utility value ... a starving
/// Sim will never even consider watching TV unless they fail to find anything that can solve their hunger"
/// (Graham, Game AI Pro 1 ch. 9, corpus doc `gameaipro1-ch09-introduction-utility-theory`), which is dual-utility
/// reasoning whose rank follows the situation (Dill, Game AI Pro 2 ch. 3).
///
/// While the actor's `need` is under `below`, the activity's rank is the larger of its own and `rank`, so it is
/// in the tier that wins over every option of a lower rank — and when it has no viable option (no table to eat
/// at, a place just failed), the person falls through to the lower tiers as before. Above `below` the activity
/// is exactly what it was. Nothing in the crate names a need or a number: the pack says which activity answers
/// which need and how low is low.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UrgentDef {
    /// The need that makes the activity urgent.
    pub need: String,
    /// The level under which it is urgent, in `(0, 1]`.
    pub below: f32,
    /// The rank taken while urgent; must exceed the activity's own `rank`.
    pub rank: u8,
}

/// Something a person can do, chosen by utility scoring.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ActivityDef {
    /// Unique name.
    pub id: String,
    /// Where the activity happens.
    pub target: ActivityTarget,
    /// How long the activity lasts once arrived, in game-hours.
    pub duration_hours: f32,
    /// Dual-utility rank; the highest rank with any option above zero wins (Dill 2015).
    #[serde(default)]
    pub rank: u8,
    /// A higher rank for as long as one need is low (see [`UrgentDef`]); `None` keeps `rank` always.
    #[serde(default)]
    pub urgent: Option<UrgentDef>,
    /// Whether a person doing this cannot be approached. From the moment they arrive at it they are in
    /// nobody's `near` list, so no one chooses them as the target of a `Person` activity (and they are not a
    /// `Distance` neighbour), and an activity still walking toward them ends (`completed: false`). Someone
    /// still walking to it is on their way, not yet unavailable. `false` by default.
    ///
    /// This is what `sleep` needs once people keep their own hours ([`Chronotype`](crate::Chronotype)): an
    /// owl awake at 01:00 stands among sleeping neighbours, and without the flag the village would
    /// compliment its sleepers. It is the per-activity form of the rule [`Dormant`](crate::Dormant) states
    /// per person (out of perception, no exchanges).
    #[serde(default)]
    pub unavailable: bool,
    /// Multiplies the option's score.
    #[serde(default = "one")]
    pub weight: f32,
    /// Considerations whose product is the option's score.
    #[serde(default)]
    pub considerations: Vec<Consideration>,
    /// Needs this activity raises per game-hour while arrived.
    #[serde(default)]
    pub satisfies: Vec<(String, f32)>,
    /// Interaction performed on arrival; requires a `Person` target.
    pub interaction: Option<String>,
    /// Goods this activity makes, **per completed use**, with the amount.
    ///
    /// Per use, not per game-hour: a stock is a quantity, while `satisfies` is the rate-shaped field. A
    /// task that is interrupted produces nothing, which is the same rule `satisfies` follows.
    #[serde(default)]
    pub produces: Vec<(String, f32)>,
    /// Goods this activity uses up, per completed use. A person without them still does the activity —
    /// a good changes what someone prefers, never what they may do.
    #[serde(default)]
    pub consumes: Vec<(String, f32)>,
    /// The skill this activity is a **task** for, when it is one.
    ///
    /// A task is "a unit of work activity that produces output" and a skill is "a worker's endowment of
    /// capabilities for performing various tasks" — Acemoglu & Autor 2010 (DOI `10.3386/w16082`). Naming a
    /// skill here does **not** gate the activity: an unskilled person can still choose it, at a lower score
    /// if a consideration reads `Skill(..)`. That is comparative advantage rather than assignment, which is
    /// the paper's own point ("the assignment of skills to tasks is endogenous").
    #[serde(default)]
    pub profession: Option<String>,
    /// Thought barks while doing the activity.
    #[serde(default)]
    pub barks: Vec<String>,
}

/// Where an activity happens.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ActivityTarget {
    /// In place, for no location.
    Itself,
    /// A random point within the radius of the person.
    Wander(f32),
    /// Any place carrying this tag.
    Place(String),
    /// The person's home.
    Home,
    /// The place this person has bound under this name, from
    /// [`BoundPlaces`](crate::BoundPlaces). A person with no such binding has no candidate: they do not
    /// do the activity.
    Bound(String),
    /// Another person nearby.
    Person,
    /// Toward (or away from, when false) a field's gradient. Needs the `fields` feature.
    Gradient(FieldInput, bool),
}

/// One scoring term: an input mapped through a curve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Consideration {
    /// The signal read for the option.
    pub input: Input,
    /// Maps the input to [0, 1].
    pub curve: Curve,
}

/// Signals a consideration can read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Input {
    /// The actor's level of a need.
    Need(String),
    /// A value the host wrote for the actor.
    Signal(String),
    /// The clock hour divided by 24.
    Hour,
    /// The hour on the actor's own clock divided by 24: the clock hour less the actor's
    /// [`Chronotype`](crate::Chronotype). `Hour` is the village's (social) clock and is the same for
    /// everybody; this is the actor's body clock, and equals `Hour` for a person with no offset. Use it for
    /// what the body decides (when to sleep), and `Hour` for what the village decides (when the workshop
    /// opens). Takes the `Hours` curve like `Hour`.
    BodyHour,
    /// **How far through the week it is**, `(weekday + hour / 24) / 7`, in `[0, 1)`: the village's clock, the same for
    /// everybody, never shifted by a [`Chronotype`](crate::Chronotype). The weekday counts from
    /// [`SocietySettings::start_weekday`](crate::SocietySettings) on game-day 0, and day 0 is whatever the host calls the
    /// first day of its week. It is the input of the `Days(from, to)` curve, the way `Hour` is of `Hours`: `Days(0.0, 5.0)`
    /// is the first five days and `Days(5.0, 7.0)` the last two. It carries the hour of the day as well, so a window may
    /// start mid-day (`Days(4.75, 6.0)` opens at 18:00 on day 4).
    Week,
    /// The actor's mood pleasure, rescaled to [0, 1].
    Pleasure,
    /// The actor's mood arousal, rescaled to [0, 1].
    Arousal,
    /// The actor's mood dominance, rescaled to [0, 1].
    Dominance,
    /// A personality trait of the actor, rescaled to [0, 1].
    Trait(Trait),
    /// The actor's strongest current intensity of an emotion.
    Emotion(EmotionKind),
    /// Affinity toward the target, rescaled to [0, 1]. Person targets only.
    Affinity,
    /// Trust toward the target. Person targets only.
    Trust,
    /// Respect toward the target, rescaled to [0, 1]. Person targets only.
    Respect,
    /// Familiarity with the target. Person targets only.
    Familiarity,
    /// Distance to the target divided by the perception radius. Place, Home and Person targets.
    Distance,
    /// Fraction of the actor's close ties doing this activity. Person targets only.
    SocialProof,
    /// A named skill's level, in `[0, 1]`. See [`SkillDef`].
    Skill(String),
    /// The **joint surplus** a trade in this good would produce, in `[0, 1]`.
    ///
    /// `value(target's store) − value(actor's store)` for the good named, where `value(held) = 1/(1+held)`.
    /// This is Hall & Milgrom's precondition as a consideration: "once ... they have met and found that they
    /// would enjoy a **joint surplus**, the threats to disclaim the match are hollow" (Hall 2005, DOI
    /// `10.3386/w11678`). Near zero when both stores are the same, and largest when one is empty.
    ///
    /// Zero unless the actor holds **more than** [`Tuning::trade_reserve`](crate::Tuning) of the good (it has
    /// something to spare) **and** the gap is at least [`Tuning::trade_margin`](crate::Tuning) (it is worth
    /// the walk). The input itself is a measurement of two stores, not a rate. It needs a `Person` target,
    /// and a target holding no goods at all is not a counterparty.
    Surplus(String),
    /// **How much of a good the actor itself holds**, in units, clamped to `[0, 1]` like every input.
    ///
    /// A unit is whatever the pack calls one: the clamp makes `1.0` the top of the scale, so a pack that
    /// counts a meal in quarter-loaves rescales it in the curve (`Linear(4.0, 0.0)` reads "a meal in hand"
    /// as `1.0`). This is the **appetitive** half of a need that a good satisfies: an activity that
    /// *consumes* the good can score by whether there is any to consume, and the activity that *produces*
    /// it by whether the shelf is empty, so production answers to the household's own larder rather than
    /// to the clock alone. It needs no target, and costs one read of the actor's own `Stock`.
    Stock(String),
    /// A social field value at the target cell. Needs the `fields` feature.
    Field(FieldInput),
    /// A Rhai float expression, clamped to [0, 1].
    Script(String),
}

/// Social fields a consideration or gradient target can read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FieldInput {
    /// Presence of everyone at the cell, relative to its peak.
    Crowd,
    /// Recent deeds at the cell, relative to its peak.
    Commotion,
    /// The actor's faction's presence at the cell, relative to its peak.
    OwnFaction,
    /// Presence of factions the actor is not in, relative to its peak.
    OtherFactions,
    /// The actor's faction's share of presence at the cell (Schelling 1971, DOI 10.1080/0022250X.1971.9989794).
    OwnShare,
}

/// A social exchange between two persons.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InteractionDef {
    /// Unique name.
    pub id: String,
    /// Rhai boolean; the exchange is refused by rule when false.
    pub requires: Option<String>,
    /// Acceptance probability terms.
    #[serde(default)]
    pub accept: AcceptDef,
    /// Effects when the target accepts.
    #[serde(default)]
    pub on_accept: EffectsDef,
    /// Effects when the target refuses.
    #[serde(default)]
    pub on_reject: EffectsDef,
    /// Topics that influence both persons' opinions when the exchange is accepted.
    #[serde(default)]
    pub influence: Vec<String>,
    /// Whether an accepted exchange passes on a rumor.
    #[serde(default)]
    pub gossip: bool,
    /// Deed the exchange performs on the target when accepted.
    pub deed: Option<String>,
    /// Whether the exchange is a contest that sets a winner.
    #[serde(default)]
    pub contest: bool,
    /// Bark lines.
    #[serde(default)]
    pub barks: InteractionBarks,
}

/// Terms of the acceptance probability (Deffuant et al. 2000 and Byrne 1961 inform the defaults;
/// the plan records the numbers).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct AcceptDef {
    /// Base probability.
    pub base: f32,
    /// Weight of affinity toward the actor.
    pub affinity: f32,
    /// Weight of the target's trust in the actor.
    pub trust: f32,
    /// Weight of the target's agreeableness.
    pub agreeableness: f32,
    /// Weight of the target's mood pleasure.
    pub pleasure: f32,
    /// Bonus when both share a faction.
    pub ingroup: f32,
}

impl Default for AcceptDef {
    fn default() -> Self {
        Self {
            base: 0.5,
            affinity: 0.3,
            trust: 0.2,
            agreeableness: 0.2,
            pleasure: 0.1,
            ingroup: 0.1,
        }
    }
}

/// Tie changes applied by an interaction outcome.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct TieDelta {
    /// Change in affinity.
    pub affinity: f32,
    /// Change in trust.
    pub trust: f32,
    /// Change in respect.
    pub respect: f32,
    /// Change in familiarity.
    pub familiarity: f32,
}

/// The effects of one interaction outcome.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct EffectsDef {
    /// Tie change from actor toward target.
    pub actor_to_target: TieDelta,
    /// Tie change from target toward actor.
    pub target_to_actor: TieDelta,
    /// Emotion the actor feels, with intensity.
    pub actor_emotion: Option<(EmotionKind, f32)>,
    /// Emotion the target feels, with intensity.
    pub target_emotion: Option<(EmotionKind, f32)>,
    /// Need changes for the actor.
    pub actor_needs: Vec<(String, f32)>,
    /// Need changes for the target.
    pub target_needs: Vec<(String, f32)>,
    /// **A good the actor hands over on accept**, with the amount: a trade.
    ///
    /// Pairwise barter, not a market: "a less-studied alternative to auction systems is the pattern of
    /// Edgeworth barter, in which buyers and sellers interact directly with each other in repeated pairwise
    /// transactions, without the benefit of an auctioneer" (corpus doc `10.1007_11678809_10`). The transfer
    /// is *declarative* — the activity says what changes hands — so no new system decides who trades with
    /// whom; `Perceive` already does, and the acceptance draw decides whether it happens.
    #[serde(default)]
    pub actor_gives: Vec<(String, f32)>,
    /// A good the target hands over on accept, with the amount.
    #[serde(default)]
    pub target_gives: Vec<(String, f32)>,
    /// How memorable the outcome is, in [0, 1].
    pub importance: f32,
    /// Rhai statements run with actor and target bound.
    pub script: Option<String>,
}

impl Default for EffectsDef {
    fn default() -> Self {
        Self {
            actor_gives: Vec::new(),
            target_gives: Vec::new(),
            actor_to_target: TieDelta::default(),
            target_to_actor: TieDelta::default(),
            actor_emotion: None,
            target_emotion: None,
            actor_needs: Vec::new(),
            target_needs: Vec::new(),
            importance: 0.3,
            script: None,
        }
    }
}

/// Bark lines for an interaction. Templates may use `{self}`, `{target}`, `{subject}` and `{place}`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct InteractionBarks {
    /// What the actor says when it starts the exchange.
    pub actor: Vec<String>,
    /// What the target says when it accepts.
    pub accepted: Vec<String>,
    /// What the target says when it refuses.
    pub rejected: Vec<String>,
}

/// A rule that fires on a simulation event and runs a script.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TriggerDef {
    /// Unique name, used in error messages.
    pub id: String,
    /// The event that starts evaluation.
    pub on: TriggerOn,
    /// Rhai boolean that must hold for `then` to run.
    #[serde(rename = "if")]
    pub condition: Option<String>,
    /// Rhai statements to run.
    pub then: String,
    /// Fire at most once per (trigger, actor).
    #[serde(default)]
    pub once: bool,
    /// Minimum game-hours between firings per (trigger, actor).
    #[serde(default)]
    pub cooldown_hours: f32,
    /// Fire only while the bound actor stands inside this rectangle on the society plane. An event
    /// with no actor never fires an area trigger, so `Tick`, `Hour` and `RumorReach`, which bind
    /// none, are refused at load. Design default: absent means anywhere.
    #[serde(default)]
    pub area: Option<TriggerArea>,
    /// Fire only for an actor who belongs to at least one of these factions. Needs an event that
    /// binds an actor, like `area`. Design default: empty means any actor.
    #[serde(default)]
    pub factions: Vec<String>,
    /// Fire only for an actor with one of these `PersonId`s. Needs an event that binds an actor,
    /// like `area`. Design default: empty means any actor.
    #[serde(default)]
    pub persons: Vec<u32>,
}

/// An axis-aligned rectangle on the society plane, edges inclusive: where an area trigger is live.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct TriggerArea {
    /// The corner with the smaller coordinates.
    pub min: [f32; 2],
    /// The corner with the larger coordinates.
    pub max: [f32; 2],
}

impl TriggerArea {
    /// Whether `p` lies inside the rectangle, edges included.
    pub fn contains(&self, p: [f32; 2]) -> bool {
        p[0] >= self.min[0] && p[0] <= self.max[0] && p[1] >= self.min[1] && p[1] <= self.max[1]
    }
}

/// The events a trigger can listen to.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerOn {
    /// Every simulation tick.
    Tick,
    /// When the clock crosses this hour, in [0, 24).
    Hour(f32),
    /// When a person dies, with the deceased bound as the actor.
    PersonDied,
    /// When this interaction resolves.
    Interaction(String),
    /// When a tie's label changes to this label.
    TieLabel(TieLabel),
    /// When a rumor of this deed first reaches this fraction of living persons.
    RumorReach {
        /// The deed.
        deed: String,
        /// Fraction in (0, 1].
        fraction: f32,
    },
    /// When a witness judges this deed a norm violation.
    NormViolated(String),
    /// When a person's need first falls below this level.
    NeedBelow {
        /// The need.
        need: String,
        /// The threshold level.
        below: f32,
    },
    /// When this activity starts.
    Activity(String),
    /// When a dialogue node is entered in this conversation.
    DialogueNode {
        /// The conversation name in the host's `DialogueScript`.
        conversation: String,
        /// The node name.
        node: String,
    },
    /// A named event the host fires with `FireTrigger`.
    Custom(String),
}

/// Chooses the conversation for a `TalkTo`. The highest priority matching rule wins.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConversationRuleDef {
    /// The conversation name in the host's `DialogueScript`.
    pub conversation: String,
    /// Higher wins; ties go to the earlier definition.
    #[serde(default)]
    pub priority: i32,
    /// Rhai boolean; actor is the NPC, target is the player.
    #[serde(rename = "if")]
    pub condition: Option<String>,
}

/// Runs a script when a dialogue node is entered.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NodeEffectDef {
    /// The conversation name.
    pub conversation: String,
    /// The node name.
    pub node: String,
    /// Rhai statements to run, with actor as the NPC and target as the player.
    pub then: String,
}

/// Why a definitions file was rejected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DefsError {
    /// The RON text did not parse.
    Ron(String),
    /// An id was defined twice.
    Duplicate {
        /// What kind of definition.
        kind: &'static str,
        /// The repeated id.
        id: String,
    },
    /// A definition names an id that is not defined.
    UnknownId {
        /// What kind of definition was expected.
        kind: &'static str,
        /// The missing id.
        id: String,
        /// The definition that names it.
        owner: String,
    },
    /// A value is out of range or a combination is not allowed.
    Invalid {
        /// The definition at fault.
        owner: String,
        /// What is wrong.
        message: String,
    },
    /// A Rhai script does not compile.
    Script {
        /// The definition that holds the script.
        owner: String,
        /// The Rhai parse error.
        message: String,
    },
}

impl fmt::Display for DefsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ron(message) => write!(f, "bevy_society: definitions do not parse: {message}"),
            Self::Duplicate { kind, id } => {
                write!(f, "bevy_society: {kind} '{id}' is defined more than once")
            }
            Self::UnknownId { kind, id, owner } => {
                write!(
                    f,
                    "bevy_society: {owner} names {kind} '{id}', which is not defined"
                )
            }
            Self::Invalid { owner, message } => write!(f, "bevy_society: {owner}: {message}"),
            Self::Script { owner, message } => {
                write!(
                    f,
                    "bevy_society: {owner}: script does not compile: {message}"
                )
            }
        }
    }
}

impl std::error::Error for DefsError {}

impl DefsFile {
    /// Parses a definitions file from RON text.
    pub fn from_ron(text: &str) -> Result<Self, DefsError> {
        ron::from_str(text).map_err(|err| DefsError::Ron(err.to_string()))
    }

    /// Writes the file as pretty RON; [`DefsFile::from_ron`] reads it back equal. This is what an
    /// editor saves after it changes a definition.
    pub fn to_ron(&self) -> Result<String, DefsError> {
        ron::ser::to_string_pretty(self, ron::ser::PrettyConfig::default())
            .map_err(|err| DefsError::Ron(err.to_string()))
    }

    /// Adds `other` to `self`. An id defined in both files, or twice in `other`, is an error and
    /// `self` is left unchanged.
    pub fn merge(&mut self, other: DefsFile) -> Result<(), DefsError> {
        check_disjoint(
            "need",
            self.needs.iter().map(|d| d.id.as_str()),
            other.needs.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "signal",
            self.signals.iter().map(|d| d.id.as_str()),
            other.signals.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "topic",
            self.topics.iter().map(|d| d.id.as_str()),
            other.topics.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "deed",
            self.deeds.iter().map(|d| d.id.as_str()),
            other.deeds.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "faction",
            self.factions.iter().map(|d| d.id.as_str()),
            other.factions.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "activity",
            self.activities.iter().map(|d| d.id.as_str()),
            other.activities.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "interaction",
            self.interactions.iter().map(|d| d.id.as_str()),
            other.interactions.iter().map(|d| d.id.as_str()),
        )?;
        // **`goods` and `skills` were omitted here until 2026-10-26-13.** Eleven lists were carried and two
        // were not, so a pack merged in that declares a good contributed nothing: `compile` then resolved
        // every `consumes` and `produces` that named it to "not defined", and the merge either failed with a
        // confusing unknown-id error or — for a good only the *other* pack used — dropped the good silently.
        // Found when `bake` moved into the starter pack, which is exactly the merge the village example does.
        check_disjoint(
            "good",
            self.goods.iter().map(|d| d.id.as_str()),
            other.goods.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "skill",
            self.skills.iter().map(|d| d.id.as_str()),
            other.skills.iter().map(|d| d.id.as_str()),
        )?;
        check_disjoint(
            "trigger",
            self.triggers.iter().map(|d| d.id.as_str()),
            other.triggers.iter().map(|d| d.id.as_str()),
        )?;
        self.needs.extend(other.needs);
        self.signals.extend(other.signals);
        self.skills.extend(other.skills);
        self.goods.extend(other.goods);
        self.topics.extend(other.topics);
        self.deeds.extend(other.deeds);
        self.factions.extend(other.factions);
        self.activities.extend(other.activities);
        self.interactions.extend(other.interactions);
        self.triggers.extend(other.triggers);
        self.conversations.extend(other.conversations);
        self.node_effects.extend(other.node_effects);
        Ok(())
    }

    /// The starter pack (`assets/starter.society.ron`).
    pub fn starter() -> Result<Self, DefsError> {
        Self::from_ron(include_str!("../assets/starter.society.ron"))
    }
}

fn check_disjoint<'a>(
    kind: &'static str,
    mine: impl Iterator<Item = &'a str>,
    theirs: impl Iterator<Item = &'a str>,
) -> Result<(), DefsError> {
    let mut seen: HashSet<&str> = mine.collect();
    for name in theirs {
        if !seen.insert(name) {
            return Err(DefsError::Duplicate {
                kind,
                id: name.to_owned(),
            });
        }
    }
    Ok(())
}

/// Compiled definitions: the resource the simulation reads. `Default` is the empty set plus the
/// reserved `idle` activity.
///
/// `Clone` because an exclusive system takes a copy before writing the world: a `&SocietyDefs`
/// borrowed from the world cannot coexist with `&mut World`, and every decision needs to read it.
#[derive(Resource, Clone)]
pub struct SocietyDefs {
    pub(crate) needs: Vec<NeedSpec>,
    pub(crate) signals: Vec<String>,
    /// Named capabilities, in definition order.
    pub(crate) skills: Vec<SkillGroup>,
    /// Goods, in definition order. Public so a host can count what its pack declares.
    pub goods: Vec<String>,
    /// What a new person holds of each good, parallel to `goods` ([`GoodDef::initial`]).
    pub(crate) good_initial: Vec<f32>,
    pub(crate) topics: Vec<TopicSpec>,
    pub(crate) deeds: Vec<DeedSpec>,
    pub(crate) factions: Vec<FactionSpec>,
    pub(crate) activities: Vec<ActivitySpec>,
    pub(crate) interactions: Vec<InteractionSpec>,
    pub(crate) triggers: Vec<TriggerSpec>,
    pub(crate) conversations: Vec<ConversationSpec>,
    pub(crate) node_effects: Vec<NodeEffectSpec>,
    pub(crate) scripts: Vec<CompiledScript>,
    need_ids: HashMap<String, u16>,
    signal_ids: HashMap<String, u16>,
    skill_ids: HashMap<String, u16>,
    good_ids: HashMap<String, u16>,
    topic_ids: HashMap<String, u16>,
    deed_ids: HashMap<String, u16>,
    faction_ids: HashMap<String, u16>,
    activity_ids: HashMap<String, u16>,
    interaction_ids: HashMap<String, u16>,
}

impl Default for SocietyDefs {
    fn default() -> Self {
        Self::empty()
    }
}

impl SocietyDefs {
    fn empty() -> Self {
        let mut activity_ids = HashMap::new();
        activity_ids.insert(IDLE.to_owned(), IDLE_ACTIVITY.0);
        Self {
            needs: Vec::new(),
            signals: Vec::new(),
            skills: Vec::new(),
            goods: Vec::new(),
            good_initial: Vec::new(),
            good_ids: HashMap::new(),
            topics: Vec::new(),
            deeds: Vec::new(),
            factions: Vec::new(),
            activities: vec![ActivitySpec {
                name: IDLE.to_owned(),
                target: ActivityTarget::Itself,
                duration_hours: 1.0,
                rank: 0,
                urgent: None,
                unavailable: false,
                weight: 1.0,
                considerations: Vec::new(),
                satisfies: Vec::new(),
                interaction: None,
                produces: Vec::new(),
                consumes: Vec::new(),
                barks: Vec::new(),
            }],
            interactions: Vec::new(),
            triggers: Vec::new(),
            conversations: Vec::new(),
            node_effects: Vec::new(),
            scripts: Vec::new(),
            need_ids: HashMap::new(),
            signal_ids: HashMap::new(),
            skill_ids: HashMap::new(),
            topic_ids: HashMap::new(),
            deed_ids: HashMap::new(),
            faction_ids: HashMap::new(),
            activity_ids,
            interaction_ids: HashMap::new(),
        }
    }

    /// Compiles authored definitions into ids and scripts. Errors name the offending definition.
    pub fn compile(file: DefsFile) -> Result<Self, DefsError> {
        let mut defs = Self::empty();
        let mut scripts = ScriptCompiler::new();
        for def in file.needs {
            defs.add_need(def)?;
        }
        for def in file.signals {
            defs.add_signal(def)?;
        }
        for def in file.skills {
            defs.add_skill(def)?;
        }
        for def in file.goods {
            defs.add_good(def)?;
        }
        for def in file.topics {
            defs.add_topic(def)?;
        }
        for def in file.deeds {
            defs.add_deed(def)?;
        }
        for def in file.factions {
            defs.add_faction(def)?;
        }
        for def in file.interactions {
            defs.add_interaction(def, &mut scripts)?;
        }
        for def in file.activities {
            defs.add_activity(def, &mut scripts)?;
        }
        let mut trigger_names = HashSet::new();
        for def in file.triggers {
            defs.add_trigger(def, &mut scripts, &mut trigger_names)?;
        }
        for def in file.conversations {
            defs.add_conversation(def, &mut scripts)?;
        }
        for def in file.node_effects {
            defs.add_node_effect(def, &mut scripts)?;
        }
        defs.scripts = scripts.into_scripts();
        Ok(defs)
    }

    /// Parses and compiles a definitions file from RON text.
    pub fn from_ron(text: &str) -> Result<Self, DefsError> {
        Self::compile(DefsFile::from_ron(text)?)
    }

    /// Swaps in an edited definitions file while the society runs: the live path for an editor
    /// that changes a trigger's script, an activity's score or an interaction's effects without a
    /// restart. Every id in the world is an index into the id tables (needs, signals, skills,
    /// goods, topics, deeds, factions, activities, interactions), so the edit must leave those
    /// tables name-for-name unchanged; anything else (triggers, conversations, node effects,
    /// considerations, effects, tunings of a definition) may change. A file that does not compile,
    /// or that changes an id table, is refused and `self` is left as it was.
    ///
    /// Prefer [`reload_defs`](crate::reload_defs), which also keeps `once` and cooldown state for
    /// the triggers that survive the edit.
    pub fn reload(&mut self, file: DefsFile) -> Result<(), DefsError> {
        let next = Self::compile(file)?;
        let changed = |table: &str| {
            Err(DefsError::Invalid {
                owner: "reload".to_owned(),
                message: format!(
                    "the {table} list changed; ids already in the world index it, so a live edit \
                     may not add, remove or reorder {table}"
                ),
            })
        };
        fn names<T>(items: &[T], name: impl Fn(&T) -> &str) -> Vec<&str> {
            items.iter().map(name).collect()
        }
        if names(&self.needs, |s| &s.name) != names(&next.needs, |s| &s.name) {
            return changed("needs");
        }
        if self.signals != next.signals {
            return changed("signals");
        }
        if self.skill_ids != next.skill_ids || self.skills != next.skills {
            return changed("skills");
        }
        if self.goods != next.goods {
            return changed("goods");
        }
        if names(&self.topics, |s| &s.name) != names(&next.topics, |s| &s.name) {
            return changed("topics");
        }
        if names(&self.deeds, |s| &s.name) != names(&next.deeds, |s| &s.name) {
            return changed("deeds");
        }
        if names(&self.factions, |s| &s.name) != names(&next.factions, |s| &s.name) {
            return changed("factions");
        }
        if names(&self.activities, |s| &s.name) != names(&next.activities, |s| &s.name) {
            return changed("activities");
        }
        if names(&self.interactions, |s| &s.name) != names(&next.interactions, |s| &s.name) {
            return changed("interactions");
        }
        *self = next;
        Ok(())
    }

    /// The compiled starter pack.
    pub fn starter() -> Result<Self, DefsError> {
        Self::compile(DefsFile::starter()?)
    }

    /// The id of a need, if defined.
    pub fn need_id(&self, name: &str) -> Option<NeedId> {
        self.need_ids.get(name).copied().map(NeedId)
    }

    /// The id of a good, if defined.
    pub fn good_id(&self, name: &str) -> Option<GoodId> {
        self.good_ids.get(name).copied().map(GoodId)
    }

    /// An activity's compiled specification, by its authored name.
    pub(crate) fn activity_by_name(&self, name: &str) -> Option<&ActivitySpec> {
        self.activity_id(name)
            .and_then(|id| self.activities.get(usize::from(id.0)))
    }

    /// The id of a skill, if defined.
    pub fn skill_id(&self, name: &str) -> Option<SkillId> {
        self.skill_ids.get(name).copied().map(SkillId)
    }

    /// The group a skill reads, by id.
    pub fn skill_group(&self, id: SkillId) -> Option<SkillGroup> {
        self.skills.get(usize::from(id.0)).copied()
    }

    /// The id of a signal, if defined.
    pub fn signal_id(&self, name: &str) -> Option<SignalId> {
        self.signal_ids.get(name).copied().map(SignalId)
    }

    /// The id of a topic, if defined.
    pub fn topic_id(&self, name: &str) -> Option<TopicId> {
        self.topic_ids.get(name).copied().map(TopicId)
    }

    /// The id of a deed, if defined.
    pub fn deed_id(&self, name: &str) -> Option<DeedId> {
        self.deed_ids.get(name).copied().map(DeedId)
    }

    /// The id of a faction, if defined.
    pub fn faction_id(&self, name: &str) -> Option<FactionId> {
        self.faction_ids.get(name).copied().map(FactionId)
    }

    /// The id of an activity, if defined. `idle` is always defined.
    pub fn activity_id(&self, name: &str) -> Option<ActivityId> {
        self.activity_ids.get(name).copied().map(ActivityId)
    }

    /// The id of an interaction, if defined.
    pub fn interaction_id(&self, name: &str) -> Option<InteractionId> {
        self.interaction_ids.get(name).copied().map(InteractionId)
    }

    /// The name of a need, or `""` for an id this definition set does not contain.
    pub fn need_name(&self, id: NeedId) -> &str {
        self.needs
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// The name of a signal, or `""` for an id this definition set does not contain.
    pub fn signal_name(&self, id: SignalId) -> &str {
        self.signals
            .get(usize::from(id.0))
            .map_or("", String::as_str)
    }

    /// The name of a topic, or `""` for an unknown id.
    pub fn topic_name(&self, id: TopicId) -> &str {
        self.topics
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// The name of a deed, or `""` for an unknown id.
    pub fn deed_name(&self, id: DeedId) -> &str {
        self.deeds
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// The name of a faction, or `""` for an unknown id.
    pub fn faction_name(&self, id: FactionId) -> &str {
        self.factions
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// The name of an activity, or `""` for an unknown id.
    pub fn activity_name(&self, id: ActivityId) -> &str {
        self.activities
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// Every activity's name with the signals its considerations read, in definition order.
    ///
    /// A host needs this to check whether a definition relies on a signal the behaviour systems do
    /// not yet score: `BehaviorPlugin` warns at startup about `Field` and about `Gradient` targets,
    /// which the definitions file accepts but which currently choose nothing.
    pub fn activity_signals(&self) -> Vec<(&str, Vec<crate::defs::Signal>)> {
        self.activities
            .iter()
            .map(|spec| {
                (
                    spec.name.as_str(),
                    spec.considerations.iter().map(|term| term.signal).collect(),
                )
            })
            .collect()
    }

    /// How fast `need` decays per game-day, or `None` when the name is not defined.
    ///
    /// With [`Self::best_source`] this is the whole of a need's budget: a need whose best single use
    /// supplies less than its decay must be met more than once a day, and a definition where that
    /// number is large describes people who starve.
    pub fn need_decay(&self, need: &str) -> Option<f32> {
        let id = self.need_id(need)?;
        self.needs
            .get(usize::from(id.0))
            .map(|spec| spec.decay_per_day)
    }

    /// Every activity that supplies `need`, with the amount each pays per use, in definition order.
    ///
    /// A need with one source is a need with no choice: whatever else competes for the same hour takes
    /// from it. `fun` in the starter pack had exactly one.
    pub fn sources_for(&self, need: &str) -> Vec<(&str, f32)> {
        let Some(id) = self.need_id(need) else {
            return Vec::new();
        };
        self.activities
            .iter()
            .filter_map(|activity| {
                let rate = activity
                    .satisfies
                    .iter()
                    .find(|(slot, _)| *slot == id)
                    .map(|(_, rate)| *rate)?;
                Some((activity.name.as_str(), rate * activity.duration_hours))
            })
            .collect()
    }

    /// The activity that supplies `need` most per use, with the amount it supplies, or `None` when no
    /// activity satisfies it.
    ///
    /// A use supplies `satisfies · duration_hours`, because `satisfies` is a per-game-hour rate paid
    /// for the activity's whole duration. Ties go to the earlier activity in definition order.
    pub fn best_source(&self, need: &str) -> Option<(&str, f32)> {
        let id = self.need_id(need)?;
        self.activities
            .iter()
            .filter_map(|activity| {
                let rate = activity
                    .satisfies
                    .iter()
                    .find(|(slot, _)| *slot == id)
                    .map(|(_, rate)| *rate)?;
                Some((activity.name.as_str(), rate * activity.duration_hours))
            })
            .fold(None::<(&str, f32)>, |best, candidate| match best {
                Some((_, amount)) if amount >= candidate.1 => best,
                _ => Some(candidate),
            })
    }

    /// Whether the activity called `name` targets a field gradient.
    pub fn activity_targets_gradient(&self, name: &str) -> bool {
        self.activities
            .iter()
            .any(|spec| spec.name == name && matches!(spec.target, ActivityTarget::Gradient(..)))
    }

    /// Whether any compiled activity targets a field gradient.
    pub fn has_gradient_activity(&self) -> bool {
        self.activities
            .iter()
            .any(|spec| matches!(spec.target, ActivityTarget::Gradient(..)))
    }

    /// Every activity's name with its duration in game-hours, in definition order.
    ///
    /// A host needs this to check its own `seconds_per_day`: a duration shorter than a society tick
    /// makes the activity degenerate, and `BehaviorPlugin` warns about it at startup. Exposed rather
    /// than inferred so a host (or a test) can make the same check without the compiled internals.
    pub fn activity_durations(&self) -> Vec<(&str, f32)> {
        self.activities
            .iter()
            .map(|spec| (spec.name.as_str(), spec.duration_hours))
            .collect()
    }

    /// The name of an interaction, or `""` for an unknown id.
    pub fn interaction_name(&self, id: InteractionId) -> &str {
        self.interactions
            .get(usize::from(id.0))
            .map_or("", |spec| spec.name.as_str())
    }

    /// Needs for a new person: each need starts at its `initial` level, then the named values
    /// replace theirs.
    pub fn needs<'a>(
        &self,
        values: impl IntoIterator<Item = (&'a str, f32)>,
    ) -> Result<Needs, DefsError> {
        let mut levels: Vec<f32> = self.needs.iter().map(|spec| spec.initial).collect();
        for (name, level) in values {
            let id = require(self.need_id(name), "need", name, "person needs")?;
            if let Some(slot) = levels.get_mut(usize::from(id.0)) {
                *slot = level;
            }
        }
        Ok(Needs(levels))
    }

    /// Signals for a new person: one slot per defined signal, every value `0.0`, then the named
    /// values replace theirs. The crate never changes them afterwards.
    pub fn signals<'a>(
        &self,
        values: impl IntoIterator<Item = (&'a str, f32)>,
    ) -> Result<Signals, DefsError> {
        let mut levels = vec![0.0; self.signals.len()];
        for (name, value) in values {
            let id = require(self.signal_id(name), "signal", name, "person signals")?;
            if let Some(slot) = levels.get_mut(usize::from(id.0)) {
                *slot = if value.is_finite() { value } else { 0.0 };
            }
        }
        Ok(Signals(levels))
    }

    /// Opinions for a new person. Each named topic starts at its value, which is also its
    /// Friedkin–Johnsen anchor (DOI 10.1080/0022250X.1990.9990069); the others start neutral.
    pub fn opinions<'a>(
        &self,
        values: impl IntoIterator<Item = (&'a str, f32)>,
    ) -> Result<Opinions, DefsError> {
        let mut topics = vec![Opinion::default(); self.topics.len()];
        for (name, value) in values {
            let id = require(self.topic_id(name), "topic", name, "person opinions")?;
            if let Some(slot) = topics.get_mut(usize::from(id.0)) {
                *slot = Opinion::at(value);
            }
        }
        Ok(Opinions(topics))
    }

    /// Faction memberships for a new person, sorted and without duplicates.
    pub fn memberships<'a>(
        &self,
        factions: impl IntoIterator<Item = &'a str>,
    ) -> Result<Memberships, DefsError> {
        let mut ids = Vec::new();
        for name in factions {
            ids.push(require(
                self.faction_id(name),
                "faction",
                name,
                "person memberships",
            )?);
        }
        ids.sort();
        ids.dedup();
        Ok(Memberships(ids))
    }

    fn add_need(&mut self, def: NeedDef) -> Result<(), DefsError> {
        let owner = format!("need '{}'", def.id);
        if def.decay_per_day.is_nan() || def.decay_per_day < 0.0 {
            return Err(invalid(&owner, "decay_per_day must be 0 or more"));
        }
        register(&mut self.need_ids, "need", &def.id, self.needs.len())?;
        self.needs.push(NeedSpec {
            name: def.id,
            decay_per_day: def.decay_per_day,
            initial: def.initial,
        });
        Ok(())
    }

    fn add_signal(&mut self, def: SignalDef) -> Result<(), DefsError> {
        register(&mut self.signal_ids, "signal", &def.id, self.signals.len())?;
        self.signals.push(def.id);
        Ok(())
    }

    fn add_skill(&mut self, def: SkillDef) -> Result<(), DefsError> {
        register(&mut self.skill_ids, "skill", &def.id, self.skills.len())?;
        self.skills.push(def.group);
        Ok(())
    }

    fn add_good(&mut self, def: GoodDef) -> Result<(), DefsError> {
        let owner = format!("good '{}'", def.id);
        if !def.initial.is_finite() || def.initial < 0.0 {
            return Err(invalid(&owner, "initial must be a number, 0 or more"));
        }
        register(&mut self.good_ids, "good", &def.id, self.goods.len())?;
        self.goods.push(def.id);
        self.good_initial.push(def.initial);
        Ok(())
    }

    fn add_topic(&mut self, def: TopicDef) -> Result<(), DefsError> {
        register(&mut self.topic_ids, "topic", &def.id, self.topics.len())?;
        self.topics.push(TopicSpec { name: def.id });
        Ok(())
    }

    fn add_deed(&mut self, def: DeedDef) -> Result<(), DefsError> {
        let owner = format!("deed '{}'", def.id);
        let topic = require(self.topic_id(&def.topic), "topic", &def.topic, &owner)?;
        if !(-1.0..=1.0).contains(&def.harm) {
            return Err(invalid(&owner, "harm must be in [-1, 1]"));
        }
        register(&mut self.deed_ids, "deed", &def.id, self.deeds.len())?;
        self.deeds.push(DeedSpec {
            name: def.id,
            topic,
            harm: def.harm,
        });
        Ok(())
    }

    fn add_faction(&mut self, def: FactionDef) -> Result<(), DefsError> {
        register(
            &mut self.faction_ids,
            "faction",
            &def.id,
            self.factions.len(),
        )?;
        self.factions.push(FactionSpec {
            name: def.id,
            ingroup_bias: def.ingroup_bias,
        });
        Ok(())
    }

    fn add_interaction(
        &mut self,
        def: InteractionDef,
        scripts: &mut ScriptCompiler,
    ) -> Result<(), DefsError> {
        let owner = format!("interaction '{}'", def.id);
        register(
            &mut self.interaction_ids,
            "interaction",
            &def.id,
            self.interactions.len(),
        )?;
        let requires = match def.requires.as_deref() {
            Some(source) => Some(scripts.expression(&format!("{owner} requires"), source)?),
            None => None,
        };
        let on_accept =
            self.compile_effects(&format!("{owner} on_accept"), &def.on_accept, scripts)?;
        let on_reject =
            self.compile_effects(&format!("{owner} on_reject"), &def.on_reject, scripts)?;
        let mut influence = Vec::with_capacity(def.influence.len());
        for topic in &def.influence {
            influence.push(require(self.topic_id(topic), "topic", topic, &owner)?);
        }
        let deed = match def.deed.as_deref() {
            Some(name) => Some(require(self.deed_id(name), "deed", name, &owner)?),
            None => None,
        };
        let barks_owner = format!("{owner} barks");
        for line in def
            .barks
            .actor
            .iter()
            .chain(&def.barks.accepted)
            .chain(&def.barks.rejected)
        {
            check_template(&barks_owner, line)?;
        }
        self.interactions.push(InteractionSpec {
            name: def.id,
            requires,
            accept: def.accept,
            on_accept,
            on_reject,
            influence,
            gossip: def.gossip,
            deed,
            contest: def.contest,
            barks: def.barks,
        });
        Ok(())
    }

    fn compile_effects(
        &self,
        owner: &str,
        def: &EffectsDef,
        scripts: &mut ScriptCompiler,
    ) -> Result<EffectsSpec, DefsError> {
        let actor_needs = self.need_deltas(owner, &def.actor_needs)?;
        let target_needs = self.need_deltas(owner, &def.target_needs)?;
        let actor_gives = self.good_list(owner, &def.actor_gives)?;
        let target_gives = self.good_list(owner, &def.target_gives)?;
        let script = match def.script.as_deref() {
            Some(source) => Some(scripts.statements(owner, source)?),
            None => None,
        };
        Ok(EffectsSpec {
            actor_to_target: def.actor_to_target,
            target_to_actor: def.target_to_actor,
            actor_emotion: def.actor_emotion,
            target_emotion: def.target_emotion,
            actor_needs,
            target_needs,
            actor_gives,
            target_gives,
            importance: def.importance,
            script,
        })
    }

    fn need_deltas(
        &self,
        owner: &str,
        pairs: &[(String, f32)],
    ) -> Result<Vec<(NeedId, f32)>, DefsError> {
        let mut out = Vec::with_capacity(pairs.len());
        for (name, delta) in pairs {
            out.push((require(self.need_id(name), "need", name, owner)?, *delta));
        }
        Ok(out)
    }

    fn add_activity(
        &mut self,
        def: ActivityDef,
        scripts: &mut ScriptCompiler,
    ) -> Result<(), DefsError> {
        let owner = format!("activity '{}'", def.id);
        if def.duration_hours.is_nan() || def.duration_hours <= 0.0 {
            return Err(invalid(&owner, "duration_hours must be above 0"));
        }
        if def.weight.is_nan() || def.weight < 0.0 {
            return Err(invalid(&owner, "weight must be 0 or more"));
        }
        check_target(&owner, &def.target)?;
        let urgent = match &def.urgent {
            Some(urgent) => {
                let urgent_owner = format!("{owner} urgent");
                let need = require(
                    self.need_id(&urgent.need),
                    "need",
                    &urgent.need,
                    &urgent_owner,
                )?;
                if !urgent.below.is_finite() || urgent.below <= 0.0 || urgent.below > 1.0 {
                    return Err(invalid(&urgent_owner, "below must be in (0, 1]"));
                }
                if urgent.rank <= def.rank {
                    return Err(invalid(
                        &urgent_owner,
                        "rank must be above the activity's own rank, or it changes nothing",
                    ));
                }
                Some(Urgent {
                    need,
                    below: urgent.below,
                    rank: urgent.rank,
                })
            }
            None => None,
        };
        register(
            &mut self.activity_ids,
            "activity",
            &def.id,
            self.activities.len(),
        )?;
        let mut considerations = Vec::with_capacity(def.considerations.len());
        for (index, term) in def.considerations.iter().enumerate() {
            let term_owner = format!("{owner} consideration {index}");
            considerations.push(self.compile_term(&term_owner, term, &def.target, scripts)?);
        }
        let satisfies_owner = format!("{owner} satisfies");
        let satisfies = self.need_deltas(&satisfies_owner, &def.satisfies)?;
        let interaction = match def.interaction.as_deref() {
            Some(name) => {
                if !matches!(def.target, ActivityTarget::Person) {
                    return Err(invalid(&owner, "an interaction needs a Person target"));
                }
                Some(require(
                    self.interaction_id(name),
                    "interaction",
                    name,
                    &owner,
                )?)
            }
            None => None,
        };
        let barks_owner = format!("{owner} barks");
        for line in &def.barks {
            check_template(&barks_owner, line)?;
        }
        // Goods, resolved against the definitions file. An unknown name is an error rather than a
        // silent no-op: a task that produces nothing because of a typo is a bug a host cannot see.
        let produces = self.good_list(&owner, &def.produces)?;
        let consumes = self.good_list(&owner, &def.consumes)?;
        self.activities.push(ActivitySpec {
            name: def.id,
            target: def.target,
            duration_hours: def.duration_hours,
            rank: def.rank,
            urgent,
            unavailable: def.unavailable,
            weight: def.weight,
            considerations,
            satisfies,
            interaction,
            produces,
            consumes,
            barks: def.barks,
        });
        Ok(())
    }

    /// Resolves `(name, amount)` pairs to goods, refusing an unknown name or a negative amount.
    fn good_list(
        &self,
        owner: &str,
        list: &[(String, f32)],
    ) -> Result<Vec<(GoodId, f32)>, DefsError> {
        let mut out = Vec::with_capacity(list.len());
        for (name, amount) in list {
            if *amount < 0.0 {
                return Err(invalid(
                    owner,
                    format!("good '{name}' has a negative amount"),
                ));
            }
            out.push((require(self.good_id(name), "good", name, owner)?, *amount));
        }
        Ok(out)
    }

    fn compile_term(
        &self,
        owner: &str,
        term: &Consideration,
        target: &ActivityTarget,
        scripts: &mut ScriptCompiler,
    ) -> Result<Term, DefsError> {
        check_input(owner, &term.input, target)?;
        if matches!(term.curve, Curve::Hours(..))
            && !matches!(term.input, Input::Hour | Input::BodyHour)
        {
            return Err(invalid(
                owner,
                "an Hours curve needs the Hour or BodyHour input",
            ));
        }
        if let Curve::Days(from, to) = term.curve {
            if !matches!(term.input, Input::Week) {
                return Err(invalid(owner, "a Days curve needs the Week input"));
            }
            let days = 0.0..=f32::from(crate::model::DAYS_PER_WEEK);
            if !days.contains(&from) || !days.contains(&to) {
                return Err(invalid(
                    owner,
                    format!(
                        "Days({from}, {to}) is outside the week: both ends must be in 0..={}",
                        crate::model::DAYS_PER_WEEK
                    ),
                ));
            }
        }
        let signal = match &term.input {
            Input::Need(name) => Signal::Need(require(self.need_id(name), "need", name, owner)?),
            Input::Signal(name) => {
                Signal::Host(require(self.signal_id(name), "signal", name, owner)?)
            }
            Input::Hour => Signal::Hour,
            Input::BodyHour => Signal::BodyHour,
            Input::Week => Signal::Week,
            Input::Pleasure => Signal::Pleasure,
            Input::Arousal => Signal::Arousal,
            Input::Dominance => Signal::Dominance,
            Input::Trait(personality) => Signal::Trait(*personality),
            Input::Emotion(kind) => Signal::Emotion(*kind),
            Input::Affinity => Signal::Affinity,
            Input::Trust => Signal::Trust,
            Input::Respect => Signal::Respect,
            Input::Familiarity => Signal::Familiarity,
            Input::Distance => Signal::Distance,
            Input::SocialProof => Signal::SocialProof,
            Input::Skill(name) => {
                Signal::Skill(require(self.skill_id(name), "skill", name, owner)?)
            }
            Input::Surplus(name) => {
                Signal::Surplus(require(self.good_id(name), "good", name, owner)?)
            }
            Input::Stock(name) => Signal::Stock(require(self.good_id(name), "good", name, owner)?),
            Input::Field(field) => Signal::Field(*field),
            Input::Script(source) => Signal::Script(scripts.expression(owner, source)?),
        };
        Ok(Term {
            signal,
            curve: term.curve,
        })
    }

    fn add_trigger(
        &mut self,
        def: TriggerDef,
        scripts: &mut ScriptCompiler,
        names: &mut HashSet<String>,
    ) -> Result<(), DefsError> {
        let owner = format!("trigger '{}'", def.id);
        if !names.insert(def.id.clone()) {
            return Err(DefsError::Duplicate {
                kind: "trigger",
                id: def.id,
            });
        }
        if def.cooldown_hours.is_nan() || def.cooldown_hours < 0.0 {
            return Err(invalid(&owner, "cooldown_hours must be 0 or more"));
        }
        let on = self.trigger_kind(&owner, &def.on)?;
        let binds_no_actor = matches!(
            on,
            TriggerKind::Tick | TriggerKind::Hour(_) | TriggerKind::RumorReach { .. }
        );
        if let Some(area) = def.area {
            if area.min.iter().chain(&area.max).any(|v| !v.is_finite())
                || area.min[0] > area.max[0]
                || area.min[1] > area.max[1]
            {
                return Err(invalid(&owner, "area needs finite corners with min <= max"));
            }
            if binds_no_actor {
                return Err(invalid(
                    &owner,
                    "area needs an event that binds an actor; Tick, Hour and RumorReach bind none",
                ));
            }
        }
        if binds_no_actor && (!def.factions.is_empty() || !def.persons.is_empty()) {
            return Err(invalid(
                &owner,
                "factions and persons need an event that binds an actor; Tick, Hour and RumorReach bind none",
            ));
        }
        let mut factions = Vec::with_capacity(def.factions.len());
        for name in &def.factions {
            match self.faction_id(name) {
                Some(id) => factions.push(id),
                None => {
                    return Err(invalid(&owner, format!("unknown faction '{name}'")));
                }
            }
        }
        let condition = match def.condition.as_deref() {
            Some(source) => Some(scripts.expression(&format!("{owner} if"), source)?),
            None => None,
        };
        let then = scripts.statements(&owner, &def.then)?;
        self.triggers.push(TriggerSpec {
            id: def.id.clone(),
            on,
            condition,
            then,
            once: def.once,
            cooldown_hours: def.cooldown_hours,
            area: def.area,
            factions,
            persons: def.persons.clone(),
        });
        Ok(())
    }

    fn trigger_kind(&self, owner: &str, on: &TriggerOn) -> Result<TriggerKind, DefsError> {
        Ok(match on {
            TriggerOn::Tick => TriggerKind::Tick,
            TriggerOn::PersonDied => TriggerKind::PersonDied,
            TriggerOn::Hour(hour) => {
                if !(0.0..24.0).contains(hour) {
                    return Err(invalid(owner, "an Hour trigger needs an hour in [0, 24)"));
                }
                TriggerKind::Hour(*hour)
            }
            TriggerOn::Interaction(name) => TriggerKind::Interaction(require(
                self.interaction_id(name),
                "interaction",
                name,
                owner,
            )?),
            TriggerOn::TieLabel(label) => TriggerKind::TieLabel(*label),
            TriggerOn::RumorReach { deed, fraction } => {
                let deed = require(self.deed_id(deed), "deed", deed, owner)?;
                if !(*fraction > 0.0 && *fraction <= 1.0) {
                    return Err(invalid(owner, "fraction must be in (0, 1]"));
                }
                TriggerKind::RumorReach {
                    deed,
                    fraction: *fraction,
                }
            }
            TriggerOn::NormViolated(deed) => {
                TriggerKind::NormViolated(require(self.deed_id(deed), "deed", deed, owner)?)
            }
            TriggerOn::NeedBelow { need, below } => TriggerKind::NeedBelow {
                need: require(self.need_id(need), "need", need, owner)?,
                below: *below,
            },
            TriggerOn::Activity(name) => {
                TriggerKind::Activity(require(self.activity_id(name), "activity", name, owner)?)
            }
            TriggerOn::DialogueNode { conversation, node } => TriggerKind::DialogueNode {
                conversation: conversation.clone(),
                node: node.clone(),
            },
            TriggerOn::Custom(name) => TriggerKind::Custom(name.clone()),
        })
    }

    fn add_conversation(
        &mut self,
        def: ConversationRuleDef,
        scripts: &mut ScriptCompiler,
    ) -> Result<(), DefsError> {
        let owner = format!("conversation rule for '{}'", def.conversation);
        let condition = match def.condition.as_deref() {
            Some(source) => Some(scripts.expression(&owner, source)?),
            None => None,
        };
        self.conversations.push(ConversationSpec {
            conversation: def.conversation,
            priority: def.priority,
            condition,
        });
        Ok(())
    }

    fn add_node_effect(
        &mut self,
        def: NodeEffectDef,
        scripts: &mut ScriptCompiler,
    ) -> Result<(), DefsError> {
        let owner = format!("node effect '{}/{}'", def.conversation, def.node);
        let then = scripts.statements(&owner, &def.then)?;
        self.node_effects.push(NodeEffectSpec {
            conversation: def.conversation,
            node: def.node,
            then,
        });
        Ok(())
    }
}

/// The per-person state [`size_person_state`] sizes, bundled to stay inside clippy's type-complexity limit.
type PersonStateQuery<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static mut Needs,
        &'static mut Signals,
        &'static mut Opinions,
        Option<&'static mut crate::Stock>,
    ),
    With<Person>,
>;

/// Keeps every person's `Needs`, `Signals`, `Opinions` and `Stock` the length of the defs (plan D2). A
/// short vector grows with the defs' starting values; a long one is an error and is truncated. `Mut`
/// changes only when a length actually differs.
///
/// **`Stock` is added here too**, as a `Component` when the pack declares goods, so a host that adds a good
/// to its definitions file does not also have to remember to spawn one. A new `Stock`, and the slots a short
/// one gains, start at each good's [`GoodDef::initial`] (held at `Tuning::stock_ceiling`), exactly as a need
/// starts at its `initial`; a `Stock` of the right length is the host's own and is left alone.
pub fn size_person_state(
    defs: Res<SocietyDefs>,
    settings: Res<SocietySettings>,
    mut commands: Commands,
    mut people: PersonStateQuery,
) {
    let need_count = defs.needs.len();
    let signal_count = defs.signals.len();
    let topic_count = defs.topics.len();
    let good_count = defs.goods.len();
    let ceiling = settings.tuning.stock_ceiling;
    let starting = |slot: usize| defs.good_initial.get(slot).map_or(0.0, |&n| n.min(ceiling));
    for (entity, mut needs, mut signals, mut opinions, stock) in &mut people {
        // **Stock is sized with the rest of the per-person state**, so a host that adds a good to its
        // definitions file does not have to remember to spawn a component for it.
        match stock {
            Some(mut stock) => {
                let have = stock.0.len();
                if have > good_count {
                    stock.0.truncate(good_count);
                } else if have < good_count {
                    stock.0.extend((have..good_count).map(starting));
                }
            }
            None if good_count > 0 => {
                commands
                    .entity(entity)
                    .insert(crate::Stock((0..good_count).map(starting).collect()));
            }
            None => {}
        }
        let have = needs.0.len();
        if have > need_count {
            error!(
                "bevy_society: {entity} has {have} needs but the defs define {need_count}; truncating"
            );
            needs.0.truncate(need_count);
        } else if have < need_count {
            needs
                .0
                .extend(defs.needs.iter().skip(have).map(|spec| spec.initial));
        }
        let have = signals.0.len();
        if have > signal_count {
            error!(
                "bevy_society: {entity} has {have} signals but the defs define {signal_count}; truncating"
            );
            signals.0.truncate(signal_count);
        } else if have < signal_count {
            signals
                .0
                .extend(std::iter::repeat_n(0.0, signal_count - have));
        }
        let have = opinions.0.len();
        if have > topic_count {
            error!(
                "bevy_society: {entity} has {have} opinions but the defs define {topic_count}; truncating"
            );
            opinions.0.truncate(topic_count);
        } else if have < topic_count {
            opinions
                .0
                .extend(std::iter::repeat_n(Opinion::default(), topic_count - have));
        }
    }
}

/// A compiled need.
#[derive(Debug, Clone)]
pub(crate) struct NeedSpec {
    pub(crate) name: String,
    pub(crate) decay_per_day: f32,
    pub(crate) initial: f32,
}

/// A compiled topic.
#[derive(Debug, Clone)]
pub(crate) struct TopicSpec {
    pub(crate) name: String,
}

/// A compiled deed.
#[derive(Debug, Clone)]
pub(crate) struct DeedSpec {
    pub(crate) name: String,
    pub(crate) topic: TopicId,
    pub(crate) harm: f32,
}

/// A compiled faction.
#[derive(Debug, Clone)]
pub(crate) struct FactionSpec {
    pub(crate) name: String,
    pub(crate) ingroup_bias: f32,
}

/// A compiled activity.
#[derive(Debug, Clone)]
pub(crate) struct ActivitySpec {
    pub(crate) name: String,
    pub(crate) target: ActivityTarget,
    pub(crate) duration_hours: f32,
    pub(crate) rank: u8,
    /// The rank taken while a need is low; see [`UrgentDef`].
    pub(crate) urgent: Option<Urgent>,
    /// Whether a person doing this is out of everyone else's `near` list; see [`ActivityDef::unavailable`].
    pub(crate) unavailable: bool,
    pub(crate) weight: f32,
    pub(crate) considerations: Vec<Term>,
    pub(crate) satisfies: Vec<(NeedId, f32)>,
    pub(crate) interaction: Option<InteractionId>,
    /// Goods made per completed use.
    pub(crate) produces: Vec<(GoodId, f32)>,
    /// Goods used up per completed use.
    pub(crate) consumes: Vec<(GoodId, f32)>,
    pub(crate) barks: Vec<String>,
}

/// A compiled [`UrgentDef`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Urgent {
    pub(crate) need: NeedId,
    pub(crate) below: f32,
    pub(crate) rank: u8,
}

impl ActivitySpec {
    /// The rank this activity has for a person whose needs are `levels`: its own, raised to `urgent.rank`
    /// while the named need is under `urgent.below`.
    pub(crate) fn rank_for(&self, levels: &[f32]) -> u8 {
        match self.urgent {
            Some(urgent)
                if levels
                    .get(usize::from(urgent.need.0))
                    .is_some_and(|level| *level < urgent.below) =>
            {
                self.rank.max(urgent.rank)
            }
            _ => self.rank,
        }
    }
}

/// A compiled consideration: a signal through a curve.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Term {
    pub(crate) signal: Signal,
    pub(crate) curve: Curve,
}

/// A compiled signal, with ids resolved.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Signal {
    /// A need's level.
    Need(NeedId),
    /// A host-written signal value.
    Host(SignalId),
    /// Clock hour / 24.
    Hour,
    /// Body-clock hour / 24 ([`Input::BodyHour`]).
    BodyHour,
    /// Position in the week / 7 ([`Input::Week`]).
    Week,
    /// Mood pleasure.
    Pleasure,
    /// Mood arousal.
    Arousal,
    /// Mood dominance.
    Dominance,
    /// A personality trait.
    Trait(Trait),
    /// An emotion's intensity.
    Emotion(EmotionKind),
    /// Affinity toward the target.
    Affinity,
    /// Trust toward the target.
    Trust,
    /// Respect toward the target.
    Respect,
    /// Familiarity with the target.
    Familiarity,
    /// Distance to the target.
    Distance,
    /// Share of close ties doing the activity.
    SocialProof,
    /// A skill's level, read from the actor's personality.
    Skill(SkillId),
    /// The joint surplus a trade in this good would produce.
    Surplus(GoodId),
    /// How much of a good the actor holds.
    Stock(GoodId),
    /// A social field value.
    Field(FieldInput),
    /// A compiled Rhai expression.
    Script(ScriptId),
}

/// A compiled effect set.
#[derive(Debug, Clone)]
pub(crate) struct EffectsSpec {
    pub(crate) actor_to_target: TieDelta,
    pub(crate) target_to_actor: TieDelta,
    pub(crate) actor_emotion: Option<(EmotionKind, f32)>,
    pub(crate) target_emotion: Option<(EmotionKind, f32)>,
    pub(crate) actor_needs: Vec<(NeedId, f32)>,
    pub(crate) target_needs: Vec<(NeedId, f32)>,
    pub(crate) actor_gives: Vec<(GoodId, f32)>,
    pub(crate) target_gives: Vec<(GoodId, f32)>,
    pub(crate) importance: f32,
    pub(crate) script: Option<ScriptId>,
}

/// A compiled interaction.
#[derive(Debug, Clone)]
pub(crate) struct InteractionSpec {
    pub(crate) name: String,
    pub(crate) requires: Option<ScriptId>,
    pub(crate) accept: AcceptDef,
    pub(crate) on_accept: EffectsSpec,
    pub(crate) on_reject: EffectsSpec,
    pub(crate) influence: Vec<TopicId>,
    pub(crate) gossip: bool,
    pub(crate) deed: Option<DeedId>,
    pub(crate) contest: bool,
    pub(crate) barks: InteractionBarks,
}

/// A compiled trigger event.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum TriggerKind {
    /// Every tick.
    Tick,
    /// The clock crossing an hour.
    Hour(f32),
    /// A person died; the actor binding is the deceased.
    PersonDied,
    /// An interaction resolving.
    Interaction(InteractionId),
    /// A tie label changing to this label.
    TieLabel(TieLabel),
    /// A rumor of the deed reaching a fraction.
    RumorReach {
        /// The deed.
        deed: DeedId,
        /// The fraction.
        fraction: f32,
    },
    /// A norm violation for the deed.
    NormViolated(DeedId),
    /// A need falling below a level.
    NeedBelow {
        /// The need.
        need: NeedId,
        /// The threshold.
        below: f32,
    },
    /// An activity starting.
    Activity(ActivityId),
    /// A dialogue node being entered.
    DialogueNode {
        /// The conversation.
        conversation: String,
        /// The node.
        node: String,
    },
    /// A host-fired named event.
    Custom(String),
}

/// A compiled trigger.
#[derive(Debug, Clone)]
pub(crate) struct TriggerSpec {
    pub(crate) id: String,
    pub(crate) on: TriggerKind,
    pub(crate) condition: Option<ScriptId>,
    pub(crate) then: ScriptId,
    pub(crate) once: bool,
    pub(crate) cooldown_hours: f32,
    pub(crate) area: Option<TriggerArea>,
    pub(crate) factions: Vec<FactionId>,
    pub(crate) persons: Vec<u32>,
}

/// A compiled conversation rule.
#[derive(Debug, Clone)]
pub(crate) struct ConversationSpec {
    pub(crate) conversation: String,
    pub(crate) priority: i32,
    pub(crate) condition: Option<ScriptId>,
}

/// A compiled node effect.
#[derive(Debug, Clone)]
pub(crate) struct NodeEffectSpec {
    pub(crate) conversation: String,
    pub(crate) node: String,
    pub(crate) then: ScriptId,
}

fn invalid(owner: &str, message: impl Into<String>) -> DefsError {
    DefsError::Invalid {
        owner: owner.to_owned(),
        message: message.into(),
    }
}

fn require<T>(
    found: Option<T>,
    kind: &'static str,
    name: &str,
    owner: &str,
) -> Result<T, DefsError> {
    found.ok_or_else(|| DefsError::UnknownId {
        kind,
        id: name.to_owned(),
        owner: owner.to_owned(),
    })
}

/// Records a new id and returns its index. The index is the position the definition will take in
/// its `Vec`, so it must be the current length.
fn register(
    map: &mut HashMap<String, u16>,
    kind: &'static str,
    name: &str,
    index: usize,
) -> Result<u16, DefsError> {
    if name.is_empty() {
        return Err(invalid(kind, "an id must not be empty"));
    }
    if map.contains_key(name) {
        return Err(DefsError::Duplicate {
            kind,
            id: name.to_owned(),
        });
    }
    let id = u16::try_from(index).map_err(|_| {
        invalid(
            &format!("{kind} '{name}'"),
            "too many definitions of this kind (limit 65536)",
        )
    })?;
    map.insert(name.to_owned(), id);
    Ok(id)
}

fn check_target(owner: &str, target: &ActivityTarget) -> Result<(), DefsError> {
    if let ActivityTarget::Bound(name) = target
        && name.trim().is_empty()
    {
        return Err(invalid(owner, "a Bound target needs a name"));
    }
    if let ActivityTarget::Wander(radius) = target
        && (radius.is_nan() || *radius < 0.0)
    {
        return Err(invalid(owner, "Wander radius must be 0 or more"));
    }
    if matches!(target, ActivityTarget::Gradient(..)) && !FIELDS_ENABLED {
        return Err(invalid(
            owner,
            "a Gradient target needs the `fields` feature",
        ));
    }
    Ok(())
}

fn check_input(owner: &str, input: &Input, target: &ActivityTarget) -> Result<(), DefsError> {
    let person_only = matches!(
        input,
        Input::Affinity
            | Input::Trust
            | Input::Respect
            | Input::Familiarity
            | Input::SocialProof
            | Input::Surplus(_)
    );
    if person_only && !matches!(target, ActivityTarget::Person) {
        return Err(invalid(owner, format!("{input:?} needs a Person target")));
    }
    if matches!(input, Input::Distance)
        && !matches!(
            target,
            ActivityTarget::Place(_)
                | ActivityTarget::Home
                | ActivityTarget::Bound(_)
                | ActivityTarget::Person
        )
    {
        return Err(invalid(
            owner,
            "Distance needs a Place, Home, Bound or Person target",
        ));
    }
    if matches!(input, Input::Field(_)) && !FIELDS_ENABLED {
        return Err(invalid(owner, "field inputs need the `fields` feature"));
    }
    Ok(())
}

/// Checks a bark template: only `{self}`, `{target}`, `{subject}` and `{place}` may appear in braces.
fn check_template(owner: &str, text: &str) -> Result<(), DefsError> {
    let mut rest = text;
    while let Some(position) = rest.find(['{', '}']) {
        let tail = &rest[position..];
        if tail.starts_with('}') {
            return Err(invalid(owner, format!("stray '}}' in bark '{text}'")));
        }
        let Some(end) = tail.find('}') else {
            return Err(invalid(owner, format!("unclosed '{{' in bark '{text}'")));
        };
        let key = &tail[1..end];
        if !matches!(key, "self" | "target" | "subject" | "place") {
            return Err(invalid(
                owner,
                format!("unknown placeholder '{{{key}}}' in bark '{text}'"),
            ));
        }
        rest = &tail[end + 1..];
    }
    Ok(())
}

fn default_ingroup_bias() -> f32 {
    0.2
}

fn one() -> f32 {
    1.0
}