infinity-agent-core 0.2.0

Core time-sliced agent runtime for Infinity: event processing, threads, and tool dispatch.
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
//! Driver and router behavioral tests for interruption, deferral, idling,
//! routing, replay, and auto-compaction.

use async_trait::async_trait;
use infinity_provider_protocol::StreamChunk;
use infinity_provider_protocol::message::UserContent;
use rap_protocol::ThreadId;
use tokio::sync::mpsc;

use super::events::AgentEvent;
use super::local::{ChannelSender, ThreadLifecycleEvent, ThreadLifecycleState};
use super::test_support::*;
use crate::message::{
    InputMessage, InputMessageContent, SyntheticKind, TaggedSyntheticKind, UserChoiceRequired,
};
use crate::tools::{Tool, ToolContext};

#[tokio::test(flavor = "current_thread")]
async fn pending_choices_are_thread_local_and_replayed() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            use super::{AgentSystemBuilder, EventCollector, NoDeferral};
            use crate::stores::{InMemoryConversationStore, InMemoryStateStore};
            use crate::traits::{ConversationStore, StateStore};

            let (model, _ctrl) = model_source(None);
            let conv = InMemoryConversationStore::new();
            conv.ensure_root_thread(ThreadId::from_ref("t1"))
                .await
                .expect("ensure root");
            conv.ensure_root_thread(ThreadId::from_ref("t2"))
                .await
                .expect("ensure root");
            let state = InMemoryStateStore::new();
            let sender = ChannelSender::new_pair().0;
            let mut system = AgentSystemBuilder::new(conv, state.clone(), model, sender).build();
            let choice_input = |thread_id: &str, choice_id: &str| {
                (
                    InputMessage {
                        content: InputMessageContent::UserChoice(UserChoiceRequired {
                            content_type: "user_choice_required".to_owned(),
                            id: choice_id.into(),
                            call_id: None,
                            prompt: "Pick one".to_owned(),
                            choices: vec!["A".to_owned(), "B".to_owned()],
                            default: 0,
                            response_url: "http://example.test/choice".to_owned(),
                        }),
                        group_id: thread_id.into(),
                        metadata: None,
                        synthetic: None,
                        display_as: None,
                        subscription: false,
                    },
                    format!("message-{choice_id}"),
                )
            };
            let collector = EventCollector::new();
            system
                .step(
                    vec![
                        choice_input("t1", "choice-1"),
                        choice_input("t2", "choice-2"),
                    ],
                    &collector,
                    &mut NoDeferral,
                )
                .await
                .expect("persist choices");

            assert_eq!(
                state
                    .get_pending_user_choices(ThreadId::from_ref("t1"))
                    .await
                    .expect("load first thread choices")[0]
                    .id
                    .as_str(),
                "choice-1"
            );
            assert_eq!(
                state
                    .get_pending_user_choices(ThreadId::from_ref("t2"))
                    .await
                    .expect("load second thread choices")[0]
                    .id
                    .as_str(),
                "choice-2"
            );

            let (sub_tx, mut sub_rx) = mpsc::unbounded_channel();
            let replay_conv = InMemoryConversationStore::new();
            replay_conv
                .ensure_root_thread(ThreadId::from_ref("t1"))
                .await
                .expect("ensure replay root");
            let running = AgentSystemBuilder::new_local(replay_conv, state, model_source(None).0)
                .start_with_observer(|_| TestObserver {
                    tx: mpsc::unbounded_channel().0,
                });
            running.subscribe(ThreadId::from_ref("t1"), sub_tx).await;
            let Evt::Replay(snapshot) = next_evt(&mut sub_rx).await else {
                panic!("expected replay");
            };
            assert_eq!(snapshot.pending_choices.len(), 1);
            assert_eq!(snapshot.pending_choices[0].id.as_str(), "choice-1");
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn driver_idles_after_text_response() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut rx, mut ctrl, _conv) = start_system(vec![], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "hello")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("hi there");
            ctrl.finish();
            let texts = collect_until_finished(&mut rx).await;
            assert_eq!(texts, vec!["hi there"]);
            wait_idle(&mut running).await;
            assert!(running.is_idle());
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn driver_stays_alive_waiting_for_tool_result() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "use tool")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            assert!(
                !matches!(
                    running.try_next_lifecycle_event(),
                    Ok(ThreadLifecycleEvent {
                        state: ThreadLifecycleState::Idle,
                        ..
                    })
                ),
                "should not idle while a tool call is pending"
            );
            assert!(!running.is_idle());

            // A client attaching while waiting gets a replay whose history
            // ends with the unresolved tool call and no completion in flight.
            let (sub_tx, mut sub_rx) = mpsc::unbounded_channel();
            running.subscribe(ThreadId::from_ref("t1"), sub_tx).await;
            match next_evt(&mut sub_rx).await {
                Evt::Replay(snapshot) => {
                    assert!(!snapshot.in_progress);
                    assert!(matches!(
                        snapshot.history.last(),
                        Some(crate::message::InfinityMessage::ToolCall { call, .. })
                            if call.function.name == "async_tool"
                    ));
                }
                other => panic!("expected replay, got {other:?}"),
            }

            // Deliver the result; the driver wakes and finishes.
            running
                .send(tool_result_input("t1", "tc-1", "tool done").0, "res-1")
                .await;
            let _req2 = ctrl.next_request().await;
            ctrl.send_text("ok");
            ctrl.finish();
            collect_until_finished(&mut rx).await;
            wait_idle(&mut running).await;
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn user_text_interrupts_active_completion() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "first")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("partial...");
            // Wait until the chunk is observed so the completion is in flight.
            loop {
                if let Evt::E(AgentEvent::TextChunk { .. }) = next_evt(&mut rx).await {
                    break;
                }
            }
            running
                .send_user_text(ThreadId::from_ref("t1"), "stop that")
                .await;
            let req2 = ctrl.next_request().await;
            let has_interrupt = req2.chat_history.into_iter().any(|m| {
                if let infinity_provider_protocol::message::Message::User { content } = &m
                    && let Some(UserContent::Text(t)) = content.first()
                {
                    return t.text.contains("<interrupt>");
                }
                false
            });
            assert!(has_interrupt, "interrupting input should carry the marker");
            ctrl.send_text("ok stopped");
            ctrl.finish();
            collect_until_finished(&mut rx).await;
        })
        .await;
}

/// A non-user-text input (e.g. a stale tool result) arriving while a
/// completion is streaming must not interrupt it.
#[tokio::test(flavor = "current_thread")]
async fn non_user_text_during_completion_does_not_interrupt() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![Box::new(AsyncTool)], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "do stuff")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            running
                .send(tool_result_input("t1", "tc-1", "tool output").0, "res-1")
                .await;
            let _req2 = ctrl.next_request().await;
            ctrl.send_text("processing...");
            loop {
                if let Evt::E(AgentEvent::TextChunk { .. }) = next_evt(&mut rx).await {
                    break;
                }
            }
            // A stale tool result arrives mid-stream — must not interrupt.
            running
                .send(
                    tool_result_input("t1", "tc-other", "stale event").0,
                    "res-stale",
                )
                .await;
            ctrl.send_text(" done");
            ctrl.finish();
            let texts = collect_until_finished(&mut rx).await;
            assert!(
                texts.join("").contains("done"),
                "should not have been interrupted"
            );
        })
        .await;
}

/// An associative subscription event arriving while a completion is streaming
/// is queued and processed in the next round rather than interrupting it.
#[tokio::test(flavor = "current_thread")]
async fn subscription_event_queued_during_completion_processed_after() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) =
                start_system(vec![Box::new(SubscribeTool)], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "subscribe")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-sub", "subscribe_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // The subscription result triggers the next round; leave the model
            // mid-stream while the event arrives.
            let _req2 = ctrl.next_request().await;
            ctrl.send_text("got subscription...");
            loop {
                if let Evt::E(AgentEvent::TextChunk { .. }) = next_evt(&mut rx).await {
                    break;
                }
            }
            running
                .send(
                    subscription_event_input("t1", "tc-sub", "event payload xyz").0,
                    "ev-1",
                )
                .await;
            ctrl.send_text(" all good");
            ctrl.finish();
            let texts = collect_until_finished(&mut rx).await;
            assert!(
                texts.join("").contains("all good"),
                "should not have been interrupted"
            );

            // The queued event appears in the next round.
            let req3 = ctrl.next_request().await;
            assert!(
                tool_result_texts(&req3)
                    .iter()
                    .any(|t| t.contains("event payload xyz")),
                "queued event should appear in next round"
            );
            ctrl.send_text("processed");
            ctrl.finish();
            collect_until_finished(&mut rx).await;
        })
        .await;
}
/// An unanswered `close_thread` call never receives a result, so it must not
/// keep the driver resident.
#[tokio::test(flavor = "current_thread")]
async fn driver_idles_after_close_thread_tool_call() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            /// Stub close_thread (the built-in one refuses to close a root
            /// thread); registered with built-ins disabled so it is the only
            /// tool by that name.
            struct CloseThreadStub;
            #[async_trait]
            impl Tool<ChannelSender> for CloseThreadStub {
                fn name(&self) -> &str {
                    "close_thread"
                }
                fn description(&self) -> &str {
                    "close"
                }
                fn parameters(&self) -> serde_json::Value {
                    serde_json::json!({"type":"object","properties":{}})
                }
                async fn execute(
                    &self,
                    _: serde_json::Value,
                    _: rap_protocol::ToolCallId,
                    _: Option<rap_protocol::ProviderCallId>,
                    _: &ToolContext<ChannelSender>,
                ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                    Ok(())
                }
            }
            let (mut running, mut rx, mut ctrl, _conv) =
                start_system_with(vec![Box::new(CloseThreadStub)], None, false);
            running
                .send_user_text(ThreadId::from_ref("t1"), "close")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-1",
                "close_thread",
                serde_json::json!({"thread_id": "t1"}),
            );
            ctrl.finish();
            collect_until_finished(&mut rx).await;
            wait_idle(&mut running).await;
            assert!(running.is_idle());
        })
        .await;
}

/// Thread reports arriving while waiting for a non-passive async tool result
/// are deferred until the tool result is processed.
#[tokio::test(flavor = "current_thread")]
async fn thread_report_deferred_during_async_tool_wait() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![Box::new(AsyncTool)], None);

            // 1. User sends input, model calls async_tool.
            running
                .send_user_text(ThreadId::from_ref("t1"), "do async")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-async", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // 2. While waiting for the tool result, a thread report arrives.
            running
                .send(
                    InputMessage {
                        content: InputMessageContent::User(UserContent::ToolResult(
                            infinity_provider_protocol::message::ToolResult {
                                id: String::new(),
                                call_id: None,
                                content: vec![
                                    infinity_provider_protocol::message::ToolResultContent::Text(
                                        infinity_provider_protocol::message::Text {
                                            text: "Report from child thread: progress update"
                                                .into(),
                                        },
                                    ),
                                ],
                            },
                        )),
                        group_id: "t1".into(),
                        metadata: None,
                        synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
                            tool_call_id: "tc-async".into(),
                            child_thread_id: "child-1".into(),
                        })),
                        display_as: None,
                        subscription: false,
                    },
                    "report-1",
                )
                .await;
            for _ in 0..4 {
                tokio::task::yield_now().await;
            }

            // 3. The thread report must not have triggered a completion.
            assert!(
                ctrl.try_next_request().is_none(),
                "thread report should not trigger completion while waiting for async tool"
            );

            // 4. The real result arrives; the deferred report is included.
            running
                .send(tool_result_input("t1", "tc-async", "tool done").0, "res-1")
                .await;
            let req2 = ctrl.next_request().await;
            ctrl.send_text("all processed");
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            let texts = tool_result_texts(&req2);
            assert!(texts.iter().any(|t| t.contains("tool done")));
            assert!(texts.iter().any(|t| t.contains("progress update")));
        })
        .await;
}

/// Shutting the system down while a completion is in flight interrupts the
/// completion (stripping trailing reasoning) and waits for every thread
/// driver to flush pending history items before the router task returns.
/// A tool result the model has already produced output for is validated and
/// must be persisted together with the partial output.
#[tokio::test(flavor = "current_thread")]
async fn shutdown_persists_model_validated_tool_result() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, conv) = start_system(vec![Box::new(AsyncTool)], None);

            // 1. User input → model issues an async tool call.
            running
                .send_user_text(ThreadId::from_ref("t1"), "do something")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // 2. The tool result arrives → the driver starts a new
            //    completion, and the model streams some output for it
            //    (validating the result for persistence).
            running
                .send(
                    tool_result_input("t1", "tc-1", "tool execution result").0,
                    "res-1",
                )
                .await;
            let _req2 = ctrl.next_request().await;
            ctrl.send_text("partial reply");
            loop {
                if let Evt::E(AgentEvent::TextChunk { .. }) = next_evt(&mut rx).await {
                    break;
                }
            }

            // 3. Shut down while the model is mid-response.
            let active_threads = running.active_threads();
            running.shutdown().await;
            assert!(
                active_threads
                    .lock()
                    .expect("bug: active_threads mutex poisoned")
                    .is_empty(),
                "no thread drivers should remain after shutdown"
            );

            // 4. The tool result and the partial output must have been
            //    synced to the store.
            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("tool execution result"),
                "validated in-flight tool result should be persisted on shutdown; history: {stored}"
            );
            assert!(
                stored.contains("partial reply"),
                "partial model output should be persisted on shutdown; history: {stored}"
            );
        })
        .await;
}

/// Shutting down while the model has produced *no* output for a freshly
/// arrived tool result must not persist that result: the model never
/// validated it, and it could be the oversized input that permanently
/// wedges the thread. The durable state keeps the tool call unanswered
/// (a later user input settles it with a synthetic "interrupted" result).
#[tokio::test(flavor = "current_thread")]
async fn shutdown_does_not_persist_unvalidated_tool_result() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, conv) = start_system(vec![Box::new(AsyncTool)], None);

            running
                .send_user_text(ThreadId::from_ref("t1"), "do something")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // The tool result arrives; the completion is in flight but the
            // model has not produced any output yet.
            running
                .send(
                    tool_result_input("t1", "tc-1", "tool execution result").0,
                    "res-1",
                )
                .await;
            let _req2 = ctrl.next_request().await;

            running.shutdown().await;

            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("tc-1"),
                "the tool call itself is model output and must be persisted; history: {stored}"
            );
            assert!(
                !stored.contains("tool execution result"),
                "an unvalidated tool result must not be persisted on shutdown; history: {stored}"
            );
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn subscription_event_deferred_during_async_tool_wait() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![Box::new(AsyncTool)], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "do async")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-async", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // A subscription event arrives while the tool result is pending.
            running
                .send(
                    subscription_event_input("t1", "tc-async", "sub event data").0,
                    "sub-1",
                )
                .await;
            for _ in 0..4 {
                tokio::task::yield_now().await;
            }
            assert!(
                ctrl.try_next_request().is_none(),
                "deferred event must not trigger a completion"
            );

            // The real result arrives; the deferred event is included after it.
            running
                .send(tool_result_input("t1", "tc-async", "tool done").0, "res-1")
                .await;
            let req2 = ctrl.next_request().await;
            ctrl.send_text("all processed");
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            let texts = tool_result_texts(&req2);
            assert!(texts.iter().any(|t| t.contains("tool done")));
            assert!(texts.iter().any(|t| t.contains("sub event data")));
            assert!(
                !texts.iter().any(|t| t.contains("interrupted")),
                "in-flight tool call must not have been interrupted: {texts:?}"
            );
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn stale_result_does_not_flush_deferred_events_during_async_tool_wait() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![Box::new(AsyncTool)], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "do async")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-async", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // A deferrable event and a stale tool result arrive together.
            running
                .send(
                    subscription_event_input("t1", "tc-async", "sub event data").0,
                    "sub-1",
                )
                .await;
            running
                .send(
                    tool_result_input("t1", "tc-stale", "stale result").0,
                    "res-stale",
                )
                .await;
            for _ in 0..6 {
                tokio::task::yield_now().await;
            }
            assert!(
                ctrl.try_next_request().is_none(),
                "stale result must not flush the deferred event"
            );

            running
                .send(tool_result_input("t1", "tc-async", "tool done").0, "res-1")
                .await;
            let req2 = ctrl.next_request().await;
            ctrl.send_text("all processed");
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            let texts = tool_result_texts(&req2);
            assert!(texts.iter().any(|t| t.contains("tool done")));
            assert!(texts.iter().any(|t| t.contains("sub event data")));
            assert!(
                !texts.iter().any(|t| t.contains("interrupted")),
                "in-flight tool call must not have been interrupted: {texts:?}"
            );
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn subscribe_mid_thinking_replays_current_thinking() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "think hard")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_chunk(StreamChunk::ReasoningDelta {
                id: None,
                text: "deep ".into(),
            });
            ctrl.send_chunk(StreamChunk::ReasoningDelta {
                id: None,
                text: "thought".into(),
            });
            // Wait until both chunks have been observed.
            let mut seen = String::new();
            while seen != "deep thought" {
                if let Evt::E(AgentEvent::ThinkingChunk { text }) = next_evt(&mut rx).await {
                    seen.push_str(&text);
                }
            }

            let (sub_tx, mut sub_rx) = mpsc::unbounded_channel();
            running.subscribe(ThreadId::from_ref("t1"), sub_tx).await;
            match next_evt(&mut sub_rx).await {
                Evt::Replay(snapshot) => {
                    assert!(snapshot.in_progress, "completion is in flight");
                    assert_eq!(snapshot.current_thinking.as_deref(), Some("deep thought"));
                }
                other => panic!("expected replay, got {other:?}"),
            }

            // Past the thinking chain, a new subscriber sees no stale thinking.
            ctrl.send_text("the answer");
            loop {
                if let Evt::E(AgentEvent::TextChunk { .. }) = next_evt(&mut rx).await {
                    break;
                }
            }
            let (sub_tx2, mut sub_rx2) = mpsc::unbounded_channel();
            running.subscribe(ThreadId::from_ref("t1"), sub_tx2).await;
            match next_evt(&mut sub_rx2).await {
                Evt::Replay(snapshot) => {
                    assert!(snapshot.in_progress);
                    assert!(snapshot.current_thinking.is_none());
                    // The partial text is visible via the in-flight turn.
                    assert!(matches!(
                        snapshot.history.last(),
                        Some(crate::message::InfinityMessage::Assistant { .. })
                    ));
                }
                other => panic!("expected replay, got {other:?}"),
            }

            ctrl.finish();
            collect_until_finished(&mut rx).await;
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn routes_to_separate_threads() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut rx, mut ctrl, _conv) = start_system(vec![], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "one")
                .await;
            let _r1 = ctrl.next_request().await;
            ctrl.send_text("first");
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            running
                .send_user_text(ThreadId::from_ref("t2"), "two")
                .await;
            let _r2 = ctrl.next_request().await;
            ctrl.send_text("second");
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            wait_idle(&mut running).await;
        })
        .await;
}

#[tokio::test(flavor = "current_thread")]
async fn respawns_driver_after_idle() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut rx, mut ctrl, _conv) = start_system(vec![], None);
            running
                .send_user_text(ThreadId::from_ref("t1"), "hello")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("hi");
            ctrl.finish();
            collect_until_finished(&mut rx).await;
            wait_idle(&mut running).await;
            assert!(running.is_idle());

            // A new message respawns the driver; the history is intact.
            running
                .send_user_text(ThreadId::from_ref("t1"), "again")
                .await;
            let req2 = ctrl.next_request().await;
            assert!(req2.chat_history.into_iter().any(|m| {
                if let infinity_provider_protocol::message::Message::User { content } = &m
                    && let Some(UserContent::Text(t)) = content.first()
                {
                    return t.text.contains("hello");
                }
                false
            }));
            ctrl.send_text("welcome back");
            ctrl.finish();
            collect_until_finished(&mut rx).await;
        })
        .await;
}
/// Regression test: a tool result arriving while a compaction child is
/// summarizing must not leave the history with an orphaned tool result whose
/// matching tool call was compacted away. The safe spawn point excludes the
/// trailing unanswered call from the compaction range.
#[tokio::test(flavor = "current_thread")]
async fn compaction_during_tool_call_corrupts_history() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut _rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], Some(small_context_entry()));

            // 1. User sends input, model responds with an async tool call and
            //    usage above the compaction threshold.
            running
                .send_user_text(ThreadId::from_ref("t1"), "do something")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish_with_usage(high_usage());

            // 2. Compaction triggers. Send the tool result BEFORE the
            //    compaction child finishes (simulating a fast tool execution).
            running
                .send(
                    tool_result_input("t1", "tc-1", "tool execution result").0,
                    "res-1",
                )
                .await;

            // Two model requests arrive (compaction child + parent processing
            // the tool result) in scheduling-dependent order.
            let req2 = ctrl.next_request().await;
            if is_compaction_req(&req2) {
                handle_compaction_child(&mut ctrl, &req2, "Summary of conversation so far");
                let _req3 = ctrl.next_request().await;
                ctrl.send_text("processed tool result");
                ctrl.finish();
            } else {
                ctrl.send_text("processed tool result");
                ctrl.finish();
                let compaction_req = ctrl.next_request().await;
                handle_compaction_child(&mut ctrl, &compaction_req, "Summary of conversation so far");
            }

            // 3. After CompactionComplete is applied, trigger a model call so
            //    we can inspect the history.
            running
                .send_user_text(ThreadId::from_ref("t1"), "what happened?")
                .await;
            let req_final =
                tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                    .await
                    .expect("timed out waiting for final model request");

            let history: Vec<_> = req_final.chat_history.into_iter().collect();
            let has_orphaned_tool_result = history.iter().enumerate().any(|(i, m)| {
                if let infinity_provider_protocol::message::Message::User { content } = m
                    && let Some(UserContent::ToolResult(r)) = content.first()
                    && let Some(infinity_provider_protocol::message::ToolResultContent::Text(t)) = r.content.first()
                    && t.text.contains("tool execution result")
                {
                    !history[..i].iter().any(|prev| {
                        if let infinity_provider_protocol::message::Message::Assistant { content, .. } = prev {
                            content.iter().any(|c| {
                                matches!(c, infinity_provider_protocol::message::AssistantContent::ToolCall(tc) if tc.id == "tc-1")
                            })
                        } else {
                            false
                        }
                    })
                } else {
                    false
                }
            });
            assert!(
                !has_orphaned_tool_result,
                "History is corrupted: tool result has no matching tool_call after compaction. History: {history:#?}"
            );

            ctrl.send_text("all good");
            ctrl.finish();
        })
        .await;
}

/// Regression test for issue #64: after compaction is applied, the tracked
/// context usage must be reset so auto-compaction does not immediately
/// re-trigger on the stale pre-compaction token count.
#[tokio::test(flavor = "current_thread")]
async fn compaction_does_not_retrigger_after_applied() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut _rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], Some(small_context_entry()));

            // 1. User input → async tool call + high usage → compaction triggers.
            running
                .send_user_text(ThreadId::from_ref("t1"), "do something")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish_with_usage(high_usage());

            // 2. The compaction child asks for a summary; close it. This sends
            //    CompactionComplete to the parent driver, which is still alive
            //    waiting on the tc-1 tool result.
            let compaction_req = ctrl.next_request().await;
            assert!(is_compaction_req(&compaction_req));
            handle_compaction_child(&mut ctrl, &compaction_req, "Summary of conversation so far");

            // 3. The tool result arrives. The parent applies the compaction
            //    and then processes the tool result. With the bug, the stale
            //    86-token count immediately re-triggers compaction, spawning a
            //    second compaction child whose model request would show up
            //    here.
            running
                .send(
                    tool_result_input("t1", "tc-1", "tool execution result").0,
                    "res-1",
                )
                .await;
            let req = ctrl.next_request().await;
            assert!(
                !is_compaction_req(&req),
                "compaction must not re-trigger after being applied"
            );
            // Finish without usage so the tracked context usage stays at its
            // post-compaction value.
            ctrl.send_text("processed tool result");
            ctrl.finish();

            // 4. With the fix, all drivers wind down. With the bug, a second
            //    compaction child sits waiting on the mock model forever and
            //    the system never idles.
            wait_idle(&mut running).await;
            for _ in 0..100 {
                tokio::task::yield_now().await;
            }
            assert!(
                ctrl.try_next_request().is_none(),
                "no further model requests should be made after compaction is applied"
            );
        })
        .await;
}

/// Regression test: a second compaction on the same (still-loaded) thread
/// after a prior compaction must compute the safe spawn point against
/// absolute store orders, not in-memory indices. The compaction child's
/// inherited history must include everything before the pending tool call and
/// exclude the call itself.
#[tokio::test(flavor = "current_thread")]
async fn second_compaction_during_tool_call_after_prior_compaction() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut _rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], Some(small_context_entry()));

            // ── FIRST ROUND: text response + compaction (no tool call) ──
            running
                .send_user_text(ThreadId::from_ref("t1"), "first message")
                .await;
            let _req1 = ctrl.next_request().await;
            ctrl.send_text("first response");
            ctrl.finish_with_usage(high_usage());

            let compaction_req1 = ctrl.next_request().await;
            assert!(is_compaction_req(&compaction_req1));
            handle_compaction_child(&mut ctrl, &compaction_req1, "Summary of first round");

            // Build more history after the first compaction.
            running
                .send_user_text(ThreadId::from_ref("t1"), "second message")
                .await;
            let _req2 = ctrl.next_request().await;
            ctrl.send_text("second response");
            ctrl.finish();

            running
                .send_user_text(ThreadId::from_ref("t1"), "third message")
                .await;
            let _req3 = ctrl.next_request().await;
            ctrl.send_text("third response");
            ctrl.finish();

            // ── SECOND ROUND: tool call + compaction after prior compaction ──
            running
                .send_user_text(ThreadId::from_ref("t1"), "fourth message")
                .await;
            let _req4 = ctrl.next_request().await;
            ctrl.send_tool_call("tc-2", "async_tool", serde_json::json!({}));
            ctrl.finish_with_usage(high_usage());

            // Send tool result before the compaction child finishes.
            running
                .send(
                    tool_result_input("t1", "tc-2", "second tool result").0,
                    "res-2",
                )
                .await;

            let req_c = ctrl.next_request().await;
            let compaction_child_req = if is_compaction_req(&req_c) {
                let r = req_c;
                handle_compaction_child(&mut ctrl, &r, "Summary of second round");
                let _req_d = ctrl.next_request().await;
                ctrl.send_text("processed second tool");
                ctrl.finish();
                r
            } else {
                ctrl.send_text("processed second tool");
                ctrl.finish();
                let req_d = ctrl.next_request().await;
                handle_compaction_child(&mut ctrl, &req_d, "Summary of second round");
                req_d
            };

            // The compaction child inherits everything before the pending
            // tool call ("fourth message" included, tc-2 excluded).
            insta::assert_json_snapshot!(
                "second_compaction_child_history",
                compaction_child_req.chat_history,
                {
                    "[].content[].id" => "[id]",
                    "[].content[].content[].text" => insta::dynamic_redaction(|value, _| {
                        let s = value.as_str().unwrap_or("");
                        if s.contains("compaction thread") {
                            insta::internals::Content::String("[compaction_instructions]".into())
                        } else {
                            value
                        }
                    })
                }
            );
        })
        .await;
}

/// Regression test for issue #31: compaction spawned inside a child thread
/// must account for ancestor messages when computing the safe spawn point;
/// otherwise the grandchild panics loading history.
#[tokio::test(flavor = "current_thread")]
async fn compaction_inside_child_thread_does_not_panic() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut _rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], Some(small_context_entry()));

            // ── Build root history ──
            running
                .send_user_text(ThreadId::from_ref("root"), "root message one")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("root response one");
            ctrl.finish();

            running
                .send_user_text(ThreadId::from_ref("root"), "root message two")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("root response two");
            ctrl.finish();

            // ── Spawn a child thread from root ──
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "do child work",
                    "child_of": ["root"]
                }),
            );
            ctrl.finish();

            // Parent loops back after the sync spawn — extract the child id.
            let parent_followup = ctrl.next_request().await;
            let child_thread_id = tool_result_texts(&parent_followup)
                .iter()
                .find_map(|t| {
                    let after =
                        t.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find child thread ID in spawn result");
            ctrl.send_text("ok, child spawned");
            ctrl.finish();

            // ── Child thread gets its first model call ──
            let _child_req = ctrl.next_request().await;
            ctrl.send_text("child first response");
            ctrl.finish();

            // ── Another round in the child: tool call + high usage triggers
            //    compaction inside the child thread. ──
            running
                .send_user_text(ThreadId::from_ref(&child_thread_id), "child follow-up")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-child", "async_tool", serde_json::json!({}));
            ctrl.finish_with_usage(high_usage());

            // Send tool result before compaction completes.
            running
                .send(
                    tool_result_input(&child_thread_id, "tc-child", "async tool result").0,
                    "res-child",
                )
                .await;

            // Two model requests arrive (compaction grandchild + child
            // processing the tool result) in scheduling-dependent order.
            let req_a = ctrl.next_request().await;
            let compaction_req = if is_compaction_req(&req_a) {
                handle_compaction_child(&mut ctrl, &req_a, "Summary of child work");
                let _req_b = ctrl.next_request().await;
                ctrl.send_text("processed tool result");
                ctrl.finish();
                req_a
            } else {
                ctrl.send_text("processed tool result");
                ctrl.finish();
                let req_b = ctrl.next_request().await;
                handle_compaction_child(&mut ctrl, &req_b, "Summary of child work");
                req_b
            };

            insta::assert_json_snapshot!(
                "issue31_compaction_child_history",
                compaction_req.chat_history,
                {
                    "[].content[].id" => "[id]",
                    "[].content[].content[].text" => insta::dynamic_redaction(|value, _| {
                        let s = value.as_str().unwrap_or("");
                        if s.contains("compaction thread") {
                            insta::internals::Content::String("[compaction_instructions]".into())
                        } else if s.contains("INSIDE the thread") {
                            insta::internals::Content::String("[spawn_instructions]".into())
                        } else {
                            value
                        }
                    })
                }
            );

            // ── After compaction applies, inspect the child's history ──
            running
                .send_user_text(
                    ThreadId::from_ref(&child_thread_id),
                    "message after compaction",
                )
                .await;
            let post_compaction_req =
                tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                    .await
                    .expect("child should respond after compaction");

            insta::assert_json_snapshot!(
                "issue31_post_compaction_history",
                post_compaction_req.chat_history,
                {
                    "[].content[].id" => "[id]",
                }
            );

            ctrl.send_text("done");
            ctrl.finish();
        })
        .await;
}

// ═══════════════════════════════════════════════════════════════════════
// Oversized-input / persistence-safety driver tests
// ═══════════════════════════════════════════════════════════════════════

/// The messages persisted for a thread, debug-formatted for asserts.
fn persisted(conv: &crate::stores::InMemoryConversationStore, thread_id: &str) -> String {
    format!(
        "{:?}",
        conv.thread_messages(ThreadId::from_ref(thread_id))
            .unwrap_or_default()
    )
}

/// Interrupting a request that produced no model output yet must not
/// persist the interrupted input — but the input stays in memory and is
/// re-sent (together with the interrupting message) on the next round.
/// Everything persists once the model produces output for it.
#[tokio::test(flavor = "current_thread")]
async fn interrupt_before_output_persists_nothing_until_model_output() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut rx, mut ctrl, conv) = start_system(vec![], None);

            // Message A: request goes out, model never answers.
            running
                .send_user_text(ThreadId::from_ref("t1"), "first message")
                .await;
            let _req1 = ctrl.next_request().await;

            // Message B interrupts before any output.
            running
                .send_user_text(ThreadId::from_ref("t1"), "second message")
                .await;
            let req2 = ctrl.next_request().await;

            // Nothing persisted yet: the model never validated A (it could
            // be the poison input blowing up the context window).
            let stored = persisted(&conv, "t1");
            assert!(
                !stored.contains("first message"),
                "interrupted input must not be persisted before model output; store: {stored}"
            );

            // But A is still in memory: the retry request carries A and B.
            let history = format!("{:?}", req2.chat_history);
            assert!(
                history.contains("first message") && history.contains("second message"),
                "the retry must include both inputs; history: {history}"
            );

            ctrl.send_text("model reply");
            ctrl.finish();
            collect_until_finished(&mut rx).await; // interrupted round 1
            collect_until_finished(&mut rx).await; // round 2
            wait_idle(&mut running).await;

            // Model output validated everything: now it all persists.
            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("first message")
                    && stored.contains("second message")
                    && stored.contains("model reply"),
                "validated inputs and output must be persisted; store: {stored}"
            );
        })
        .await;
}

/// End-to-end oversized tool result recovery: the result is replaced with a
/// placeholder and retried; if the placeholder still overflows, the step
/// errors out *without* persisting the poison result, keeping the call
/// answered in memory as "interrupted by user" — so a later user input just
/// works and the thread never hangs.
#[tokio::test(flavor = "current_thread")]
async fn oversized_tool_result_never_wedges_the_thread() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            use infinity_provider_protocol::{CompletionError, ErrorClass};

            let (mut running, mut rx, mut ctrl, conv) =
                start_system(vec![Box::new(AsyncTool)], None);

            // Round 1: the model calls an async tool.
            running
                .send_user_text(ThreadId::from_ref("t1"), "use the tool")
                .await;
            let _req1 = ctrl.next_request().await;
            ctrl.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl.finish();
            collect_until_finished(&mut rx).await;

            // The tool result is enormous: the model reports an overflow.
            running
                .send(
                    tool_result_input("t1", "tc-1", "HUGE TOOL RESULT").0,
                    "res-1",
                )
                .await;
            let _req2 = ctrl.next_request().await;
            ctrl.send_error(CompletionError::provider(
                ErrorClass::ContextOverflow,
                "input is too long for the model",
            ));
            ctrl.drop_stream();

            // Core retries with the placeholder result...
            let req3 = tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                .await
                .expect("core should retry with a placeholder tool result");
            let history = format!("{:?}", req3.chat_history);
            assert!(
                !history.contains("HUGE TOOL RESULT"),
                "retry must not resend the oversized result; history: {history}"
            );
            assert!(
                history.contains(crate::event_processor::TOOL_RESULT_TOO_LARGE_PLACEHOLDER),
                "retry must answer the call with the placeholder; history: {history}"
            );

            // ...which still overflows: the step gives up.
            ctrl.send_error(CompletionError::provider(
                ErrorClass::ContextOverflow,
                "input is too long for the model",
            ));
            ctrl.drop_stream();
            collect_until_finished(&mut rx).await;

            // The poison result must not have been persisted.
            let stored = persisted(&conv, "t1");
            assert!(
                !stored.contains("HUGE TOOL RESULT"),
                "the oversized result must not be persisted; store: {stored}"
            );

            // A later user input settles the stranded call and the thread
            // keeps working.
            running
                .send_user_text(ThreadId::from_ref("t1"), "are you alive?")
                .await;
            let req4 = tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                .await
                .expect("a later user input must reach the model (no permanent hang)");
            let history = format!("{:?}", req4.chat_history);
            assert!(
                history.contains(crate::event_processor::TOOL_CALL_INTERRUPTED_TEXT),
                "the call must stay answered (settled as interrupted); history: {history}"
            );
            assert!(
                !history.contains(crate::event_processor::TOOL_RESULT_TOO_LARGE_PLACEHOLDER),
                "a 'too large' note would mislead the model; history: {history}"
            );
            assert!(
                !history.contains("HUGE TOOL RESULT"),
                "the poison result must be gone from the model-facing history"
            );
            ctrl.send_text("alive and well");
            ctrl.finish();
            let texts = collect_until_finished(&mut rx).await;
            assert_eq!(texts, vec!["alive and well"]);
            wait_idle(&mut running).await;
        })
        .await;
}

/// Reboot recovery: a session dies while a tool result was still
/// unvalidated, so the durable store ends on the unanswered tool *call*.
/// When a fresh session boots from that store and user input arrives, the
/// stranded call must be settled with a synthetic "interrupted" result and
/// the thread must keep working.
#[tokio::test(flavor = "current_thread")]
async fn rebooted_session_settles_persisted_unanswered_tool_call() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            use super::AgentSystemBuilder;
            use crate::stores::{InMemoryConversationStore, InMemoryStateStore};

            let conv = InMemoryConversationStore::new();
            let state = InMemoryStateStore::new();

            // ── Session 1: the model calls a tool; its (oversized) result
            // arrives but the session shuts down before the model produces
            // any output for it. ──
            let (model1, mut ctrl1) = model_source(None);
            let (tx1, mut rx1) = mpsc::unbounded_channel();
            let running1 = AgentSystemBuilder::new_local(conv.clone(), state.clone(), model1)
                .tools(vec![Box::new(AsyncTool) as Box<dyn Tool<ChannelSender>>])
                .start_with_observer(move |_thread_id| TestObserver { tx: tx1.clone() });
            running1
                .send_user_text(ThreadId::from_ref("t1"), "do something")
                .await;
            let _req1 = ctrl1.next_request().await;
            ctrl1.send_tool_call("tc-1", "async_tool", serde_json::json!({}));
            ctrl1.finish();
            collect_until_finished(&mut rx1).await;

            running1
                .send(
                    tool_result_input("t1", "tc-1", "HUGE TOOL RESULT").0,
                    "res-1",
                )
                .await;
            let _req2 = ctrl1.next_request().await;
            running1.shutdown().await;

            // Durable state ends on the unanswered tool call; the
            // unvalidated result was not persisted.
            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("tc-1") && !stored.contains("HUGE TOOL RESULT"),
                "store must end on the unanswered call; store: {stored}"
            );

            // ── Session 2: boots from the same stores. ──
            let (model2, mut ctrl2) = model_source(None);
            let (tx2, mut rx2) = mpsc::unbounded_channel();
            let mut running2 = AgentSystemBuilder::new_local(conv.clone(), state.clone(), model2)
                .tools(vec![Box::new(AsyncTool) as Box<dyn Tool<ChannelSender>>])
                .start_with_observer(move |_thread_id| TestObserver { tx: tx2.clone() });
            running2
                .send_user_text(ThreadId::from_ref("t1"), "hello again")
                .await;

            // The stranded call is settled before the new input reaches the
            // model.
            let req = ctrl2.next_request().await;
            let history = format!("{:?}", req.chat_history);
            assert!(
                history.contains("Tool call interrupted by user"),
                "reboot + user input must settle the stranded call; history: {history}"
            );
            assert!(history.contains("hello again"), "history: {history}");

            ctrl2.send_text("back online");
            ctrl2.finish();
            let texts = collect_until_finished(&mut rx2).await;
            assert_eq!(texts, vec!["back online"]);
            wait_idle(&mut running2).await;

            // Everything from the recovered round is validated + persisted.
            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("Tool call interrupted by user")
                    && stored.contains("hello again")
                    && stored.contains("back online"),
                "recovered round must persist; store: {stored}"
            );
        })
        .await;
}

/// Variant of the interrupt test where the retry round overflows the
/// context. User text has no safe placeholder substitute, so the only
/// possible reaction is to drop the pending inputs — and when inputs are
/// dropped the step must *stop* (no blind retry: the user clearly wants to
/// say something, and silently re-running without their words would be
/// worse). The thread stays usable for the next input.
#[tokio::test(flavor = "current_thread")]
async fn overflow_after_interrupt_drops_user_inputs_and_stops() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            use infinity_provider_protocol::{CompletionError, ErrorClass};

            let (mut running, mut rx, mut ctrl, conv) = start_system(vec![], None);

            // Message A: request goes out, model never answers.
            running
                .send_user_text(ThreadId::from_ref("t1"), "first message")
                .await;
            let _req1 = ctrl.next_request().await;

            // Message B interrupts; the retry carries A and B...
            running
                .send_user_text(ThreadId::from_ref("t1"), "second message")
                .await;
            let req2 = ctrl.next_request().await;
            let history = format!("{:?}", req2.chat_history);
            assert!(history.contains("first message") && history.contains("second message"));

            // ...and overflows the context.
            ctrl.send_error(CompletionError::provider(
                ErrorClass::ContextOverflow,
                "input is too long for the model",
            ));
            ctrl.drop_stream();

            // The step surfaces the drop and stops — dropping inputs must
            // never be followed by a silent retry. (The first
            // CompletionFinished belongs to the interrupted round; the
            // overflow happens in the second.)
            let mut saw_drop_info = false;
            let mut finished_rounds = 0;
            while finished_rounds < 2 {
                match next_evt(&mut rx).await {
                    Evt::E(AgentEvent::Info { text }) if text.contains("too large") => {
                        saw_drop_info = true;
                    }
                    Evt::E(AgentEvent::CompletionFinished { .. }) => finished_rounds += 1,
                    _ => {}
                }
            }
            assert!(
                saw_drop_info,
                "the dropped input must be surfaced to the user"
            );
            wait_idle(&mut running).await;
            assert!(
                ctrl.try_next_request().is_none(),
                "dropping user input must stop the round, not retry it"
            );

            // Nothing was persisted.
            let stored = persisted(&conv, "t1");
            assert!(
                !stored.contains("first message") && !stored.contains("second message"),
                "dropped inputs must not be persisted; store: {stored}"
            );

            // The thread is not wedged: a fresh (smaller) message works, and
            // the dropped inputs are gone from the model-facing history too.
            running
                .send_user_text(ThreadId::from_ref("t1"), "third message")
                .await;
            let req3 = ctrl.next_request().await;
            let history = format!("{:?}", req3.chat_history);
            assert!(
                history.contains("third message")
                    && !history.contains("first message")
                    && !history.contains("second message"),
                "dropped inputs must not be resent; history: {history}"
            );
            ctrl.send_text("hello!");
            ctrl.finish();
            let texts = collect_until_finished(&mut rx).await;
            assert_eq!(texts, vec!["hello!"]);
            wait_idle(&mut running).await;

            let stored = persisted(&conv, "t1");
            assert!(
                stored.contains("third message") && stored.contains("hello!"),
                "the recovered round must persist; store: {stored}"
            );
        })
        .await;
}

/// A `fresh_context: true` spawn creates a child that inherits no parent
/// history: its first model request contains only the synthetic spawn call
/// and the self-contained instructions, none of the parent's messages.
#[tokio::test(flavor = "current_thread")]
async fn fresh_context_spawn_has_no_parent_history() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut _rx, mut ctrl, _conv) = start_system(vec![], None);

            // Build root history the child must NOT see.
            running
                .send_user_text(ThreadId::from_ref("root"), "root secret message")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("root response");
            ctrl.finish();

            // Spawn a fresh-context child.
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a fresh child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn-fresh",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "summarize the file docs/overview.md",
                    "child_of": ["root"],
                    "fresh_context": true
                }),
            );
            ctrl.finish();

            // Parent loops back after the sync spawn.
            let parent_followup = ctrl.next_request().await;
            assert!(
                tool_result_texts(&parent_followup)
                    .iter()
                    .any(|t| t.contains("Child thread is successfully spawned")),
                "spawn result present in parent follow-up"
            );
            ctrl.send_text("ok, spawned");
            ctrl.finish();

            // The child's first model request: no parent content, only the
            // synthetic spawn call and the fresh instructions.
            let child_req = ctrl.next_request().await;
            let history_json =
                serde_json::to_string(&child_req.chat_history).expect("serialize history");
            assert!(
                !history_json.contains("root secret message"),
                "fresh child must not inherit parent history: {history_json}"
            );
            assert!(
                history_json.contains("summarize the file docs/overview.md"),
                "fresh child sees its instructions: {history_json}"
            );
            assert!(
                history_json.contains("FRESH context"),
                "fresh child gets the fresh-context preamble: {history_json}"
            );
            ctrl.send_text("child done");
            ctrl.finish();
        })
        .await;
}

/// An inheriting grandchild sees its fresh parent's context, but nothing
/// from before the fresh-context boundary: t1 → fresh t2 → inheriting t3.
#[tokio::test(flavor = "current_thread")]
async fn nested_spawn_inherits_only_fresh_parent_context() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut _rx, mut ctrl, _conv) = start_system(vec![], None);

            running
                .send_user_text(ThreadId::from_ref("t1"), "t1 private user message")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_text("t1 private assistant response");
            ctrl.finish();
            wait_idle(&mut running).await;

            running
                .send_user_text(ThreadId::from_ref("t1"), "spawn a fresh child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn-t2",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "t2 independent task",
                    "child_of": ["t1"],
                    "fresh_context": true
                }),
            );
            ctrl.finish();

            let root_followup = ctrl.next_request().await;
            let t2 = tool_result_texts(&root_followup)
                .iter()
                .find_map(|text| {
                    let after =
                        text.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find t2 ID in spawn result");
            ctrl.send_text("t1 spawned t2");
            ctrl.finish();

            let _child_req = ctrl.next_request().await;
            ctrl.send_text("t2 findings to share with descendants");
            ctrl.finish();
            wait_idle(&mut running).await;

            running
                .send_user_text(
                    ThreadId::from_ref(&t2),
                    "t2 follow-up: delegate the next step",
                )
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn-t3",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "t3 continue using t2 findings",
                    "child_of": ["t1", t2],
                    "fresh_context": false
                }),
            );
            ctrl.finish();

            let _child_followup = ctrl.next_request().await;
            ctrl.send_text("t2 spawned t3");
            ctrl.finish();

            let grandchild_req = ctrl.next_request().await;
            let history =
                serde_json::to_string(&grandchild_req.chat_history).expect("serialize t3 history");
            assert!(
                !history.contains("t1 private user message")
                    && !history.contains("t1 private assistant response"),
                "t3 must not inherit t1 context across the fresh boundary: {history}"
            );
            assert!(
                history.contains("t2 independent task")
                    && history.contains("t2 findings to share with descendants")
                    && history.contains("t2 follow-up: delegate the next step"),
                "t3 must inherit t2 instructions and conversation: {history}"
            );
            assert!(
                tool_result_texts(&grandchild_req)
                    .iter()
                    .any(|text| text.contains("t3 continue using t2 findings")),
                "t3 must receive its own spawn instructions: {history}"
            );
            ctrl.send_text("t3 done");
            ctrl.finish();
            wait_idle(&mut running).await;
        })
        .await;
}

/// Reproduction: a child thread parked on `sleep_until_event_or_input`
/// receives a parent message, but the provider fails the completion with a
/// fatal error (e.g. expired auth). Once the provider recovers, a later
/// parent message must still reach the child.
#[tokio::test(flavor = "current_thread")]
async fn parent_message_after_fatal_error_still_reaches_sleeping_child() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut _rx, mut ctrl, _conv) = start_system(vec![], None);

            // ── Spawn a child thread from the root ──
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "wait for my messages",
                    "child_of": ["root"]
                }),
            );
            ctrl.finish();

            // Parent loops back after the sync spawn — extract the child id.
            let parent_followup = ctrl.next_request().await;
            let child_thread_id = tool_result_texts(&parent_followup)
                .iter()
                .find_map(|t| {
                    let after =
                        t.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find child thread ID in spawn result");
            ctrl.send_text("ok, child spawned");
            ctrl.finish();

            // ── Child's first round: it goes to sleep ──
            let child_req = ctrl.next_request().await;
            assert!(
                format!("{:?}", child_req.chat_history).contains("INSIDE the thread"),
                "expected the child's seed round"
            );
            ctrl.send_tool_call(
                "tc-sleep",
                "sleep_until_event_or_input",
                serde_json::json!({}),
            );
            ctrl.finish();

            // ── Parent sends a message to the sleeping child ──
            running
                .send_user_text(ThreadId::from_ref("root"), "message the child")
                .await;
            let _parent_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-msg1",
                "send_message_to_child",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "message": "hello child"
                }),
            );
            ctrl.finish();

            // Two rounds follow in scheduling-dependent order: the parent's
            // follow-up (send_message_to_child tool result) and the child's
            // wake-up with the parent message. The child's round fails with a
            // FATAL provider error (auth).
            for _ in 0..2 {
                let req = ctrl.next_request().await;
                let history = format!("{:?}", req.chat_history);
                if history.contains("Message from parent thread: hello child") {
                    ctrl.send_error(infinity_provider_protocol::CompletionError::provider(
                        infinity_provider_protocol::ErrorClass::Fatal,
                        "auth expired",
                    ));
                    ctrl.drop_stream();
                } else {
                    ctrl.send_text("message sent");
                    ctrl.finish();
                }
            }
            // The child driver idles out after the failed round; the message
            // consumed by the fatal round is lost (it was never validated by
            // model output, so it was never persisted).
            wait_idle(&mut running).await;

            // ── Provider "recovers"; parent sends another message ──
            running
                .send_user_text(ThreadId::from_ref("root"), "message the child again")
                .await;
            let _parent_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-msg2",
                "send_message_to_child",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "message": "hello again"
                }),
            );
            ctrl.finish();

            // Again two rounds: the parent's follow-up and (hopefully) the
            // child's wake-up containing "hello again". Match on the
            // child-side text — the parent's own history also contains
            // "hello again" inside the send_message_to_child call args.
            let mut child_got_message = false;
            for _ in 0..2 {
                let req =
                    tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                        .await
                        .expect("timed out waiting for a model round after provider recovery");
                let history = format!("{:?}", req.chat_history);
                if history.contains("Message from parent thread: hello again") {
                    child_got_message = true;
                    ctrl.send_text("got it");
                    ctrl.finish();
                } else {
                    ctrl.send_text("message sent");
                    ctrl.finish();
                }
            }
            assert!(
                child_got_message,
                "the child must receive parent messages after the provider recovers"
            );
        })
        .await;
}

/// Known issue: the child is waiting on an *active* tool call when the parent
/// message arrives (so the message is deferred). The tool result then lands
/// together with the drained parent message, but the completion fails with a
/// fatal provider error: both inputs were consumed from the queue yet never
/// persisted. The store still ends with the dangling tool call, so after the
/// driver exits every later parent message defers forever against a tool
/// result that can never arrive again.
///
/// Unlike the sleeping-child case above (where the pending call is passive
/// and the waiting state is re-derivable from the store), recovering here
/// needs the driver to stay resident while it holds consumed-but-unpersisted
/// inputs, or a deferral policy that eventually gives up on a dangling call.
///
/// Expected-failure marker: `should_panic` pins the broken behavior. When
/// the wedge is fixed, this test starts failing — remove the attribute (the
/// body already asserts the desired behavior).
#[tokio::test(flavor = "current_thread")]
#[should_panic(expected = "the child must receive parent messages after the provider recovers")]
async fn parent_message_after_fatal_error_during_active_tool_call() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (mut running, mut _rx, mut ctrl, _conv) =
                start_system(vec![Box::new(AsyncTool)], None);

            // ── Spawn a child thread from the root ──
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "work then wait",
                    "child_of": ["root"]
                }),
            );
            ctrl.finish();

            let parent_followup = ctrl.next_request().await;
            let child_thread_id = tool_result_texts(&parent_followup)
                .iter()
                .find_map(|t| {
                    let after =
                        t.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find child thread ID in spawn result");
            ctrl.send_text("ok, child spawned");
            ctrl.finish();

            // ── Child's first round: it starts an async (active) tool call ──
            let _child_req = ctrl.next_request().await;
            ctrl.send_tool_call("tc-work", "async_tool", serde_json::json!({}));
            ctrl.finish();

            // ── Parent messages the child while tc-work is pending: deferred ──
            running
                .send_user_text(ThreadId::from_ref("root"), "message the child")
                .await;
            let _parent_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-msg1",
                "send_message_to_child",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "message": "hello child"
                }),
            );
            ctrl.finish();
            // Parent's follow-up round after the tool result.
            let parent_req = ctrl.next_request().await;
            assert!(
                format!("{:?}", parent_req.chat_history).contains("Message sent to child thread"),
                "expected the parent's follow-up round"
            );
            ctrl.send_text("message sent");
            ctrl.finish();

            // ── The async tool result arrives; the batch settles the pending
            //    call and drains the deferred parent message. This completion
            //    fails with a FATAL provider error (auth). ──
            running
                .send(
                    tool_result_input(&child_thread_id, "tc-work", "work finished").0,
                    "res-work",
                )
                .await;
            let child_req = ctrl.next_request().await;
            let history = format!("{:?}", child_req.chat_history);
            assert!(
                history.contains("work finished")
                    && history.contains("Message from parent thread: hello child"),
                "the child round must include the tool result and the drained parent message; got {history}"
            );
            ctrl.send_error(infinity_provider_protocol::CompletionError::provider(
                infinity_provider_protocol::ErrorClass::Fatal,
                "auth expired",
            ));
            ctrl.drop_stream();
            // The child driver idles out after the failed round, dropping the
            // consumed tool result and parent message; the store keeps the
            // dangling tc-work call.
            wait_idle(&mut running).await;

            // ── Provider "recovers"; parent sends another message ──
            running
                .send_user_text(ThreadId::from_ref("root"), "message the child again")
                .await;
            let _parent_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-msg2",
                "send_message_to_child",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "message": "hello again"
                }),
            );
            ctrl.finish();

            // The parent's follow-up and (hopefully) the child's wake-up.
            // Match on the child-side text — the parent's own history also
            // contains "hello again" inside the send_message_to_child args.
            let mut child_got_message = false;
            for _ in 0..2 {
                let Ok(req) = tokio::time::timeout(
                    std::time::Duration::from_secs(5),
                    ctrl.next_request(),
                )
                .await
                else {
                    break;
                };
                let history = format!("{:?}", req.chat_history);
                if history.contains("Message from parent thread: hello again") {
                    // The tool result and the deferred first message were
                    // consumed during the fatal round; they must have been
                    // retained and retried rather than silently lost (a lost
                    // tool result would leave tc-work dangling forever).
                    assert!(
                        history.contains("work finished")
                            && history.contains("Message from parent thread: hello child"),
                        "inputs consumed during the fatal error must be retried, not lost; got {history}"
                    );
                    child_got_message = true;
                    ctrl.send_text("got it");
                    ctrl.finish();
                } else {
                    ctrl.send_text("message sent");
                    ctrl.finish();
                }
            }
            assert!(
                child_got_message,
                "the child must receive parent messages after the provider recovers"
            );
        })
        .await;
}

/// Regression: a sleeping parent must be woken by its child's close report
/// even after a compaction folded the child's `spawn_thread` tool call into
/// the summary. Compaction never deletes store rows, so the original call
/// must be found by unwinding past the compaction boundary instead of
/// dropping the report.
#[tokio::test(flavor = "current_thread")]
async fn child_close_report_wakes_sleeping_parent_after_compaction() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![], None);

            // ── Parent spawns a child, then goes to sleep ──
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "work, then close when asked",
                    "child_of": ["root"]
                }),
            );
            ctrl.finish();

            let parent_followup = ctrl.next_request().await;
            let child_thread_id = tool_result_texts(&parent_followup)
                .iter()
                .find_map(|t| {
                    let after =
                        t.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find child thread ID in spawn result");
            ctrl.send_tool_call(
                "tc-sleep",
                "sleep_until_event_or_input",
                serde_json::json!({}),
            );
            ctrl.finish();

            // ── Child's seed round: it acknowledges and idles ──
            let child_req = ctrl.next_request().await;
            assert!(
                format!("{:?}", child_req.chat_history).contains("INSIDE the thread"),
                "expected the child's seed round"
            );
            ctrl.send_text("child ready");
            ctrl.finish();

            // ── Manually trigger compaction on the sleeping parent ──
            running
                .send(
                    InputMessage {
                        content: InputMessageContent::User(UserContent::text("")),
                        group_id: "root".into(),
                        metadata: None,
                        synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::Compaction)),
                        display_as: None,
                        subscription: false,
                    },
                    "compact-1",
                )
                .await;
            let creq = ctrl.next_request().await;
            assert!(is_compaction_req(&creq), "expected the compaction child");
            handle_compaction_child(&mut ctrl, &creq, "parent spawned a child and went to sleep");

            // Wait until the parent has actually applied the compaction, so
            // the child's report arrives strictly after the spawn call was
            // folded into the summary.
            loop {
                if let Evt::E(AgentEvent::CompactionApplied) = next_evt(&mut rx).await {
                    break;
                }
            }

            // ── The child closes with a report ──
            running
                .send_user_text(ThreadId::from_ref(&child_thread_id), "close now")
                .await;
            let _child_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-close",
                "close_thread",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "report_to_parent": "child finished its work",
                }),
            );
            ctrl.finish();

            // ── The sleeping parent must be woken by the close report ──
            let parent_req =
                tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                    .await
                    .expect("the sleeping parent must be woken by the child's close report");
            let history = format!("{:?}", parent_req.chat_history);
            assert!(
                history.contains("child finished its work"),
                "the parent's wake-up round must include the child's report; got {history}"
            );
            assert!(
                history.contains("[Compacted conversation summary]"),
                "the parent's history must be the compacted view; got {history}"
            );
            ctrl.send_text("resumed");
            ctrl.finish();
        })
        .await;
}

/// Mirror case: a parent message must reach a child whose *own* compaction
/// folded the inherited `spawn_thread` call into its summary. The spawn call
/// lives in the parent's store (the child only ever saw it through its
/// inherited ancestor slice), so resolving it requires scanning ancestor
/// slices, not just this thread's own rows.
#[tokio::test(flavor = "current_thread")]
async fn parent_message_reaches_child_after_child_compaction() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let (running, mut rx, mut ctrl, _conv) = start_system(vec![], None);

            // ── Parent spawns a child ──
            running
                .send_user_text(ThreadId::from_ref("root"), "spawn a child")
                .await;
            let _req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-spawn",
                "spawn_thread",
                serde_json::json!({
                    "instructions": "wait for my messages",
                    "child_of": ["root"]
                }),
            );
            ctrl.finish();

            let parent_followup = ctrl.next_request().await;
            let child_thread_id = tool_result_texts(&parent_followup)
                .iter()
                .find_map(|t| {
                    let after =
                        t.strip_prefix("Child thread is successfully spawned and has ID: ")?;
                    Some(after.split('.').next()?.to_owned())
                })
                .expect("should find child thread ID in spawn result");
            ctrl.send_text("ok, child spawned");
            ctrl.finish();

            // ── Child's seed round ──
            let _child_req = ctrl.next_request().await;
            ctrl.send_text("child ready");
            ctrl.finish();

            // ── Compact the CHILD: its inherited ancestor prefix (including
            //    the spawn call) is folded into the summary ──
            running
                .send(
                    InputMessage {
                        content: InputMessageContent::User(UserContent::text("")),
                        group_id: child_thread_id.as_str().into(),
                        metadata: None,
                        synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::Compaction)),
                        display_as: None,
                        subscription: false,
                    },
                    "compact-child-1",
                )
                .await;
            let creq = ctrl.next_request().await;
            assert!(is_compaction_req(&creq), "expected the compaction child");
            handle_compaction_child(&mut ctrl, &creq, "child was spawned and is waiting");
            loop {
                if let Evt::E(AgentEvent::CompactionApplied) = next_evt(&mut rx).await {
                    break;
                }
            }

            // ── Parent messages the compacted child ──
            running
                .send_user_text(ThreadId::from_ref("root"), "message the child")
                .await;
            let _parent_req = ctrl.next_request().await;
            ctrl.send_tool_call(
                "tc-msg",
                "send_message_to_child",
                serde_json::json!({
                    "thread_id": child_thread_id,
                    "message": "hello child"
                }),
            );
            ctrl.finish();

            // Two rounds in scheduling-dependent order: the parent's
            // follow-up and the child's wake-up. Match on the child-side
            // text — the parent's history also contains "hello child" in the
            // send_message_to_child call args.
            let mut child_got_message = false;
            for _ in 0..2 {
                let req =
                    tokio::time::timeout(std::time::Duration::from_secs(5), ctrl.next_request())
                        .await
                        .expect("the compacted child must receive the parent's message");
                let history = format!("{:?}", req.chat_history);
                if history.contains("Message from parent thread: hello child") {
                    assert!(
                        history.contains("[Compacted conversation summary]"),
                        "the child's history must be the compacted view; got {history}"
                    );
                    child_got_message = true;
                    ctrl.send_text("got it");
                    ctrl.finish();
                } else {
                    ctrl.send_text("message sent");
                    ctrl.finish();
                }
            }
            assert!(
                child_got_message,
                "the parent's message must reach the child after the child compacts"
            );
        })
        .await;
}