agent-sdk-core 0.1.0-alpha.4

Product-neutral primitive kernel and contracts for a Rust-first Agent SDK.
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
//! Feature-layer agent-pool coordination over runs, messages, wake conditions, and
//! subscriptions. Use this module for generic run-to-run coordination without
//! introducing workflow-engine or product swarm behavior. Side-effecting operations may
//! update pool membership, append source-run journal records, and publish agent-pool
//! events through the configured runtime ports.
//!
use std::{
    collections::{BTreeMap, BTreeSet, VecDeque},
    sync::{Arc, Mutex},
};

use serde::{Deserialize, Serialize};

use crate::{
    domain::{
        AgentError, AgentErrorKind, AgentId, AgentPoolId, ContentRef, DestinationKind,
        DestinationRef, EffectId, EntityRef, EventId, IdempotencyKey, MessageId, PolicyRef,
        PrivacyClass, RetryClassification, RunId, SourceKind, SourceRef, SpanId, TopicId, TraceId,
        WakeConditionId,
    },
    effect::{EffectIntent, EffectKind, EffectResult, EffectTerminalStatus},
    event::{
        AgentEvent, CompiledEventFilter, ContentCaptureMode, EVENT_SCHEMA_VERSION,
        EventCorrelation, EventDeliverySemantics, EventEnvelope, EventFamily, EventFilter,
        EventFilterSet, EventFrame, EventKind, EventStreamScope, PayloadAccessMode,
    },
    event_bus::AgentEventStream,
    journal::{
        AgentPoolLifecycleStatus, AgentPoolRecord, EventIndexProjection, JOURNAL_SCHEMA_VERSION,
        JournalCursor, JournalRecord, JournalRecordKind, JournalRecordPayload,
        RunMessageAddressTargetRecord, RunMessageDeliveryStatus, RunMessageRecord, WakeRecord,
        WakeResumeInputPolicyRecord, WakeTriggerStatus,
    },
    run::RunRequest,
    run_handle::RunHandle,
    runtime::AgentRuntime,
};

#[derive(Clone)]
/// Holds agent pool application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct AgentPool {
    pool_id: AgentPoolId,
    runtime: AgentRuntime,
    store: Arc<dyn AgentPoolStore>,
}

impl AgentPool {
    /// Starts a builder for this application::agent_pool value.
    /// Building is data-only; runtime side effects occur only when a
    /// later coordinator or host port executes the built configuration.
    pub fn builder(pool_id: AgentPoolId) -> AgentPoolBuilder {
        AgentPoolBuilder {
            pool_id,
            runtime: None,
            message_policy: AgentPoolMessagePolicy::bounded_defaults(),
            wake_policy: AgentPoolWakePolicy::safe_defaults(),
            policy_refs: Vec::new(),
            store: None,
        }
    }

    /// Returns the pool id currently held by this value.
    /// This is a data-only accessor and does not change membership or wake state.
    pub fn pool_id(&self) -> &AgentPoolId {
        &self.pool_id
    }

    /// Starts a run through the shared runtime and joins it to this pool.
    /// Runtime registration and provider-loop effects stay in `AgentRuntime`;
    /// the pool side effect is membership tracking for coordination.
    pub fn start_run(&self, request: RunRequest) -> Result<RunHandle, AgentError> {
        let handle = self.runtime.start_run(request.clone())?;
        self.join_run(AgentPoolMember::new(request.run_id, request.agent_id))?;
        Ok(handle)
    }

    /// Join run.
    /// This records pool membership in the coordinator so later pool messages and subscriptions
    /// can target the run.
    pub fn join_run(&self, member: AgentPoolMember) -> Result<(), AgentError> {
        let should_create = {
            let snapshot = self.snapshot()?;
            !snapshot.created
        };

        if should_create {
            self.append_pool_record(
                &member.run_id,
                &member.agent_id,
                AgentPoolLifecycleStatus::Created,
                EventKind::AgentPoolCreated,
            )?;
            self.store.record_pool_created(&self.pool_id)?;
        }

        self.store.join_member(&self.pool_id, member.clone())?;

        self.append_pool_record(
            &member.run_id,
            &member.agent_id,
            AgentPoolLifecycleStatus::RunJoined,
            EventKind::AgentPoolRunJoined,
        )?;
        Ok(())
    }

    /// Returns the members currently held by this value.
    /// This reads current pool membership without starting, stopping, or messaging runs.
    pub fn members(&self) -> Result<Vec<AgentPoolMember>, AgentError> {
        Ok(self.snapshot()?.members)
    }

    /// Records that a run has left the pool.
    /// This removes membership from the shared store, appends a lifecycle record, and publishes
    /// a pool event. It does not cancel or otherwise mutate the run itself.
    pub fn leave_run(&self, run_id: &RunId) -> Result<AgentPoolMember, AgentError> {
        let (member, _) = self.store.leave_member(&self.pool_id, run_id)?;
        self.append_pool_record(
            &member.run_id,
            &member.agent_id,
            AgentPoolLifecycleStatus::RunLeft,
            EventKind::AgentPoolRunLeft,
        )?;
        Ok(member)
    }

    /// Sends a run message through the pool coordinator.
    /// This resolves the addressed members, applies pool message policy, appends accepted
    /// and terminal delivery records to the source run journal, publishes the matching
    /// agent-pool events, and deduplicates repeated calls by idempotency key.
    pub fn send(&self, message: RunMessage) -> Result<MessageReceipt, AgentError> {
        if let Some(receipt) = self
            .store
            .message_receipt(&self.pool_id, &message.idempotency_key)?
        {
            return Ok(receipt);
        }

        let delivered_to = self.resolve_address(&message);
        let terminal_status = if message.expires_at_millis == Some(0) {
            MessageStatus::Expired
        } else if delivered_to.is_empty() {
            MessageStatus::Failed
        } else {
            MessageStatus::Delivered
        };

        if terminal_status == MessageStatus::Expired {
            let receipt =
                self.record_message_status(&message, MessageStatus::Expired, Vec::new())?;
            return Ok(receipt);
        }

        if terminal_status == MessageStatus::Failed {
            let receipt =
                self.record_message_status(&message, MessageStatus::Failed, Vec::new())?;
            return Ok(receipt);
        }

        self.record_message_status(&message, MessageStatus::Accepted, delivered_to.clone())?;
        let receipt =
            self.record_message_status(&message, MessageStatus::Delivered, delivered_to)?;
        Ok(receipt)
    }

    /// Records one run-message status transition.
    /// This appends the status record to the source run journal, publishes the matching
    /// agent-pool event on the runtime event bus, and returns a receipt carrying the journal
    /// cursor. Use [`AgentPool::send`] for the full accept-to-terminal delivery flow.
    pub fn record_message_status(
        &self,
        message: &RunMessage,
        status: MessageStatus,
        delivered_to: Vec<RunId>,
    ) -> Result<MessageReceipt, AgentError> {
        let source_member = self.member(&message.from)?;
        let journal = self.runtime.journal_port(&message.from)?;
        let record = self.run_message_record(message, status.clone(), delivered_to.clone())?;
        let cursor = journal.append(record)?;
        let frame = self.publish_agent_pool_event(
            message.from.clone(),
            source_member.agent_id,
            status.event_kind(),
            Some(message.message_id.clone()),
            None,
            EntityRef::message(message.message_id.clone()),
            message.target_related_refs(&delivered_to),
            Some(message.to.destination_ref.clone()),
            message.policy_refs.clone(),
            Some(cursor.clone()),
            status.redacted_summary(),
        )?;

        let receipt = MessageReceipt {
            message_id: message.message_id.clone(),
            status,
            delivered_to,
            journal_cursor: Some(cursor),
        };
        self.store
            .record_message(&self.pool_id, message.clone(), receipt.clone())?;
        self.trigger_matching_wakes(&frame)?;
        Ok(receipt)
    }

    /// Subscribe.
    /// This creates a read-only subscription scoped by pool membership and the supplied filter.
    pub fn subscribe(
        &self,
        filter: EventFilter,
        cursor: Option<crate::event::EventCursor>,
    ) -> Result<AgentEventStream, AgentError> {
        let compiled = self.compile_scoped_filter(filter)?;
        self.runtime.subscribe_events(compiled, cursor)
    }

    /// Computes or returns compile scoped filter for the
    /// application::agent_pool contract without external I/O or side effects.
    pub fn compile_scoped_filter(
        &self,
        filter: EventFilter,
    ) -> Result<CompiledEventFilter, AgentError> {
        self.scope_filter(filter).compile()
    }

    /// Returns scope filter derived from the supplied state.
    /// This operates on the named coordinator state or selected port; it does not create a
    /// parallel runtime path.
    pub fn scope_filter(&self, mut filter: EventFilter) -> EventFilter {
        let allowed_runs = self.observable_member_runs();
        filter.run_ids = intersect_run_ids(&filter.run_ids, &allowed_runs);
        let envelope_only = self
            .snapshot()
            .map(|snapshot| snapshot.wake_policy.envelope_only)
            .unwrap_or(true);
        if envelope_only {
            filter.payload_access = PayloadAccessMode::EnvelopeOnly;
        }
        filter
    }

    /// Registers a wake condition for a pool member run.
    /// This mutates the pool's wake registry and dedupe index, scopes the event filter to current
    /// members, and may poll the configured event subscription port to trigger immediately.
    pub fn suspend_until(
        &self,
        run_id: RunId,
        condition: WakeCondition,
    ) -> Result<WakeRegistration, AgentError> {
        if run_id != condition.run_id {
            return Err(AgentError::new(
                AgentErrorKind::InvalidStateTransition,
                RetryClassification::NotRetryable,
                "wake registration run_id must match condition run_id",
            ));
        }

        if let Some(registration) = self
            .store
            .wake_registration(&self.pool_id, &condition.idempotency_key)?
        {
            return Ok(registration);
        }

        self.member(&condition.run_id)?;
        let compiled = self.compile_scoped_filter(condition.filter.clone())?;
        let mut registration = self.record_wake_status(
            &condition,
            compiled.clone(),
            WakeRegistrationStatus::Registered,
            None,
        )?;

        if condition.timeout_millis == Some(0) {
            registration = self.record_wake_status(
                &condition,
                compiled,
                WakeRegistrationStatus::TimedOut,
                None,
            )?;
        } else if let Some(frame) = self
            .runtime
            .subscribe_events(compiled.clone(), None)?
            .next()
        {
            registration = self.record_wake_status(
                &condition,
                compiled,
                WakeRegistrationStatus::Triggered,
                Some(frame.event.envelope.event_id),
            )?;
        }

        Ok(registration)
    }

    /// Polls a registered wake condition for a matching event.
    /// This reads and may update pool wake state through `record_wake_status`; it creates a
    /// read-only event subscription but does not cancel or advance the target run.
    pub fn poll_wake(
        &self,
        condition_id: &WakeConditionId,
    ) -> Result<WakeRegistration, AgentError> {
        let stored = self
            .store
            .wake(&self.pool_id, condition_id)?
            .ok_or_else(|| AgentError::contract_violation("wake condition is not registered"))?;

        if stored.registration.status != WakeRegistrationStatus::Registered {
            return Ok(stored.registration);
        }

        let Some(frame) = self
            .runtime
            .subscribe_events(stored.compiled_filter.clone(), None)?
            .next()
        else {
            return Ok(stored.registration);
        };

        self.record_wake_status(
            &stored.condition,
            stored.compiled_filter,
            WakeRegistrationStatus::Triggered,
            Some(frame.event.envelope.event_id),
        )
    }

    /// Cancel wake.
    /// This marks a registered wake condition as cancelled in pool state; it does not cancel
    /// the run itself.
    pub fn cancel_wake(
        &self,
        condition_id: &WakeConditionId,
    ) -> Result<WakeRegistration, AgentError> {
        let stored = self
            .store
            .wake(&self.pool_id, condition_id)?
            .ok_or_else(|| AgentError::contract_violation("wake condition is not registered"))?;
        self.record_wake_status(
            &stored.condition,
            stored.compiled_filter,
            WakeRegistrationStatus::Cancelled,
            None,
        )
    }

    fn record_wake_status(
        &self,
        condition: &WakeCondition,
        compiled_filter: CompiledEventFilter,
        status: WakeRegistrationStatus,
        matched_event_id: Option<EventId>,
    ) -> Result<WakeRegistration, AgentError> {
        let member = self.member(&condition.run_id)?;
        let journal = self.runtime.journal_port(&condition.run_id)?;
        let wake_record = WakeRecord {
            condition_id: condition.condition_id.clone(),
            run_id: condition.run_id.clone(),
            event_filter_fingerprint: compiled_filter.filter_fingerprint.clone(),
            timeout_millis: condition.timeout_millis,
            resume_policy: condition.resume_with.clone().into(),
            trigger_status: status.clone().into(),
            policy_refs: condition.policy_refs.clone(),
            idempotency_key: condition.idempotency_key.clone(),
            matched_event_id,
        };
        let record = self.journal_record(
            condition.run_id.clone(),
            member.agent_id.clone(),
            JournalRecordKind::Wake,
            "agent_pool",
            status.event_kind().wire_name(),
            EntityRef::wake_condition(condition.condition_id.clone()),
            vec![EntityRef::run(condition.run_id.clone())],
            condition.policy_refs.clone(),
            Vec::new(),
            Some(condition.idempotency_key.clone()),
            JournalRecordPayload::Wake(wake_record),
        )?;
        let cursor = journal.append(record)?;
        self.publish_agent_pool_event(
            condition.run_id.clone(),
            member.agent_id,
            status.event_kind(),
            None,
            Some(condition.condition_id.clone()),
            EntityRef::wake_condition(condition.condition_id.clone()),
            vec![EntityRef::run(condition.run_id.clone())],
            Some(DestinationRef::with_kind(
                DestinationKind::Agent,
                condition.run_id.as_str(),
            )),
            condition.policy_refs.clone(),
            Some(cursor.clone()),
            status.redacted_summary(),
        )?;

        let registration = WakeRegistration {
            condition_id: condition.condition_id.clone(),
            run_id: condition.run_id.clone(),
            status,
            journal_cursor: Some(cursor),
        };

        self.store.record_wake(
            &self.pool_id,
            condition.clone(),
            compiled_filter,
            registration.clone(),
        )?;

        Ok(registration)
    }

    fn append_pool_record(
        &self,
        run_id: &RunId,
        agent_id: &AgentId,
        status: AgentPoolLifecycleStatus,
        event_kind: EventKind,
    ) -> Result<(), AgentError> {
        let journal = self.runtime.journal_port(run_id)?;
        let snapshot = self.snapshot()?;
        let member_run_ids = snapshot
            .members
            .iter()
            .map(|member| member.run_id.clone())
            .collect::<Vec<_>>();
        let topics = snapshot.topics;
        let policy_refs = snapshot.policy_refs;

        let record = AgentPoolRecord {
            pool_id: self.pool_id.clone(),
            member_run_ids,
            topics,
            policy_refs: policy_refs.clone(),
            lifecycle_status: status,
        };
        let journal_record = self.journal_record(
            run_id.clone(),
            agent_id.clone(),
            JournalRecordKind::AgentPool,
            "agent_pool",
            event_kind.wire_name(),
            EntityRef::run(run_id.clone()),
            Vec::new(),
            policy_refs.clone(),
            Vec::new(),
            None,
            JournalRecordPayload::AgentPool(record),
        )?;
        let cursor = journal.append(journal_record)?;
        self.publish_agent_pool_event(
            run_id.clone(),
            agent_id.clone(),
            event_kind,
            None,
            None,
            EntityRef::run(run_id.clone()),
            Vec::new(),
            Some(DestinationRef::with_kind(
                DestinationKind::Agent,
                run_id.as_str(),
            )),
            policy_refs,
            Some(cursor),
            "agent pool membership updated",
        )?;
        Ok(())
    }

    fn run_message_record(
        &self,
        message: &RunMessage,
        status: MessageStatus,
        delivered_to: Vec<RunId>,
    ) -> Result<JournalRecord, AgentError> {
        let member = self.member(&message.from)?;
        let mut effect_intent = None;
        let mut effect_result = None;
        let effect_id = EffectId::new(format!(
            "effect.run_message.{}",
            message.message_id.as_str()
        ));

        if status == MessageStatus::Accepted {
            let mut intent = EffectIntent::new(
                effect_id.clone(),
                EffectKind::RunMessageDelivery,
                EntityRef::message(message.message_id.clone()),
                SourceRef::with_kind(SourceKind::Sdk, "source.sdk.agent_pool"),
                "run message delivery intent",
            );
            intent.destination = Some(message.to.destination_ref.clone());
            intent.policy_refs = message.policy_refs.clone();
            intent.idempotency_key = Some(message.idempotency_key.clone());
            intent.content_refs = vec![message.content_ref.clone()];
            effect_intent = Some(intent);
        }

        if status.is_terminal_delivery() {
            effect_result = Some(EffectResult {
                effect_id,
                terminal_status: status.effect_terminal_status(),
                external_operation_id: None,
                reconciliation_ref: None,
                error_ref: None,
                content_refs: vec![message.content_ref.clone()],
                redacted_summary: status.redacted_summary().to_string(),
            });
        }

        let record = RunMessageRecord {
            message_id: message.message_id.clone(),
            source_run_id: message.from.clone(),
            address_target: message.to.target.clone().into(),
            content_ref: message.content_ref.clone(),
            correlation: message.correlation.clone(),
            reply_to: message.reply_to.clone(),
            delivery_status: status.clone().into(),
            delivered_to: delivered_to.clone(),
            policy_refs: message.policy_refs.clone(),
            idempotency_key: message.idempotency_key.clone(),
            effect_intent,
            effect_result,
        };

        self.journal_record(
            message.from.clone(),
            member.agent_id,
            JournalRecordKind::RunMessage,
            "agent_pool",
            status.event_kind().wire_name(),
            EntityRef::message(message.message_id.clone()),
            message.target_related_refs(&delivered_to),
            message.policy_refs.clone(),
            vec![message.content_ref.clone()],
            Some(message.idempotency_key.clone()),
            JournalRecordPayload::RunMessage(record),
        )
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "journal-backed pool records intentionally spell out lineage, refs, and payload until a dedicated record-builder API replaces this private helper"
    )]
    fn journal_record(
        &self,
        run_id: RunId,
        agent_id: AgentId,
        record_kind: JournalRecordKind,
        event_family: impl Into<String>,
        event_kind: impl Into<String>,
        subject_ref: EntityRef,
        related_refs: Vec<EntityRef>,
        _policy_refs: Vec<PolicyRef>,
        content_refs: Vec<ContentRef>,
        idempotency_key: Option<IdempotencyKey>,
        payload: JournalRecordPayload,
    ) -> Result<JournalRecord, AgentError> {
        let journal_seq = self.runtime.next_journal_seq();
        let source = SourceRef::with_kind(SourceKind::Sdk, "source.sdk.agent_pool");
        let fingerprint = self
            .runtime
            .run_snapshot(&run_id)
            .map(|snapshot| snapshot.runtime_package_fingerprint.as_str().to_string())
            .unwrap_or_else(|_| "runtime.package.fingerprint.agent_pool".to_string());
        let session_id = self
            .runtime
            .run_snapshot(&run_id)
            .ok()
            .and_then(|snapshot| snapshot.session_id);
        let event_family = event_family.into();
        let event_kind = event_kind.into();

        Ok(JournalRecord {
            journal_schema_version: JOURNAL_SCHEMA_VERSION,
            journal_seq,
            record_id: format!("journal.record.agent_pool.{journal_seq}"),
            record_kind,
            run_id: run_id.clone(),
            session_id: session_id.clone(),
            agent_id: agent_id.clone(),
            turn_id: None,
            attempt_id: None,
            subject_ref: subject_ref.clone(),
            related_refs: related_refs.clone(),
            causal_refs: Vec::new(),
            source: source.clone(),
            destination: Some(DestinationRef::with_kind(
                DestinationKind::Journal,
                "destination.journal.agent_pool",
            )),
            correlation_keys: Vec::new(),
            tags: vec!["feature:agent_pool".to_string()],
            delivery_semantics: "journal_backed".to_string(),
            event_index: EventIndexProjection {
                run_id,
                session_id,
                agent_id,
                turn_id: None,
                event_family,
                event_kind,
                source,
                destination: Some(DestinationRef::with_kind(
                    DestinationKind::EventStream,
                    "destination.event_stream.agent_pool",
                )),
                subject_ref,
                related_refs,
                correlation_keys: Vec::new(),
                tags: vec!["feature:agent_pool".to_string()],
                privacy_class: PrivacyClass::ContentRefsOnly,
                delivery_semantics: "journal_backed".to_string(),
            },
            timestamp_millis: journal_seq,
            runtime_package_fingerprint: fingerprint,
            privacy: PrivacyClass::ContentRefsOnly,
            content_refs,
            redaction_policy_id: "redaction.agent_pool.default".to_string(),
            idempotency_key,
            dedupe_key: None,
            checkpoint_ref: None,
            payload,
        })
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "event publication mirrors the durable event envelope fields so lineage stays explicit at the call site"
    )]
    fn publish_agent_pool_event(
        &self,
        run_id: RunId,
        agent_id: AgentId,
        event_kind: EventKind,
        message_id: Option<MessageId>,
        wake_condition_id: Option<WakeConditionId>,
        subject_ref: EntityRef,
        mut related_refs: Vec<EntityRef>,
        destination: Option<DestinationRef>,
        policy_refs: Vec<PolicyRef>,
        journal_cursor: Option<JournalCursor>,
        summary: impl Into<String>,
    ) -> Result<EventFrame, AgentError> {
        if let Some(condition_id) = wake_condition_id {
            related_refs.push(EntityRef::wake_condition(condition_id));
        }
        let event_counter = self.store.next_event_sequence(&self.pool_id)?;
        let fingerprint = self
            .runtime
            .run_snapshot(&run_id)
            .map(|snapshot| snapshot.runtime_package_fingerprint.as_str().to_string())
            .unwrap_or_else(|_| "runtime.package.fingerprint.agent_pool".to_string());
        let session_id = self
            .runtime
            .run_snapshot(&run_id)
            .ok()
            .and_then(|snapshot| snapshot.session_id);
        let event = AgentEvent::with_redacted_summary(
            EventEnvelope {
                schema_version: EVENT_SCHEMA_VERSION,
                event_id: EventId::new(format!(
                    "event.agent_pool.{}.{}",
                    self.pool_id.as_str(),
                    event_counter
                )),
                event_seq: 0,
                event_family: EventFamily::AgentPool,
                event_kind,
                payload_schema_version: 1,
                timestamp: format!("1970-01-01T00:00:{event_counter:02}Z"),
                recorded_at: format!("1970-01-01T00:00:{event_counter:02}Z"),
                run_id,
                session_id,
                agent_id,
                turn_id: None,
                attempt_id: None,
                message_id,
                context_item_id: None,
                trace_id: TraceId::new(format!("trace.agent_pool.{}", self.pool_id.as_str())),
                span_id: SpanId::new(format!(
                    "span.agent_pool.{}.{}",
                    self.pool_id.as_str(),
                    event_counter
                )),
                parent_event_id: None,
                caused_by: None,
                subject_ref,
                related_refs,
                causal_refs: Vec::new(),
                correlation: EventCorrelation::default(),
                tags: vec![crate::event::EventTag::new("feature:agent_pool")],
                source: SourceRef::with_kind(SourceKind::Sdk, "source.sdk.agent_pool"),
                destination,
                policy_refs,
                journal_cursor,
                state_before: None,
                state_after: None,
                delivery_semantics: EventDeliverySemantics::JournalBacked,
                privacy: PrivacyClass::ContentRefsOnly,
                content_capture: ContentCaptureMode::Off,
                redaction_policy_id: "redaction.agent_pool.default".to_string(),
                runtime_package_fingerprint: fingerprint,
            },
            summary,
        );
        let frame = EventFrame {
            cursor: event.envelope.cursor(EventStreamScope::All),
            event,
            archive_cursor: None,
            overflow: None,
        };
        self.runtime
            .event_bus_port(&frame.event.envelope.run_id)?
            .publish(frame.clone())?;
        Ok(frame)
    }

    fn resolve_address(&self, message: &RunMessage) -> Vec<RunId> {
        let Ok(snapshot) = self.snapshot() else {
            return Vec::new();
        };
        let members = snapshot
            .members
            .iter()
            .cloned()
            .map(|member| (member.run_id.clone(), member))
            .collect::<BTreeMap<_, _>>();
        let topics = topics_from_members(&snapshot.members);

        if !members.contains_key(&message.from) || !snapshot.message_policy.allows(message) {
            return Vec::new();
        }

        let mut candidates = match &message.to.target {
            RunAddressTarget::Run { run_id } => vec![run_id.clone()],
            RunAddressTarget::Agent { agent_id } => members
                .values()
                .filter(|member| &member.agent_id == agent_id)
                .map(|member| member.run_id.clone())
                .collect::<Vec<_>>(),
            RunAddressTarget::Topic { topic_id } => topics
                .get(topic_id)
                .map(|runs| runs.iter().cloned().collect::<Vec<_>>())
                .unwrap_or_default(),
            RunAddressTarget::Pool { pool_id } if pool_id == &self.pool_id => {
                members.keys().cloned().collect::<Vec<_>>()
            }
            RunAddressTarget::Pool { .. } => Vec::new(),
        };

        candidates.retain(|run_id| {
            members
                .get(run_id)
                .is_some_and(|member| member.allows_message_policies(&message.policy_refs))
        });

        if matches!(message.to.target, RunAddressTarget::Pool { .. })
            && !snapshot.message_policy.include_sender_in_pool_broadcast
        {
            candidates.retain(|run_id| run_id != &message.from);
        }

        candidates.sort();
        candidates.dedup();
        candidates
    }

    fn observable_member_runs(&self) -> Vec<RunId> {
        self.snapshot()
            .map(|snapshot| {
                snapshot
                    .members
                    .iter()
                    .filter(|member| member.allows_message_policies(&snapshot.policy_refs))
                    .map(|member| member.run_id.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    fn member(&self, run_id: &RunId) -> Result<AgentPoolMember, AgentError> {
        self.snapshot()?
            .members
            .into_iter()
            .find(|member| &member.run_id == run_id)
            .ok_or_else(|| {
                AgentError::new(
                    AgentErrorKind::InvalidStateTransition,
                    RetryClassification::NotRetryable,
                    "run is not a member of this agent pool",
                )
            })
    }

    /// Rehydrates the current durable pool snapshot from the configured store.
    /// This returns only pool-backed membership, message, wake, policy, and cursor state; it
    /// does not subscribe to the global event bus or synthesize missing records.
    pub fn snapshot(&self) -> Result<AgentPoolSnapshot, AgentError> {
        self.store.snapshot(&self.pool_id)
    }

    fn trigger_matching_wakes(&self, frame: &EventFrame) -> Result<(), AgentError> {
        if matches!(
            frame.event.envelope.event_kind,
            EventKind::WakeConditionRegistered
                | EventKind::WakeConditionTriggered
                | EventKind::WakeConditionTimedOut
                | EventKind::WakeConditionCancelled
                | EventKind::WakeConditionFailed
        ) {
            return Ok(());
        }

        let wakes = self.snapshot()?.wakes;
        for wake in wakes
            .into_iter()
            .filter(|wake| wake.registration.status == WakeRegistrationStatus::Registered)
        {
            if wake.compiled_filter.matches_envelope(&frame.event.envelope) {
                self.record_wake_status(
                    &wake.condition,
                    wake.compiled_filter,
                    WakeRegistrationStatus::Triggered,
                    Some(frame.event.envelope.event_id.clone()),
                )?;
            }
        }
        Ok(())
    }

    /// Watches durable pool-store changes after the supplied cursor.
    /// This is a pool-scoped coordination-record stream, not a global event bus.
    pub fn watch_pool(
        &self,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> Result<AgentPoolStoreStream, AgentError> {
        self.store.watch(&self.pool_id, cursor)
    }
}

#[derive(Clone)]
/// Holds agent pool builder application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct AgentPoolBuilder {
    pool_id: AgentPoolId,
    runtime: Option<AgentRuntime>,
    message_policy: AgentPoolMessagePolicy,
    wake_policy: AgentPoolWakePolicy,
    policy_refs: Vec<PolicyRef>,
    store: Option<Arc<dyn AgentPoolStore>>,
}

impl AgentPoolBuilder {
    /// Returns an updated value with runtime configured.
    /// This stores the runtime used by the pool builder; no run is started until `start_run` is
    /// called.
    pub fn runtime(mut self, runtime: AgentRuntime) -> Self {
        self.runtime = Some(runtime);
        self
    }

    /// Returns an updated value with message policy configured.
    /// This is builder configuration only and performs no I/O or run coordination.
    pub fn message_policy(mut self, policy: AgentPoolMessagePolicy) -> Self {
        self.message_policy = policy;
        self
    }

    /// Returns an updated value with wake policy configured.
    /// This is builder configuration only and performs no I/O or run coordination.
    pub fn wake_policy(mut self, policy: AgentPoolWakePolicy) -> Self {
        self.wake_policy = policy;
        self
    }

    /// Returns an updated value with policy ref configured.
    /// This sets the policy reference on the coordination value and performs no I/O.
    pub fn policy_ref(mut self, policy_ref: PolicyRef) -> Self {
        self.policy_refs.push(policy_ref);
        self
    }

    /// Returns an updated value with the pool store configured.
    /// The store is the shared coordination authority for membership,
    /// messages, wake registrations, dedupe, rehydration, and pool watch.
    pub fn store<S>(mut self, store: S) -> Self
    where
        S: AgentPoolStore + 'static,
    {
        self.store = Some(Arc::new(store));
        self
    }

    /// Returns an updated value with a dynamically dispatched pool store.
    /// Use this when sharing one store instance across multiple pool handles
    /// or when a host provides its own adapter.
    pub fn shared_store(mut self, store: Arc<dyn AgentPoolStore>) -> Self {
        self.store = Some(store);
        self
    }

    /// Finishes builder validation and returns the configured value.
    /// This is data-only unless the surrounding builder explicitly
    /// documents adapter or store access.
    pub fn build(self) -> Result<AgentPool, AgentError> {
        let runtime = self
            .runtime
            .ok_or_else(|| AgentError::host_configuration_needed("agent pool requires runtime"))?;
        let store = self
            .store
            .unwrap_or_else(|| Arc::new(InMemoryAgentPoolStore::default()));
        store.open_pool(
            self.pool_id.clone(),
            AgentPoolStoreConfig {
                message_policy: self.message_policy,
                wake_policy: self.wake_policy,
                policy_refs: self.policy_refs,
            },
        )?;
        Ok(AgentPool {
            pool_id: self.pool_id,
            runtime,
            store,
        })
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Store configuration for one logical agent pool.
/// This is durable pool metadata; constructing it does not open a
/// concrete store or start coordination work.
pub struct AgentPoolStoreConfig {
    /// Message policy used when resolving pool messages.
    pub message_policy: AgentPoolMessagePolicy,
    /// Wake policy used when scoping wake filters.
    pub wake_policy: AgentPoolWakePolicy,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Policy refs that scope pool-level observation and membership.
    pub policy_refs: Vec<PolicyRef>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Durable cursor for pool-scoped store records.
/// Cursors are scoped by the pool passed to `watch` and should not be
/// used as global event or journal cursors.
pub struct AgentPoolStoreCursor {
    /// Monotonic sequence within a logical pool store partition.
    pub sequence: u64,
}

impl AgentPoolStoreCursor {
    /// Builds the initial cursor before any pool-store record.
    pub fn start() -> Self {
        Self { sequence: 0 }
    }

    /// Builds a cursor for a known sequence.
    pub fn new(sequence: u64) -> Self {
        Self { sequence }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Rehydratable snapshot for one logical agent pool.
/// The snapshot is derived only from durable store records; callers must
/// not synthesize members, messages, or wakes outside the store.
pub struct AgentPoolSnapshot {
    /// Stable pool id used for typed lineage, lookup, or dedupe.
    pub pool_id: AgentPoolId,
    /// Whether the pool-created lifecycle record has been persisted.
    pub created: bool,
    /// Current members visible in the pool.
    pub members: Vec<AgentPoolMember>,
    /// Current topic ids known to the pool.
    pub topics: Vec<TopicId>,
    /// Message policy used when resolving pool messages.
    pub message_policy: AgentPoolMessagePolicy,
    /// Wake policy used when scoping wake filters.
    pub wake_policy: AgentPoolWakePolicy,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Policy refs that scope pool-level observation and membership.
    pub policy_refs: Vec<PolicyRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Durable run-message status records known to the pool.
    pub messages: Vec<AgentPoolStoredMessage>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Durable wake registrations known to the pool.
    pub wakes: Vec<AgentPoolStoredWake>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Latest store cursor represented by this snapshot.
    pub cursor: Option<AgentPoolStoreCursor>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Durable message status stored for pool rehydration and dedupe.
pub struct AgentPoolStoredMessage {
    /// Original run message request.
    pub message: RunMessage,
    /// Receipt for the stored status transition.
    pub receipt: MessageReceipt,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Durable wake state stored for pool rehydration and cross-handle wake
/// triggering.
pub struct AgentPoolStoredWake {
    /// Original wake condition.
    pub condition: WakeCondition,
    /// Scoped, compiled filter used for envelope matching.
    pub compiled_filter: CompiledEventFilter,
    /// Latest durable registration status.
    pub registration: WakeRegistration,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// One append-only pool-store record. These records are a durable
/// coordination view linked to journal-backed events; they are not a
/// replacement for `AgentEventBus`.
pub struct AgentPoolStoreRecord {
    /// Stable pool id used for typed lineage, lookup, or dedupe.
    pub pool_id: AgentPoolId,
    /// Cursor assigned by the store.
    pub cursor: AgentPoolStoreCursor,
    /// Stored pool change.
    pub payload: AgentPoolStoreRecordPayload,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
/// Finite pool-store record variants.
#[expect(
    clippy::large_enum_variant,
    reason = "pool store payloads are durable serde records; preserve direct variant ergonomics until a separate storage-envelope redesign"
)]
pub enum AgentPoolStoreRecordPayload {
    /// Pool metadata was opened or initialized.
    PoolOpened {
        /// Configuration persisted for this pool.
        config: AgentPoolStoreConfig,
    },
    /// Pool lifecycle was marked created by a journal-backed operation.
    PoolCreated,
    /// A run joined the pool.
    MemberJoined {
        /// Joined member.
        member: AgentPoolMember,
    },
    /// A run left the pool.
    MemberLeft {
        /// Left member.
        member: AgentPoolMember,
    },
    /// A run-message status was persisted.
    RunMessage {
        /// Stored message transition.
        stored: AgentPoolStoredMessage,
    },
    /// A wake status was persisted.
    Wake {
        /// Stored wake transition.
        stored: AgentPoolStoredWake,
    },
}

#[derive(Clone, Debug)]
/// Iterator over durable pool-store records for one logical pool.
pub struct AgentPoolStoreStream {
    records: VecDeque<AgentPoolStoreRecord>,
}

impl AgentPoolStoreStream {
    /// Builds a store stream from records already loaded by a store.
    pub fn new(records: impl IntoIterator<Item = AgentPoolStoreRecord>) -> Self {
        Self {
            records: records.into_iter().collect(),
        }
    }
}

impl Iterator for AgentPoolStoreStream {
    type Item = AgentPoolStoreRecord;

    fn next(&mut self) -> Option<Self::Item> {
        self.records.pop_front()
    }
}

/// Port for durable/shared agent-pool coordination.
/// Implementations may use memory, SQLite, RPC, MCP, or another backing
/// service, but they must preserve the same pool-scoped records,
/// snapshots, idempotency, and watch semantics.
pub trait AgentPoolStore: Send + Sync {
    /// Create or open a logical pool and return the durable snapshot.
    fn open_pool(
        &self,
        pool_id: AgentPoolId,
        config: AgentPoolStoreConfig,
    ) -> Result<AgentPoolSnapshot, AgentError>;

    /// Rehydrate the current durable pool snapshot.
    fn snapshot(&self, pool_id: &AgentPoolId) -> Result<AgentPoolSnapshot, AgentError>;

    /// Mark the pool-created lifecycle as durable.
    fn record_pool_created(
        &self,
        pool_id: &AgentPoolId,
    ) -> Result<AgentPoolStoreCursor, AgentError>;

    /// Persist member join.
    fn join_member(
        &self,
        pool_id: &AgentPoolId,
        member: AgentPoolMember,
    ) -> Result<AgentPoolStoreCursor, AgentError>;

    /// Persist member leave and return the removed member.
    fn leave_member(
        &self,
        pool_id: &AgentPoolId,
        run_id: &RunId,
    ) -> Result<(AgentPoolMember, AgentPoolStoreCursor), AgentError>;

    /// Look up message dedupe state by idempotency key.
    fn message_receipt(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<MessageReceipt>, AgentError>;

    /// Persist one message status transition.
    fn record_message(
        &self,
        pool_id: &AgentPoolId,
        message: RunMessage,
        receipt: MessageReceipt,
    ) -> Result<AgentPoolStoreCursor, AgentError>;

    /// Look up wake dedupe state by idempotency key.
    fn wake_registration(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<WakeRegistration>, AgentError>;

    /// Look up one stored wake by condition id.
    fn wake(
        &self,
        pool_id: &AgentPoolId,
        condition_id: &WakeConditionId,
    ) -> Result<Option<AgentPoolStoredWake>, AgentError>;

    /// Persist one wake status transition.
    fn record_wake(
        &self,
        pool_id: &AgentPoolId,
        condition: WakeCondition,
        compiled_filter: CompiledEventFilter,
        registration: WakeRegistration,
    ) -> Result<AgentPoolStoreCursor, AgentError>;

    /// Read durable pool changes after the supplied cursor.
    fn watch(
        &self,
        pool_id: &AgentPoolId,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> Result<AgentPoolStoreStream, AgentError>;

    /// Allocate a unique event sequence for pool event IDs.
    fn next_event_sequence(&self, pool_id: &AgentPoolId) -> Result<u64, AgentError>;
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds agent pool member application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct AgentPoolMember {
    /// Run identifier used for lineage, filtering, replay, and dedupe.
    pub run_id: RunId,
    /// Agent identifier used for lineage, filtering, and ownership checks.
    pub agent_id: AgentId,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Policy references that govern admission, projection, execution, or
    /// delivery.
    pub policy_refs: Vec<PolicyRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Collection of topics values.
    /// Ordering and membership should be treated as part of the serialized contract when
    /// relevant.
    pub topics: Vec<TopicId>,
}

impl AgentPoolMember {
    /// Creates a new application::agent_pool value with explicit
    /// caller-provided inputs. This constructor is data-only and
    /// performs no I/O or external side effects.
    pub fn new(run_id: RunId, agent_id: AgentId) -> Self {
        Self {
            run_id,
            agent_id,
            policy_refs: Vec::new(),
            topics: Vec::new(),
        }
    }

    /// Returns an updated value with policy ref configured.
    /// This sets the policy reference on the coordination value and performs no I/O.
    pub fn policy_ref(mut self, policy_ref: PolicyRef) -> Self {
        self.policy_refs.push(policy_ref);
        self
    }

    /// Returns an updated value with topic configured.
    /// This sets the topic id on the address/filter value and performs no subscription by
    /// itself.
    pub fn topic(mut self, topic_id: TopicId) -> Self {
        self.topics.push(topic_id);
        self
    }

    fn allows_message_policies(&self, required: &[PolicyRef]) -> bool {
        required
            .iter()
            .all(|required| self.policy_refs.contains(required))
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds agent pool message policy application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct AgentPoolMessagePolicy {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Typed required policy refs references. Resolving them is separate from
    /// constructing this record.
    pub required_policy_refs: Vec<PolicyRef>,
    /// Whether pool broadcast delivery includes the sender run as a recipient.
    /// Use this for explicit loopback semantics; the default coordination path should avoid
    /// accidental self-delivery.
    pub include_sender_in_pool_broadcast: bool,
}

impl AgentPoolMessagePolicy {
    /// Builds the bounded defaults value with the documented defaults.
    /// This uses only local coordinator state and performs no hidden host work.
    pub fn bounded_defaults() -> Self {
        Self {
            required_policy_refs: Vec::new(),
            include_sender_in_pool_broadcast: false,
        }
    }

    fn allows(&self, message: &RunMessage) -> bool {
        self.required_policy_refs
            .iter()
            .all(|required| message.policy_refs.contains(required))
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds agent pool wake policy application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct AgentPoolWakePolicy {
    /// Whether envelope only is enabled.
    /// Policy, validation, or routing code uses this flag to choose the explicit behavior.
    pub envelope_only: bool,
}

impl AgentPoolWakePolicy {
    /// Returns an updated value with safe defaults configured.
    /// This is data-only and does not perform I/O, call host ports, append journals, publish
    /// events, or start processes.
    pub fn safe_defaults() -> Self {
        Self {
            envelope_only: true,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds run address application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct RunAddress {
    /// Target used by this record or request.
    pub target: RunAddressTarget,
    /// Typed destination reference that records where this item is being sent
    /// or projected.
    pub destination_ref: DestinationRef,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Typed related refs references. Resolving them is separate from
    /// constructing this record.
    pub related_refs: Vec<EntityRef>,
}

impl RunAddress {
    /// Builds the run value with the documented defaults.
    /// This uses only local coordinator state and performs no hidden host work.
    pub fn run(run_id: RunId) -> Self {
        Self {
            destination_ref: DestinationRef::with_kind(DestinationKind::Agent, run_id.as_str()),
            related_refs: vec![EntityRef::run(run_id.clone())],
            target: RunAddressTarget::Run { run_id },
        }
    }

    /// Returns agent for the current value.
    /// This is a read-only or data-construction helper unless the method body explicitly calls
    /// a port or store.
    pub fn agent(agent_id: AgentId) -> Self {
        Self {
            destination_ref: DestinationRef::with_kind(DestinationKind::Agent, agent_id.as_str()),
            related_refs: vec![EntityRef::agent(agent_id.clone())],
            target: RunAddressTarget::Agent { agent_id },
        }
    }

    /// Returns an updated value with topic configured.
    /// This sets the topic id on the address/filter value and performs no subscription by
    /// itself.
    pub fn topic(topic_id: TopicId) -> Self {
        Self {
            destination_ref: DestinationRef::with_kind(DestinationKind::Topic, topic_id.as_str()),
            related_refs: vec![EntityRef::topic(topic_id.clone())],
            target: RunAddressTarget::Topic { topic_id },
        }
    }

    /// Builds the pool value with the documented defaults.
    /// This uses only local coordinator state and performs no hidden host work.
    pub fn pool(pool_id: AgentPoolId) -> Self {
        Self {
            destination_ref: DestinationRef::with_kind(
                DestinationKind::AgentPool,
                pool_id.as_str(),
            ),
            related_refs: vec![EntityRef::agent_pool(pool_id.clone())],
            target: RunAddressTarget::Pool { pool_id },
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
/// Enumerates the finite run address target cases.
/// Serialized names are part of the SDK contract; update fixtures when variants change.
pub enum RunAddressTarget {
    /// Use this variant when the contract needs to represent run; selecting it has no side effect by itself.
    Run {
        /// Run identifier used for lineage, filtering, replay, and dedupe.
        run_id: RunId,
    },
    /// Use this variant when the contract needs to represent agent; selecting it has no side effect by itself.
    Agent {
        /// Agent identifier used for lineage, filtering, and ownership
        /// checks.
        agent_id: AgentId,
    },
    /// Use this variant when the contract needs to represent topic; selecting it has no side effect by itself.
    Topic {
        /// Stable topic id used for typed lineage, lookup, or dedupe.
        topic_id: TopicId,
    },
    /// Use this variant when the contract needs to represent pool; selecting it has no side effect by itself.
    Pool {
        /// Stable pool id used for typed lineage, lookup, or dedupe.
        pool_id: AgentPoolId,
    },
}

impl RunAddressTarget {
    /// Returns run id for this application::agent_pool value without
    /// performing external I/O.
    pub fn run_id(&self) -> Option<&RunId> {
        match self {
            Self::Run { run_id } => Some(run_id),
            _ => None,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds run message application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct RunMessage {
    /// Message identifier for transcript, projection, or provider-response
    /// lineage.
    pub message_id: MessageId,
    /// From used by this record or request.
    pub from: RunId,
    /// To used by this record or request.
    pub to: RunAddress,
    /// Content reference where payload bytes or structured tool output are
    /// stored.
    pub content_ref: ContentRef,
    /// Correlation used by this record or request.
    pub correlation: EventCorrelation,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional reply to value.
    /// When absent, callers should use the documented default or skip that optional behavior.
    pub reply_to: Option<MessageId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional response contract value.
    /// When absent, callers should use the documented default or skip that optional behavior.
    pub response_contract: Option<MessageResponseContract>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Time value in milliseconds for expires at millis.
    /// Use it for timeout, ordering, or diagnostic calculations.
    pub expires_at_millis: Option<u64>,
    /// Idempotency setting or key for deduping retries.
    /// Use it to prevent duplicate side effects during replay or repair.
    pub idempotency_key: IdempotencyKey,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Policy references that govern admission, projection, execution, or
    /// delivery.
    pub policy_refs: Vec<PolicyRef>,
}

impl RunMessage {
    /// Creates a new application::agent_pool value with explicit
    /// caller-provided inputs. This constructor is data-only and
    /// performs no I/O or external side effects.
    pub fn new(
        message_id: MessageId,
        from: RunId,
        to: RunAddress,
        content_ref: ContentRef,
        idempotency_key: IdempotencyKey,
    ) -> Self {
        Self {
            message_id,
            from,
            to,
            content_ref,
            correlation: EventCorrelation::default(),
            reply_to: None,
            response_contract: None,
            expires_at_millis: None,
            idempotency_key,
            policy_refs: Vec::new(),
        }
    }

    /// Returns an updated value with policy ref configured.
    /// This sets the policy reference on the coordination value and performs no I/O.
    pub fn policy_ref(mut self, policy_ref: PolicyRef) -> Self {
        self.policy_refs.push(policy_ref);
        self
    }

    fn target_related_refs(&self, delivered_to: &[RunId]) -> Vec<EntityRef> {
        let mut refs = self.to.related_refs.clone();
        refs.extend(delivered_to.iter().cloned().map(EntityRef::run));
        refs.sort_by(|left, right| {
            left.kind
                .cmp(&right.kind)
                .then_with(|| left.as_str().cmp(right.as_str()))
        });
        refs.dedup_by(|left, right| left.kind == right.kind && left.as_str() == right.as_str());
        refs
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds message response contract application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct MessageResponseContract {
    /// Expected responses used by this record or request.
    pub expected_responses: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Time value in milliseconds for timeout millis.
    /// Use it for timeout, ordering, or diagnostic calculations.
    pub timeout_millis: Option<u64>,
}

impl MessageResponseContract {
    /// Builds the one response value with the documented defaults.
    /// This uses only local coordinator state and performs no hidden host work.
    pub fn one_response(timeout_millis: u64) -> Self {
        Self {
            expected_responses: 1,
            timeout_millis: Some(timeout_millis),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds message receipt application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct MessageReceipt {
    /// Message identifier for transcript, projection, or provider-response
    /// lineage.
    pub message_id: MessageId,
    /// Finite status for this record or lifecycle stage.
    pub status: MessageStatus,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Collection of delivered to values.
    /// Ordering and membership should be treated as part of the serialized contract when
    /// relevant.
    pub delivered_to: Vec<RunId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Cursor identifying a replay, export, or subscription position.
    /// Use it to resume without widening the original scope.
    pub journal_cursor: Option<JournalCursor>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
/// Enumerates the finite message status cases.
/// Serialized names are part of the SDK contract; update fixtures when variants change.
pub enum MessageStatus {
    /// Use this variant when the contract needs to represent accepted; selecting it has no side effect by itself.
    Accepted,
    /// Use this variant when the contract needs to represent delivered; selecting it has no side effect by itself.
    Delivered,
    /// Use this variant when the contract needs to represent responded; selecting it has no side effect by itself.
    Responded,
    /// Use this variant when the contract needs to represent failed; selecting it has no side effect by itself.
    Failed,
    /// Use this variant when the contract needs to represent timed out; selecting it has no side effect by itself.
    TimedOut,
    /// Use this variant when the contract needs to represent expired; selecting it has no side effect by itself.
    Expired,
    /// Use this variant when the contract needs to represent cancelled; selecting it has no side effect by itself.
    Cancelled,
}

impl MessageStatus {
    fn event_kind(&self) -> EventKind {
        match self {
            Self::Accepted => EventKind::RunMessageAccepted,
            Self::Delivered => EventKind::RunMessageDelivered,
            Self::Responded => EventKind::RunMessageResponded,
            Self::Failed => EventKind::RunMessageFailed,
            Self::TimedOut => EventKind::RunMessageTimedOut,
            Self::Expired => EventKind::RunMessageExpired,
            Self::Cancelled => EventKind::RunMessageCancelled,
        }
    }

    fn redacted_summary(&self) -> &'static str {
        match self {
            Self::Accepted => "run message accepted",
            Self::Delivered => "run message delivered",
            Self::Responded => "run message responded",
            Self::Failed => "run message failed",
            Self::TimedOut => "run message timed out",
            Self::Expired => "run message expired",
            Self::Cancelled => "run message cancelled",
        }
    }

    fn is_terminal_delivery(&self) -> bool {
        matches!(
            self,
            Self::Delivered
                | Self::Responded
                | Self::Failed
                | Self::TimedOut
                | Self::Expired
                | Self::Cancelled
        )
    }

    fn effect_terminal_status(&self) -> EffectTerminalStatus {
        match self {
            Self::Delivered | Self::Responded => EffectTerminalStatus::Completed,
            Self::TimedOut => EffectTerminalStatus::TimedOut,
            Self::Cancelled => EffectTerminalStatus::Cancelled,
            Self::Accepted => EffectTerminalStatus::Unknown,
            Self::Failed | Self::Expired => EffectTerminalStatus::Failed,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds wake condition application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct WakeCondition {
    /// Stable condition id used for typed lineage, lookup, or dedupe.
    pub condition_id: WakeConditionId,
    /// Run identifier used for lineage, filtering, replay, and dedupe.
    pub run_id: RunId,
    /// Filter used by this record or request.
    pub filter: EventFilter,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Time value in milliseconds for timeout millis.
    /// Use it for timeout, ordering, or diagnostic calculations.
    pub timeout_millis: Option<u64>,
    /// Resume with used by this record or request.
    pub resume_with: ResumeInputPolicy,
    /// Idempotency setting or key for deduping retries.
    /// Use it to prevent duplicate side effects during replay or repair.
    pub idempotency_key: IdempotencyKey,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Policy references that govern admission, projection, execution, or
    /// delivery.
    pub policy_refs: Vec<PolicyRef>,
}

impl WakeCondition {
    /// Creates a new application::agent_pool value with explicit
    /// caller-provided inputs. This constructor is data-only and
    /// performs no I/O or external side effects.
    pub fn new(
        condition_id: WakeConditionId,
        run_id: RunId,
        filter: EventFilter,
        idempotency_key: IdempotencyKey,
    ) -> Self {
        Self {
            condition_id,
            run_id,
            filter,
            timeout_millis: None,
            resume_with: ResumeInputPolicy::MatchingEventRefs,
            idempotency_key,
            policy_refs: Vec::new(),
        }
    }

    /// Returns an updated value with timeout millis configured.
    /// This updates the wake timeout on the condition value and performs no scheduling by
    /// itself.
    pub fn timeout_millis(mut self, timeout_millis: u64) -> Self {
        self.timeout_millis = Some(timeout_millis);
        self
    }

    /// Returns an updated value with policy ref configured.
    /// This sets the policy reference on the coordination value and performs no I/O.
    pub fn policy_ref(mut self, policy_ref: PolicyRef) -> Self {
        self.policy_refs.push(policy_ref);
        self
    }

    /// Computes or returns compile envelope filter for the
    /// application::agent_pool contract without external I/O or side effects.
    pub fn compile_envelope_filter(&self) -> Result<CompiledEventFilter, AgentError> {
        let mut filter = self.filter.clone();
        filter.payload_access = PayloadAccessMode::EnvelopeOnly;
        filter.compile()
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
/// Enumerates the finite resume input policy cases.
/// Serialized names are part of the SDK contract; update fixtures when variants change.
pub enum ResumeInputPolicy {
    /// Use this variant when the contract needs to represent matching event refs; selecting it has no side effect by itself.
    MatchingEventRefs,
    /// Use this variant when the contract needs to represent redacted summary; selecting it has no side effect by itself.
    RedactedSummary,
    /// Use this variant when the contract needs to represent none; selecting it has no side effect by itself.
    None,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
/// Holds wake registration application-layer state or configuration.
/// Use it with the documented coordinator methods; run, journal, event, provider, or port effects are called out on those methods rather than on construction.
pub struct WakeRegistration {
    /// Stable condition id used for typed lineage, lookup, or dedupe.
    pub condition_id: WakeConditionId,
    /// Run identifier used for lineage, filtering, replay, and dedupe.
    pub run_id: RunId,
    /// Finite status for this record or lifecycle stage.
    pub status: WakeRegistrationStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Cursor identifying a replay, export, or subscription position.
    /// Use it to resume without widening the original scope.
    pub journal_cursor: Option<JournalCursor>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
/// Enumerates the finite wake registration status cases.
/// Serialized names are part of the SDK contract; update fixtures when variants change.
pub enum WakeRegistrationStatus {
    /// Use this variant when the contract needs to represent registered; selecting it has no side effect by itself.
    Registered,
    /// Use this variant when the contract needs to represent triggered; selecting it has no side effect by itself.
    Triggered,
    /// Use this variant when the contract needs to represent timed out; selecting it has no side effect by itself.
    TimedOut,
    /// Use this variant when the contract needs to represent cancelled; selecting it has no side effect by itself.
    Cancelled,
    /// Use this variant when the contract needs to represent failed; selecting it has no side effect by itself.
    Failed,
}

impl WakeRegistrationStatus {
    fn event_kind(&self) -> EventKind {
        match self {
            Self::Registered => EventKind::WakeConditionRegistered,
            Self::Triggered => EventKind::WakeConditionTriggered,
            Self::TimedOut => EventKind::WakeConditionTimedOut,
            Self::Cancelled => EventKind::WakeConditionCancelled,
            Self::Failed => EventKind::WakeConditionFailed,
        }
    }

    fn redacted_summary(&self) -> &'static str {
        match self {
            Self::Registered => "wake condition registered",
            Self::Triggered => "wake condition triggered",
            Self::TimedOut => "wake condition timed out",
            Self::Cancelled => "wake condition cancelled",
            Self::Failed => "wake condition failed",
        }
    }
}

#[derive(Clone, Debug)]
struct AgentPoolState {
    created: bool,
    members: BTreeMap<RunId, AgentPoolMember>,
    topics: BTreeMap<TopicId, BTreeSet<RunId>>,
    message_policy: AgentPoolMessagePolicy,
    wake_policy: AgentPoolWakePolicy,
    policy_refs: Vec<PolicyRef>,
    messages: BTreeMap<MessageId, AgentPoolStoredMessage>,
    message_dedupe: BTreeMap<IdempotencyKey, MessageReceipt>,
    wake_dedupe: BTreeMap<IdempotencyKey, WakeRegistration>,
    wakes: BTreeMap<WakeConditionId, AgentPoolStoredWake>,
    next_event_counter: u64,
}

impl AgentPoolState {
    fn new(config: AgentPoolStoreConfig) -> Self {
        Self {
            created: false,
            members: BTreeMap::new(),
            topics: BTreeMap::new(),
            message_policy: config.message_policy,
            wake_policy: config.wake_policy,
            policy_refs: config.policy_refs,
            messages: BTreeMap::new(),
            message_dedupe: BTreeMap::new(),
            wake_dedupe: BTreeMap::new(),
            wakes: BTreeMap::new(),
            next_event_counter: 0,
        }
    }

    fn config(&self) -> AgentPoolStoreConfig {
        AgentPoolStoreConfig {
            message_policy: self.message_policy.clone(),
            wake_policy: self.wake_policy.clone(),
            policy_refs: self.policy_refs.clone(),
        }
    }

    fn snapshot(
        &self,
        pool_id: AgentPoolId,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> AgentPoolSnapshot {
        AgentPoolSnapshot {
            pool_id,
            created: self.created,
            members: self.members.values().cloned().collect(),
            topics: self.topics.keys().cloned().collect(),
            message_policy: self.message_policy.clone(),
            wake_policy: self.wake_policy.clone(),
            policy_refs: self.policy_refs.clone(),
            messages: self.messages.values().cloned().collect(),
            wakes: self.wakes.values().cloned().collect(),
            cursor,
        }
    }

    fn index_member(&mut self, member: AgentPoolMember) {
        for topic in &member.topics {
            self.topics
                .entry(topic.clone())
                .or_default()
                .insert(member.run_id.clone());
        }
        self.members.insert(member.run_id.clone(), member);
    }

    fn remove_member(&mut self, run_id: &RunId) -> Result<AgentPoolMember, AgentError> {
        let member = self.members.remove(run_id).ok_or_else(|| {
            AgentError::new(
                AgentErrorKind::InvalidStateTransition,
                RetryClassification::NotRetryable,
                "run is not a member of this agent pool",
            )
        })?;
        for topic in &member.topics {
            let remove_topic = if let Some(runs) = self.topics.get_mut(topic) {
                runs.remove(run_id);
                runs.is_empty()
            } else {
                false
            };
            if remove_topic {
                self.topics.remove(topic);
            }
        }
        Ok(member)
    }
}

#[derive(Clone, Debug, Default)]
/// In-memory `AgentPoolStore` implementation.
/// Cloning this value shares the same backing map, making it useful for
/// tests that simulate two process-local `AgentPool` handles sharing one
/// coordination authority. Separate default values are isolated.
pub struct InMemoryAgentPoolStore {
    pools: Arc<Mutex<BTreeMap<AgentPoolId, AgentPoolState>>>,
    records: Arc<Mutex<BTreeMap<AgentPoolId, Vec<AgentPoolStoreRecord>>>>,
}

impl InMemoryAgentPoolStore {
    fn with_pool_state<T>(
        &self,
        pool_id: &AgentPoolId,
        f: impl FnOnce(&mut AgentPoolState) -> Result<T, AgentError>,
    ) -> Result<T, AgentError> {
        let mut pools = self
            .pools
            .lock()
            .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
        let state = pools.get_mut(pool_id).ok_or_else(|| {
            AgentError::new(
                AgentErrorKind::HostConfigurationNeeded,
                RetryClassification::HostConfigurationNeeded,
                "agent pool store has not opened this pool",
            )
        })?;
        f(state)
    }

    fn append_record(
        &self,
        pool_id: &AgentPoolId,
        payload: AgentPoolStoreRecordPayload,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        let mut records = self
            .records
            .lock()
            .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
        let entries = records.entry(pool_id.clone()).or_default();
        let cursor = AgentPoolStoreCursor::new(entries.len() as u64 + 1);
        entries.push(AgentPoolStoreRecord {
            pool_id: pool_id.clone(),
            cursor: cursor.clone(),
            payload,
        });
        Ok(cursor)
    }

    fn latest_cursor(
        &self,
        pool_id: &AgentPoolId,
    ) -> Result<Option<AgentPoolStoreCursor>, AgentError> {
        let records = self
            .records
            .lock()
            .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
        Ok(records
            .get(pool_id)
            .and_then(|records| records.last().map(|record| record.cursor.clone())))
    }
}

impl AgentPoolStore for InMemoryAgentPoolStore {
    fn open_pool(
        &self,
        pool_id: AgentPoolId,
        config: AgentPoolStoreConfig,
    ) -> Result<AgentPoolSnapshot, AgentError> {
        {
            let mut pools = self
                .pools
                .lock()
                .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
            if let Some(existing) = pools.get(&pool_id) {
                if existing.config() != config {
                    return Err(AgentError::new(
                        AgentErrorKind::InvalidStateTransition,
                        RetryClassification::RepairNeeded,
                        "agent pool store config conflicts with existing pool",
                    ));
                }
            } else {
                pools.insert(pool_id.clone(), AgentPoolState::new(config.clone()));
                drop(pools);
                self.append_record(&pool_id, AgentPoolStoreRecordPayload::PoolOpened { config })?;
            }
        }
        self.snapshot(&pool_id)
    }

    fn snapshot(&self, pool_id: &AgentPoolId) -> Result<AgentPoolSnapshot, AgentError> {
        let cursor = self.latest_cursor(pool_id)?;
        let pools = self
            .pools
            .lock()
            .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
        pools
            .get(pool_id)
            .map(|state| state.snapshot(pool_id.clone(), cursor))
            .ok_or_else(|| {
                AgentError::new(
                    AgentErrorKind::HostConfigurationNeeded,
                    RetryClassification::HostConfigurationNeeded,
                    "agent pool store has not opened this pool",
                )
            })
    }

    fn record_pool_created(
        &self,
        pool_id: &AgentPoolId,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.with_pool_state(pool_id, |state| {
            state.created = true;
            Ok(())
        })?;
        self.append_record(pool_id, AgentPoolStoreRecordPayload::PoolCreated)
    }

    fn join_member(
        &self,
        pool_id: &AgentPoolId,
        member: AgentPoolMember,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.with_pool_state(pool_id, |state| {
            state.index_member(member.clone());
            Ok(())
        })?;
        self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::MemberJoined { member },
        )
    }

    fn leave_member(
        &self,
        pool_id: &AgentPoolId,
        run_id: &RunId,
    ) -> Result<(AgentPoolMember, AgentPoolStoreCursor), AgentError> {
        let member = self.with_pool_state(pool_id, |state| state.remove_member(run_id))?;
        let cursor = self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::MemberLeft {
                member: member.clone(),
            },
        )?;
        Ok((member, cursor))
    }

    fn message_receipt(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<MessageReceipt>, AgentError> {
        self.with_pool_state(pool_id, |state| {
            Ok(state.message_dedupe.get(idempotency_key).cloned())
        })
    }

    fn record_message(
        &self,
        pool_id: &AgentPoolId,
        message: RunMessage,
        receipt: MessageReceipt,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        let stored = AgentPoolStoredMessage { message, receipt };
        self.with_pool_state(pool_id, |state| {
            state.message_dedupe.insert(
                stored.message.idempotency_key.clone(),
                stored.receipt.clone(),
            );
            state
                .messages
                .insert(stored.message.message_id.clone(), stored.clone());
            Ok(())
        })?;
        self.append_record(pool_id, AgentPoolStoreRecordPayload::RunMessage { stored })
    }

    fn wake_registration(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<WakeRegistration>, AgentError> {
        self.with_pool_state(pool_id, |state| {
            Ok(state.wake_dedupe.get(idempotency_key).cloned())
        })
    }

    fn wake(
        &self,
        pool_id: &AgentPoolId,
        condition_id: &WakeConditionId,
    ) -> Result<Option<AgentPoolStoredWake>, AgentError> {
        self.with_pool_state(pool_id, |state| Ok(state.wakes.get(condition_id).cloned()))
    }

    fn record_wake(
        &self,
        pool_id: &AgentPoolId,
        condition: WakeCondition,
        compiled_filter: CompiledEventFilter,
        registration: WakeRegistration,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        let stored = AgentPoolStoredWake {
            condition,
            compiled_filter,
            registration,
        };
        self.with_pool_state(pool_id, |state| {
            state.wake_dedupe.insert(
                stored.condition.idempotency_key.clone(),
                stored.registration.clone(),
            );
            state
                .wakes
                .insert(stored.condition.condition_id.clone(), stored.clone());
            Ok(())
        })?;
        self.append_record(pool_id, AgentPoolStoreRecordPayload::Wake { stored })
    }

    fn watch(
        &self,
        pool_id: &AgentPoolId,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> Result<AgentPoolStoreStream, AgentError> {
        let start_after = cursor.map(|cursor| cursor.sequence).unwrap_or(0);
        let records = self
            .records
            .lock()
            .map_err(|_| AgentError::contract_violation("agent pool store lock poisoned"))?;
        Ok(AgentPoolStoreStream::new(
            records
                .get(pool_id)
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .filter(|record| record.cursor.sequence > start_after),
        ))
    }

    fn next_event_sequence(&self, pool_id: &AgentPoolId) -> Result<u64, AgentError> {
        self.with_pool_state(pool_id, |state| {
            state.next_event_counter += 1;
            Ok(state.next_event_counter)
        })
    }
}

impl From<RunAddressTarget> for RunMessageAddressTargetRecord {
    fn from(value: RunAddressTarget) -> Self {
        match value {
            RunAddressTarget::Run { run_id } => Self::Run { run_id },
            RunAddressTarget::Agent { agent_id } => Self::Agent { agent_id },
            RunAddressTarget::Topic { topic_id } => Self::Topic { topic_id },
            RunAddressTarget::Pool { pool_id } => Self::Pool { pool_id },
        }
    }
}

impl From<MessageStatus> for RunMessageDeliveryStatus {
    fn from(value: MessageStatus) -> Self {
        match value {
            MessageStatus::Accepted => Self::Accepted,
            MessageStatus::Delivered => Self::Delivered,
            MessageStatus::Responded => Self::Responded,
            MessageStatus::Failed => Self::Failed,
            MessageStatus::TimedOut => Self::TimedOut,
            MessageStatus::Expired => Self::Expired,
            MessageStatus::Cancelled => Self::Cancelled,
        }
    }
}

impl From<ResumeInputPolicy> for WakeResumeInputPolicyRecord {
    fn from(value: ResumeInputPolicy) -> Self {
        match value {
            ResumeInputPolicy::MatchingEventRefs => Self::MatchingEventRefs,
            ResumeInputPolicy::RedactedSummary => Self::RedactedSummary,
            ResumeInputPolicy::None => Self::None,
        }
    }
}

impl From<WakeRegistrationStatus> for WakeTriggerStatus {
    fn from(value: WakeRegistrationStatus) -> Self {
        match value {
            WakeRegistrationStatus::Registered => Self::Registered,
            WakeRegistrationStatus::Triggered => Self::Triggered,
            WakeRegistrationStatus::TimedOut => Self::TimedOut,
            WakeRegistrationStatus::Cancelled => Self::Cancelled,
            WakeRegistrationStatus::Failed => Self::Failed,
        }
    }
}

trait AgentPoolEventKindName {
    fn wire_name(&self) -> &'static str;
}

impl AgentPoolEventKindName for EventKind {
    fn wire_name(&self) -> &'static str {
        match self {
            EventKind::AgentPoolCreated => "agent_pool_created",
            EventKind::AgentPoolRunJoined => "agent_pool_run_joined",
            EventKind::AgentPoolRunLeft => "agent_pool_run_left",
            EventKind::RunMessageAccepted => "run_message_accepted",
            EventKind::RunMessageDelivered => "run_message_delivered",
            EventKind::RunMessageResponded => "run_message_responded",
            EventKind::RunMessageFailed => "run_message_failed",
            EventKind::RunMessageTimedOut => "run_message_timed_out",
            EventKind::RunMessageExpired => "run_message_expired",
            EventKind::RunMessageCancelled => "run_message_cancelled",
            EventKind::WakeConditionRegistered => "wake_condition_registered",
            EventKind::WakeConditionTriggered => "wake_condition_triggered",
            EventKind::WakeConditionTimedOut => "wake_condition_timed_out",
            EventKind::WakeConditionCancelled => "wake_condition_cancelled",
            EventKind::WakeConditionFailed => "wake_condition_failed",
            _ => "agent_pool_event",
        }
    }
}

fn intersect_run_ids(filter: &EventFilterSet<RunId>, allowed: &[RunId]) -> EventFilterSet<RunId> {
    match filter {
        EventFilterSet::Any => EventFilterSet::Include(allowed.to_vec()),
        EventFilterSet::Include(requested) => EventFilterSet::Include(
            requested
                .iter()
                .filter(|run_id| allowed.contains(run_id))
                .cloned()
                .collect(),
        ),
    }
}

fn topics_from_members(members: &[AgentPoolMember]) -> BTreeMap<TopicId, BTreeSet<RunId>> {
    let mut topics = BTreeMap::new();
    for member in members {
        for topic in &member.topics {
            topics
                .entry(topic.clone())
                .or_insert_with(BTreeSet::new)
                .insert(member.run_id.clone());
        }
    }
    topics
}