bamboo-engine 2026.8.1

Execution engine and orchestration for the Bamboo agent framework
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
//! Tool execution helpers for the agent loop runner.

use std::sync::Arc;

use futures::future::join_all;
use tokio::sync::mpsc;

use crate::runtime::config::AgentLoopConfig;
use crate::runtime::task_context::TaskLoopContext;
use bamboo_agent_core::tools::{ToolCall, ToolExecutor, ToolSchema};
use bamboo_agent_core::{AgentError, AgentEvent, Session};
use bamboo_domain::{AgentHookPoint, AgentRuntimeState};
use bamboo_llm::LLMProvider;
use bamboo_metrics::{MetricsCollector, RoundStatus as MetricsRoundStatus};

fn build_context_pressure(session: &Session) -> Option<output_compressor::ContextPressure> {
    let usage = session.token_usage.as_ref()?;
    let budget = session.effective_token_budget()?;
    let trigger = budget.compression_trigger_context_tokens();
    if trigger == 0 {
        return None;
    }
    let remaining = trigger.saturating_sub(usage.total_tokens);
    let percent = ((usage.total_tokens as f64 / trigger as f64) * 100.0).min(100.0) as u8;
    Some(output_compressor::ContextPressure {
        usage_percent: percent,
        remaining_tokens: remaining,
    })
}

/// Build the task-aware compression hint from the ACTIVE task item's completion
/// criteria (+ description), so a truncated tool output preferentially preserves
/// lines relevant to what the task is verifying (Phase 4). `None` when there is
/// no active task or it yields no significant terms.
fn build_task_compression_hint(
    task_context: &Option<TaskLoopContext>,
) -> Option<output_compressor::TaskCompressionHint> {
    let ctx = task_context.as_ref()?;
    let item = ctx
        .items
        .iter()
        .find(|item| Some(&item.id) == ctx.active_item_id.as_ref())?;
    let mut phrases = item.completion_criteria.clone();
    phrases.push(item.description.clone());
    let hint = output_compressor::TaskCompressionHint::from_phrases(phrases);
    (!hint.is_empty()).then_some(hint)
}

mod clarification;
mod events;
mod execution_paths;
mod loop_state;
mod output_compressor;
mod per_call;
mod policy;
mod task;
pub(in crate::runtime::runner) use task::persist_shared_task_list;
pub(crate) mod tool_error_collector;

use loop_state::RoundExecutionState;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolSchedulingMode {
    ParallelSafe,
    Sequential,
}

fn scheduling_mode_for_tool_call(
    tool_call: &ToolCall,
    tools: &Arc<dyn ToolExecutor>,
) -> ToolSchedulingMode {
    let normalized = bamboo_tools::normalize_tool_ref(&tool_call.function.name)
        .unwrap_or_else(|| tool_call.function.name.trim().to_string());

    let canonical = bamboo_tools::resolve_alias(&normalized)
        .map(|s: &str| s.to_string())
        .unwrap_or(normalized);

    let mut effective_call = tool_call.clone();
    effective_call.function.name = canonical;

    if bamboo_tools::parallel::ToolCallRuntime::supports_parallel(tools, &effective_call) {
        ToolSchedulingMode::ParallelSafe
    } else {
        ToolSchedulingMode::Sequential
    }
}

pub(crate) struct RoundToolExecutionResult {
    pub awaiting_clarification: bool,
    pub waiting_for_children: bool,
    pub round_status: MetricsRoundStatus,
    pub round_error: Option<String>,
}

struct SingleToolExecutionControl {
    should_break: bool,
    stop_round: bool,
}

#[allow(clippy::too_many_arguments)]
async fn execute_and_apply_single_tool_call(
    tool_call: &ToolCall,
    event_tx: &mpsc::Sender<AgentEvent>,
    metrics_collector: Option<&MetricsCollector>,
    session_id: &str,
    round_id: &str,
    round: usize,
    session: &mut Session,
    tools: &Arc<dyn ToolExecutor>,
    config: &AgentLoopConfig,
    // Pre-built per-round snapshot of the executor's full tool-schema list —
    // avoids re-cloning every schema on each tool call.
    available_tool_schemas: &[ToolSchema],
    runtime_state: &mut AgentRuntimeState,
    task_context: &mut Option<TaskLoopContext>,
    state: &mut RoundExecutionState,
    policy_guard: &mut policy::ToolPolicyGuard,
    reserved_calls: usize,
) -> Result<SingleToolExecutionControl, AgentError> {
    // Every sequential/single dispatch is its own externally visible safe
    // boundary. Re-read only the authoritative permission control-plane before
    // deriving flags; storage failures abort before ToolStart or executor entry.
    super::state_bridge::refresh_tool_boundary_permission_posture(
        session,
        runtime_state,
        config.storage.as_ref(),
    )
    .await?;
    let session_flags =
        bamboo_agent_core::tools::ToolExecutionSessionFlags::from_session_and_configured_mode(
            session,
            config.permission_mode.unwrap_or_default(),
        );
    // Plan mode gate: block mutating tools (except pause/clarification tools)
    if session_flags.plan_read_only {
        let tool_name = tool_call.function.name.trim();
        if !bamboo_tools::orchestrator::plan_mode_allows_tool(tool_name) {
            tracing::warn!(
                "[{}][round:{}] Plan mode blocked mutating tool: tool_call_id={}, tool_name={}",
                session_id,
                round,
                tool_call.id,
                tool_name
            );
            let outcome = per_call::ToolExecutionOutcome {
                needs_human: None,
                post_tool_hook_eligible: false,
                result: Err(format!("Plan mode: {} operation blocked", tool_name)),
                tool_duration: std::time::Duration::ZERO,
            };
            policy_guard.observe_outcome(tool_call, &outcome.result);
            let task_hint = build_task_compression_hint(task_context);
            let outcome = output_compressor::maybe_compress(
                &tool_call.function.name,
                &tool_call.function.arguments,
                session_id,
                outcome,
                session
                    .effective_token_budget()
                    .map(|b| b.max_tool_output_tokens)
                    .unwrap_or(0),
                build_context_pressure(session),
                task_hint.as_ref(),
            )
            .await;
            let should_break = per_call::apply_tool_execution_outcome(
                per_call::ToolExecutionApplyContext {
                    tool_call,
                    event_tx,
                    metrics_collector,
                    session_id,
                    round_id,
                    round,
                    session,
                    tools,
                    session_flags,
                    config,
                    runtime_state,
                    task_context,
                    state,
                },
                outcome,
            )
            .await?;
            return Ok(SingleToolExecutionControl {
                should_break,
                stop_round: false,
            });
        }
    }

    let mut stop_round = false;
    let outcome = match policy_guard.check_before_execution(tool_call, reserved_calls) {
        Ok(()) => {
            if let Err(policy_error) = policy::validate_tool_call_context(tool_call, session) {
                tracing::warn!(
                    "[{}][round:{}] Tool call blocked by context policy before ToolStart: tool_call_id={}, tool_name={}, error={}",
                    session_id,
                    round,
                    tool_call.id,
                    tool_call.function.name,
                    policy_error
                );
                per_call::ToolExecutionOutcome {
                    needs_human: None,
                    post_tool_hook_eligible: false,
                    result: Err(policy_error),
                    tool_duration: std::time::Duration::ZERO,
                }
            } else {
                let before_tool_hooks = config
                    .hook_runner
                    .has_hooks_for(AgentHookPoint::BeforeToolExecution);
                per_call::execute_tool_call_only(per_call::ToolExecutionOnlyContext {
                    tool_call,
                    event_tx,
                    metrics_collector,
                    session_id,
                    round_id,
                    round,
                    tools,
                    config,
                    hook_session: before_tool_hooks.then_some(&mut *session),
                    hook_runtime_state: before_tool_hooks.then_some(&mut *runtime_state),
                    session_flags,
                    available_tool_schemas,
                })
                .await?
            }
        }
        Err(violation) => {
            stop_round = violation.should_stop_round();
            let message = violation.into_message();
            tracing::warn!(
                "[{}][round:{}] Tool call blocked by policy before execution: tool_call_id={}, tool_name={}, error={}",
                session_id,
                round,
                tool_call.id,
                tool_call.function.name,
                message
            );
            per_call::ToolExecutionOutcome {
                needs_human: None,
                post_tool_hook_eligible: false,
                result: Err(message),
                tool_duration: std::time::Duration::ZERO,
            }
        }
    };

    policy_guard.observe_outcome(tool_call, &outcome.result);

    // Compress tool output before applying
    let task_hint = build_task_compression_hint(task_context);
    let outcome = output_compressor::maybe_compress(
        &tool_call.function.name,
        &tool_call.function.arguments,
        session_id,
        outcome,
        session
            .effective_token_budget()
            .map(|b| b.max_tool_output_tokens)
            .unwrap_or(0),
        build_context_pressure(session),
        task_hint.as_ref(),
    )
    .await;

    let should_break = per_call::apply_tool_execution_outcome(
        per_call::ToolExecutionApplyContext {
            tool_call,
            event_tx,
            metrics_collector,
            session_id,
            round_id,
            round,
            session,
            tools,
            session_flags,
            config,
            runtime_state,
            task_context,
            state,
        },
        outcome,
    )
    .await?;

    Ok(SingleToolExecutionControl {
        should_break,
        stop_round,
    })
}

/// Check if the most recent tool result is from `compact_context` and set
/// the manual compression flag on the session so the next compression check
/// forces a compression cycle regardless of threshold.
///
/// Detection is based on the tool call name in the assistant message, not the
/// tool result content — this avoids fragility if the tool output text changes.
fn detect_manual_compression_request(session: &mut Session) {
    if session.force_manual_compression.is_some() {
        return;
    }

    // Find the most recent assistant message containing a compact_context tool call.
    let Some((call_id, instructions)) = session
        .messages
        .iter()
        .rev()
        .take(6)
        .find(|m| {
            m.role == bamboo_agent_core::Role::Assistant
                && m.tool_calls
                    .as_ref()
                    .is_some_and(|calls| calls.iter().any(|c| c.function.name == "compact_context"))
        })
        .and_then(|m| {
            m.tool_calls.as_ref().and_then(|calls| {
                let call = calls
                    .iter()
                    .find(|c| c.function.name == "compact_context")?;
                let instructions =
                    serde_json::from_str::<serde_json::Value>(&call.function.arguments)
                        .ok()
                        .and_then(|args| args.get("instructions").cloned())
                        .and_then(|v| v.as_str().map(String::from));
                Some((call.id.clone(), instructions))
            })
        })
    else {
        return;
    };

    // Verify the corresponding tool result exists (call completed, not in-flight).
    let result_exists = session.messages.iter().rev().take(4).any(|m| {
        m.role == bamboo_agent_core::Role::Tool
            && m.tool_call_id.as_deref() == Some(call_id.as_str())
    });

    if result_exists {
        tracing::info!("detected compact_context tool call, flagging for manual compression");
        session.force_manual_compression = Some(instructions.unwrap_or_default());
    }
}

/// Best-effort mid-turn context compression, run after a single tool result.
///
/// Mid-turn compression is an OPTIMIZATION, never a correctness requirement. By
/// the time it runs the assistant turn is already mid-execution: the assistant
/// message (carrying this round's `tool_calls`) has been appended and one or
/// more tools have run and committed their side effects. If the host
/// summarization LLM call fails transiently (HTTP 500 / 429 / timeout), that
/// error MUST NOT propagate out of `execute_round_tool_calls`. Propagating it
/// surfaces the failure to the per-turn retry loop, which would either
///   (a) classify it as retryable and re-run the WHOLE turn — appending a
///       SECOND assistant message, re-billing the LLM, and orphaning the
///       not-yet-executed tool calls; or
///   (b) fail the turn terminally and abort the remaining tools.
/// Both corrupt session state over a discardable optimization.
///
/// So this function is INFALLIBLE by construction: a compression failure is
/// logged and swallowed, and the turn keeps executing its remaining tools with
/// the uncompressed context. Compression is retried on the next natural
/// trigger. (issue #238)
#[allow(clippy::too_many_arguments)]
async fn maybe_apply_mid_turn_context_compression_after_tool(
    session: &mut Session,
    config: &AgentLoopConfig,
    llm: &Arc<dyn LLMProvider>,
    event_tx: &mpsc::Sender<AgentEvent>,
    session_id: &str,
    model_name: Option<&str>,
    _compression_model_provider: Option<&Arc<dyn LLMProvider>>,
    tool_schemas: &[ToolSchema],
) {
    let Some(model_name) = model_name else {
        return;
    };

    detect_manual_compression_request(session);

    match super::round_lifecycle::maybe_apply_mid_turn_context_compression(
        session,
        config,
        llm,
        event_tx,
        session_id,
        model_name,
        tool_schemas,
    )
    .await
    {
        Ok(true) => {
            tracing::debug!(
                "[{}] Applied mid-turn host context compression after single tool result",
                session_id
            );
        }
        Ok(false) => {}
        // Degrade gracefully: a transient summarization failure must never abort
        // or retry the whole turn — keep running the remaining tools uncompressed.
        Err(error) => {
            tracing::warn!(
                "[{}] Mid-turn context compression failed; continuing the turn with uncompressed context (best-effort, will retry on next trigger): {}",
                session_id,
                error
            );
        }
    }
}

pub(crate) struct RoundToolExecution<'a, 'frame> {
    pub(crate) tool_calls: &'a [ToolCall],
    pub(crate) frame: &'a crate::runtime::runner::round_frame::RoundFrame<'frame>,
    pub(crate) session: &'a mut Session,
    pub(crate) runtime_state: &'a mut AgentRuntimeState,
    pub(crate) task_context: &'a mut Option<TaskLoopContext>,
    pub(crate) compression_model_name: Option<&'a str>,
    pub(crate) compression_model_provider: Option<&'a Arc<dyn LLMProvider>>,
    pub(crate) tool_schemas: &'a [ToolSchema],
}

pub(crate) async fn execute_round_tool_calls(
    execution: RoundToolExecution<'_, '_>,
) -> Result<RoundToolExecutionResult, AgentError> {
    let RoundToolExecution {
        tool_calls,
        frame,
        session,
        runtime_state,
        task_context,
        compression_model_name,
        compression_model_provider,
        tool_schemas,
    } = execution;

    // Bind frame fields as locals so the rest of the function body stays unchanged.
    let event_tx = frame.event_tx;
    let metrics_collector = frame.metrics_collector;
    let session_id = frame.session_id;
    let round_id = frame.round_id;
    let round = frame.turn;
    let tools = frame.tools;
    let config = frame.config;
    let llm = frame.llm;

    // Build the executor's full tool-schema list ONCE for this round instead of
    // on every individual tool call (the per-call path previously called
    // `tools.list_tools()`, which clones all ~25 schemas — each carrying a JSON
    // parameters block — per invocation). The slice is threaded into the dispatch
    // context via `ToolExecutionOnlyContext::available_tool_schemas`. It is a
    // local, so it is scoped to this round/session and can never leak one
    // session's tool set into another. NOTE: this is the executor's full set and
    // is DISTINCT from the `tool_schemas` parameter (the per-session *filtered*
    // prompt set) — they must not be conflated. The agent loop never
    // registers/unregisters tools mid-round, so the snapshot stays valid for the
    // whole round.
    let available_tool_schemas: Vec<ToolSchema> = tools.list_tools();
    let available_tool_schemas = available_tool_schemas.as_slice();

    let mut state = RoundExecutionState::default();
    let mut policy_guard = policy::ToolPolicyGuard::new(
        config.max_tool_calls_per_round,
        config.max_consecutive_failures_per_tool,
    );

    // Pre-classify all tool calls to avoid repeated normalization.
    let scheduling_modes: Vec<ToolSchedulingMode> = if config
        .hook_runner
        .has_hooks_for(AgentHookPoint::BeforeToolExecution)
    {
        vec![ToolSchedulingMode::Sequential; tool_calls.len()]
    } else {
        tool_calls
            .iter()
            .map(|tc| scheduling_mode_for_tool_call(tc, tools))
            .collect()
    };

    let mut next_index = 0usize;
    'tool_calls: while next_index < tool_calls.len() {
        let tool_call = &tool_calls[next_index];

        if scheduling_modes[next_index] == ToolSchedulingMode::ParallelSafe {
            let batch_start = next_index;
            while next_index < tool_calls.len()
                && scheduling_modes[next_index] == ToolSchedulingMode::ParallelSafe
            {
                next_index += 1;
            }

            let batch = &tool_calls[batch_start..next_index];

            let policy_precheck_error = batch
                .iter()
                .enumerate()
                .find_map(|(offset, call)| policy_guard.check_before_execution(call, offset).err());

            if policy_precheck_error.is_some() {
                for batch_call in batch {
                    let control = execute_and_apply_single_tool_call(
                        batch_call,
                        event_tx,
                        metrics_collector,
                        session_id,
                        round_id,
                        round,
                        session,
                        tools,
                        config,
                        available_tool_schemas,
                        runtime_state,
                        task_context,
                        &mut state,
                        &mut policy_guard,
                        0,
                    )
                    .await?;

                    maybe_apply_mid_turn_context_compression_after_tool(
                        session,
                        config,
                        llm,
                        event_tx,
                        session_id,
                        compression_model_name,
                        compression_model_provider,
                        tool_schemas,
                    )
                    .await;

                    if control.should_break || control.stop_round {
                        break 'tool_calls;
                    }
                }
                continue;
            }

            // Single parallel-safe tool: execute directly, skip join_all overhead
            if batch.len() == 1 {
                let control = execute_and_apply_single_tool_call(
                    &batch[0],
                    event_tx,
                    metrics_collector,
                    session_id,
                    round_id,
                    round,
                    session,
                    tools,
                    config,
                    available_tool_schemas,
                    runtime_state,
                    task_context,
                    &mut state,
                    &mut policy_guard,
                    0,
                )
                .await?;

                maybe_apply_mid_turn_context_compression_after_tool(
                    session,
                    config,
                    llm,
                    event_tx,
                    session_id,
                    compression_model_name,
                    compression_model_provider,
                    tool_schemas,
                )
                .await;

                if control.should_break || control.stop_round {
                    break 'tool_calls;
                }
                continue;
            }

            // A true parallel batch has one admission boundary: refresh once
            // before any task is spawned, then freeze one flags snapshot across
            // every already-started call. A transition during the batch applies
            // at the next sequential call or batch, never nondeterministically
            // to only part of this batch.
            super::state_bridge::refresh_tool_boundary_permission_posture(
                session,
                runtime_state,
                config.storage.as_ref(),
            )
            .await?;

            let tool_names: Vec<&str> = batch.iter().map(|tc| tc.function.name.as_str()).collect();
            tracing::info!(
                "[{}][round:{}] ⚡ Executing {} parallel-safe tool calls concurrently: {:?}",
                session_id,
                round,
                batch.len(),
                tool_names
            );

            let parallel_start = std::time::Instant::now();
            let per_tool_timeout = std::time::Duration::from_secs(config.per_tool_timeout_secs);
            let batch_timeout = std::time::Duration::from_secs(config.parallel_batch_timeout_secs);
            // Derive once before the parallel borrow; the Copy flags struct is
            // captured by each concurrent task (we can't borrow `&mut session`
            // inside them).
            let session_flags = bamboo_agent_core::tools::ToolExecutionSessionFlags::from_session_and_configured_mode(
                session,
                config.permission_mode.unwrap_or_default(),
            );
            let outcomes = tokio::time::timeout(
                batch_timeout,
                join_all(batch.iter().map(|tool_call| {
                    let timeout = per_tool_timeout;
                    async move {
                        tokio::time::timeout(
                            timeout,
                            per_call::execute_tool_call_only(per_call::ToolExecutionOnlyContext {
                                tool_call,
                                event_tx,
                                metrics_collector,
                                session_id,
                                round_id,
                                round,
                                tools,
                                config,
                                hook_session: None,
                                hook_runtime_state: None,
                                session_flags,
                                available_tool_schemas,
                            }),
                        )
                        .await
                        .unwrap_or_else(|_| {
                            Ok(per_call::ToolExecutionOutcome {
                                needs_human: None,
                                post_tool_hook_eligible: true,
                                result: Err(format!(
                                    "Tool '{}' timed out after {:?}",
                                    tool_call.function.name, timeout
                                )),
                                tool_duration: timeout,
                            })
                        })
                    }
                })),
            )
            .await
            .unwrap_or_else(|_| {
                tracing::warn!(
                    "[{}][round:{}] Parallel batch timed out after {:?}",
                    session_id,
                    round,
                    batch_timeout
                );
                batch
                    .iter()
                    .map(|_batch_call| {
                        Ok(per_call::ToolExecutionOutcome {
                            needs_human: None,
                            post_tool_hook_eligible: true,
                            result: Err(format!(
                                "Parallel batch timed out after {:?}",
                                batch_timeout
                            )),
                            tool_duration: batch_timeout,
                        })
                    })
                    .collect::<Vec<_>>()
            });
            let outcomes = outcomes
                .into_iter()
                .collect::<Result<Vec<_>, AgentError>>()?;
            let parallel_elapsed = parallel_start.elapsed();

            // Log individual tool durations to confirm parallelism
            let individual_durations: Vec<String> = batch
                .iter()
                .zip(outcomes.iter())
                .map(|(tc, o)| format!("{}={:?}", tc.function.name, o.tool_duration))
                .collect();
            let sum_sequential: std::time::Duration =
                outcomes.iter().map(|o| o.tool_duration).sum();
            tracing::info!(
                "[{}][round:{}] ⚡ Parallel batch completed in {:?} (sequential would be {:?}, speedup {:.1}x): [{}]",
                session_id,
                round,
                parallel_elapsed,
                sum_sequential,
                if parallel_elapsed.as_millis() > 0 {
                    sum_sequential.as_millis() as f64 / parallel_elapsed.as_millis() as f64
                } else {
                    1.0
                },
                individual_durations.join(", ")
            );

            // Compress all outcomes in parallel before applying sequentially.
            let max_tool_tokens = session
                .effective_token_budget()
                .map(|b| b.max_tool_output_tokens)
                .unwrap_or(0);
            let pressure = build_context_pressure(session);
            let task_hint = build_task_compression_hint(task_context);
            let compressed: Vec<_> =
                join_all(batch.iter().zip(outcomes).map(|(batch_call, outcome)| {
                    let tool_name = batch_call.function.name.clone();
                    let args = batch_call.function.arguments.clone();
                    let sid = session_id.to_string();
                    let pressure = pressure
                        .as_ref()
                        .map(|p| output_compressor::ContextPressure {
                            usage_percent: p.usage_percent,
                            remaining_tokens: p.remaining_tokens,
                        });
                    let task_hint = task_hint.clone();
                    async move {
                        output_compressor::maybe_compress(
                            &tool_name,
                            &args,
                            &sid,
                            outcome,
                            max_tool_tokens,
                            pressure,
                            task_hint.as_ref(),
                        )
                        .await
                    }
                }))
                .await;

            for (batch_call, outcome) in batch.iter().zip(compressed) {
                policy_guard.observe_outcome(batch_call, &outcome.result);

                let should_break = per_call::apply_tool_execution_outcome(
                    per_call::ToolExecutionApplyContext {
                        tool_call: batch_call,
                        event_tx,
                        metrics_collector,
                        session_id,
                        round_id,
                        round,
                        session,
                        tools,
                        session_flags,
                        config,
                        runtime_state,
                        task_context,
                        state: &mut state,
                    },
                    outcome,
                )
                .await?;

                maybe_apply_mid_turn_context_compression_after_tool(
                    session,
                    config,
                    llm,
                    event_tx,
                    session_id,
                    compression_model_name,
                    compression_model_provider,
                    tool_schemas,
                )
                .await;

                if should_break {
                    break 'tool_calls;
                }
            }

            continue;
        }

        let control = execute_and_apply_single_tool_call(
            tool_call,
            event_tx,
            metrics_collector,
            session_id,
            round_id,
            round,
            session,
            tools,
            config,
            available_tool_schemas,
            runtime_state,
            task_context,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await?;

        next_index += 1;

        maybe_apply_mid_turn_context_compression_after_tool(
            session,
            config,
            llm,
            event_tx,
            session_id,
            compression_model_name,
            compression_model_provider,
            tool_schemas,
        )
        .await;

        if control.should_break || control.stop_round {
            break;
        }
    }

    Ok(state.into_result())
}

#[cfg(test)]
mod tests {
    use super::{
        execute_round_tool_calls, scheduling_mode_for_tool_call, RoundToolExecution,
        RoundToolExecutionResult, ToolSchedulingMode,
    };
    use bamboo_agent_core::storage::Storage;
    use bamboo_agent_core::tools::{
        FunctionCall, FunctionSchema, ToolCall, ToolExecutionContext, ToolExecutor, ToolOutcome,
        ToolResult, ToolSchema,
    };
    use bamboo_agent_core::{AgentError, AgentEvent, Message, Session};
    use bamboo_domain::{AgentRuntimeState, PermissionAuditSnapshot, SessionPermissionMode};
    use bamboo_llm::{LLMChunk, LLMError, LLMProvider, LLMStream};
    use bamboo_tools::BuiltinToolExecutor;
    use futures::stream;
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use tokio::sync::mpsc;

    fn tool_call(name: &str) -> ToolCall {
        tool_call_with_args(name, json!({}))
    }

    fn tool_call_with_args(name: &str, args: serde_json::Value) -> ToolCall {
        ToolCall {
            id: "call_1".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: args.to_string(),
            },
        }
    }

    fn builtin_tools() -> Arc<dyn ToolExecutor> {
        Arc::new(BuiltinToolExecutor::new())
    }

    #[derive(Clone, Copy)]
    enum BoundaryTransition {
        Mode(SessionPermissionMode, u64),
        FailNextLoad,
        RemoveSession,
    }

    struct BoundaryStorage {
        session: Mutex<Option<Session>>,
        loads: AtomicUsize,
        fail_on_load: AtomicUsize,
    }

    impl BoundaryStorage {
        fn new(session: Session) -> Self {
            Self {
                session: Mutex::new(Some(session)),
                loads: AtomicUsize::new(0),
                fail_on_load: AtomicUsize::new(0),
            }
        }

        fn apply(&self, transition: BoundaryTransition) {
            match transition {
                BoundaryTransition::Mode(mode, audit_revision) => {
                    let mut guard = self.session.lock().expect("boundary storage lock");
                    let mut session = guard.clone().expect("transition requires session");
                    session
                        .agent_runtime_state
                        .get_or_insert_with(AgentRuntimeState::default)
                        .set_permission_mode(mode);
                    permission_audit(mode, audit_revision).write_to(&mut session.metadata);
                    *guard = Some(session);
                }
                BoundaryTransition::FailNextLoad => {
                    self.fail_on_load
                        .store(self.loads.load(Ordering::SeqCst) + 1, Ordering::SeqCst);
                }
                BoundaryTransition::RemoveSession => {
                    *self.session.lock().expect("boundary storage lock") = None;
                }
            }
        }

        fn load_count(&self) -> usize {
            self.loads.load(Ordering::SeqCst)
        }
    }

    #[async_trait::async_trait]
    impl Storage for BoundaryStorage {
        async fn save_session(&self, session: &Session) -> std::io::Result<()> {
            *self.session.lock().expect("boundary storage lock") = Some(session.clone());
            Ok(())
        }

        async fn load_session(&self, _session_id: &str) -> std::io::Result<Option<Session>> {
            Ok(self.session.lock().expect("boundary storage lock").clone())
        }

        async fn load_runtime_control_plane(
            &self,
            _session_id: &str,
        ) -> std::io::Result<Option<Session>> {
            let load = self.loads.fetch_add(1, Ordering::SeqCst) + 1;
            if self.fail_on_load.load(Ordering::SeqCst) == load {
                return Err(std::io::Error::other("injected control-plane read failure"));
            }
            Ok(self.session.lock().expect("boundary storage lock").clone())
        }

        async fn delete_session(&self, _session_id: &str) -> std::io::Result<bool> {
            Ok(self
                .session
                .lock()
                .expect("boundary storage lock")
                .take()
                .is_some())
        }
    }

    struct PermissionBoundaryExecutor {
        storage: Arc<BoundaryStorage>,
        transition_on: &'static str,
        transition: BoundaryTransition,
        flags: Mutex<HashMap<String, bamboo_agent_core::tools::ToolExecutionSessionFlags>>,
        approval_requests: AtomicUsize,
        mutations: AtomicUsize,
    }

    impl PermissionBoundaryExecutor {
        fn new(
            storage: Arc<BoundaryStorage>,
            transition_on: &'static str,
            transition: BoundaryTransition,
        ) -> Self {
            Self {
                storage,
                transition_on,
                transition,
                flags: Mutex::new(HashMap::new()),
                approval_requests: AtomicUsize::new(0),
                mutations: AtomicUsize::new(0),
            }
        }

        fn flags_for(&self, tool: &str) -> bamboo_agent_core::tools::ToolExecutionSessionFlags {
            *self
                .flags
                .lock()
                .expect("permission probe flags lock")
                .get(tool)
                .expect("tool must have entered executor")
        }

        fn entered(&self, tool: &str) -> bool {
            self.flags
                .lock()
                .expect("permission probe flags lock")
                .contains_key(tool)
        }
    }

    #[async_trait::async_trait]
    impl ToolExecutor for PermissionBoundaryExecutor {
        async fn execute(
            &self,
            call: &ToolCall,
        ) -> bamboo_agent_core::tools::executor::Result<ToolResult> {
            Ok(ToolResult::text(
                true,
                format!("{} complete", call.function.name),
            ))
        }

        async fn execute_with_context_outcome(
            &self,
            call: &ToolCall,
            ctx: ToolExecutionContext<'_>,
        ) -> bamboo_agent_core::tools::executor::Result<ToolOutcome> {
            self.flags
                .lock()
                .expect("permission probe flags lock")
                .insert(
                    call.function.name.clone(),
                    bamboo_agent_core::tools::ToolExecutionSessionFlags {
                        bypass_permissions: ctx.bypass_permissions,
                        auto_approve_permissions: ctx.auto_approve_permissions,
                        plan_read_only: ctx.plan_read_only,
                    },
                );
            if call.function.name == self.transition_on {
                self.storage.apply(self.transition);
            }
            if matches!(call.function.name.as_str(), "mutation" | "after_batch") {
                if ctx.auto_approve_permissions {
                    self.mutations.fetch_add(1, Ordering::SeqCst);
                } else {
                    self.approval_requests.fetch_add(1, Ordering::SeqCst);
                    return Ok(ToolOutcome::NeedsHuman {
                        question: bamboo_agent_core::PendingQuestion {
                            tool_call_id: call.id.clone(),
                            tool_name: call.function.name.clone(),
                            question: "Approve mutation?".to_string(),
                            options: vec!["approve".to_string(), "deny".to_string()],
                            allow_custom: false,
                            source: bamboo_agent_core::PendingQuestionSource::PauseTool,
                        },
                        result: ToolResult::text(false, "approval required"),
                    });
                }
            }
            Ok(ToolOutcome::Completed(ToolResult::text(
                true,
                format!("{} complete", call.function.name),
            )))
        }

        fn list_tools(&self) -> Vec<ToolSchema> {
            [
                "prepare",
                "mutation",
                "parallel_a",
                "parallel_b",
                "after_batch",
            ]
            .into_iter()
            .map(|name| ToolSchema {
                schema_type: "function".to_string(),
                function: FunctionSchema {
                    name: name.to_string(),
                    description: "permission boundary probe".to_string(),
                    parameters: json!({"type": "object", "properties": {}}),
                },
            })
            .collect()
        }

        fn call_parallel_classification(
            &self,
            call: &ToolCall,
        ) -> (bamboo_agent_core::tools::ToolMutability, bool) {
            if call.function.name.starts_with("parallel_") {
                (bamboo_agent_core::tools::ToolMutability::ReadOnly, true)
            } else {
                (bamboo_agent_core::tools::ToolMutability::Mutating, false)
            }
        }
    }

    struct BoundaryNoopProvider;

    #[async_trait::async_trait]
    impl LLMProvider for BoundaryNoopProvider {
        async fn chat_stream(
            &self,
            _messages: &[Message],
            _tools: &[ToolSchema],
            _max_output_tokens: Option<u32>,
            _model: &str,
        ) -> Result<LLMStream, LLMError> {
            Ok(Box::pin(stream::iter(vec![Ok(LLMChunk::Done)])))
        }
    }

    fn permission_audit(mode: SessionPermissionMode, revision: u64) -> PermissionAuditSnapshot {
        let resolution =
            bamboo_domain::resolve_permission_mode(mode, bamboo_domain::PermissionMode::Default);
        PermissionAuditSnapshot {
            audit_revision: revision,
            policy_revision: revision,
            resolution,
            executor_mapping: format!("bamboo_runtime:{}", resolution.effective.as_str()),
            transitioned_at: format!("2026-07-31T12:00:{:02}Z", revision.min(59)),
        }
    }

    fn permission_session(id: &str, mode: SessionPermissionMode, revision: u64) -> Session {
        let mut session = Session::new(id, "model");
        let mut runtime_state = AgentRuntimeState::new("permission-boundary-run");
        runtime_state.set_permission_mode(mode);
        session.agent_runtime_state = Some(runtime_state);
        permission_audit(mode, revision).write_to(&mut session.metadata);
        session
    }

    fn named_call(id: &str, name: &str) -> ToolCall {
        ToolCall {
            id: id.to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: "{}".to_string(),
            },
        }
    }

    async fn run_permission_boundary_calls(
        storage: Arc<BoundaryStorage>,
        executor: Arc<PermissionBoundaryExecutor>,
        mut session: Session,
        calls: &[ToolCall],
    ) -> (
        Result<RoundToolExecutionResult, AgentError>,
        Session,
        AgentRuntimeState,
        Vec<AgentEvent>,
    ) {
        let storage_port: Arc<dyn Storage> = storage;
        let tools: Arc<dyn ToolExecutor> = executor;
        let config = crate::runtime::config::AgentLoopConfig {
            storage: Some(storage_port),
            ..Default::default()
        };
        let (event_tx, mut event_rx) = mpsc::channel(64);
        let llm: Arc<dyn LLMProvider> = Arc::new(BoundaryNoopProvider);
        let session_id = session.id.clone();
        let frame = crate::runtime::runner::round_frame::RoundFrame {
            session_id: &session_id,
            round_id: "permission-boundary-round",
            turn: 0,
            debug_enabled: false,
            event_tx: &event_tx,
            metrics_collector: None,
            config: &config,
            llm: &llm,
            tools: &tools,
        };
        let tool_schemas = tools.list_tools();
        let mut runtime_state = session
            .agent_runtime_state
            .clone()
            .expect("permission fixture runtime state");
        let mut task_context = None;
        let result = execute_round_tool_calls(RoundToolExecution {
            tool_calls: calls,
            frame: &frame,
            session: &mut session,
            runtime_state: &mut runtime_state,
            task_context: &mut task_context,
            compression_model_name: None,
            compression_model_provider: None,
            tool_schemas: &tool_schemas,
        })
        .await;
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect();
        (result, session, runtime_state, events)
    }

    #[tokio::test]
    async fn sequential_tool_boundary_adopts_default_to_auto_before_call_b() {
        let session =
            permission_session("boundary-default-auto", SessionPermissionMode::Default, 1);
        let storage = Arc::new(BoundaryStorage::new(session.clone()));
        let executor = Arc::new(PermissionBoundaryExecutor::new(
            storage.clone(),
            "prepare",
            BoundaryTransition::Mode(SessionPermissionMode::Auto, 2),
        ));
        let calls = [
            named_call("call-a", "prepare"),
            named_call("call-b", "mutation"),
        ];

        let (result, session, runtime_state, _) =
            run_permission_boundary_calls(storage.clone(), executor.clone(), session, &calls).await;

        assert!(!result.unwrap().awaiting_clarification);
        assert_eq!(executor.approval_requests.load(Ordering::SeqCst), 0);
        assert_eq!(executor.mutations.load(Ordering::SeqCst), 1);
        assert!(executor.flags_for("mutation").auto_approve_permissions);
        assert_eq!(
            runtime_state.effective_permission_mode(),
            SessionPermissionMode::Auto
        );
        assert_eq!(
            session
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .effective_permission_mode(),
            SessionPermissionMode::Auto
        );
        let audit = PermissionAuditSnapshot::from_metadata(&session.metadata).unwrap();
        assert_eq!(audit.audit_revision, 2);
        assert_eq!(audit.resolution.requested, SessionPermissionMode::Auto);
        assert_eq!(storage.load_count(), 2, "one load per sequential call");
    }

    #[tokio::test]
    async fn sequential_tool_boundary_adopts_auto_to_default_before_call_b() {
        let session = permission_session("boundary-auto-default", SessionPermissionMode::Auto, 1);
        let storage = Arc::new(BoundaryStorage::new(session.clone()));
        let executor = Arc::new(PermissionBoundaryExecutor::new(
            storage.clone(),
            "prepare",
            BoundaryTransition::Mode(SessionPermissionMode::Default, 2),
        ));
        let calls = [
            named_call("call-a", "prepare"),
            named_call("call-b", "mutation"),
        ];

        let (result, session, runtime_state, _) =
            run_permission_boundary_calls(storage.clone(), executor.clone(), session, &calls).await;

        assert!(result.unwrap().awaiting_clarification);
        assert_eq!(executor.approval_requests.load(Ordering::SeqCst), 1);
        assert_eq!(
            executor.mutations.load(Ordering::SeqCst),
            0,
            "Default call B must stop at approval rather than reuse stale Auto"
        );
        assert!(!executor.flags_for("mutation").auto_approve_permissions);
        assert_eq!(
            runtime_state.effective_permission_mode(),
            SessionPermissionMode::Default
        );
        assert_eq!(
            session
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .effective_permission_mode(),
            SessionPermissionMode::Default
        );
        let audit = PermissionAuditSnapshot::from_metadata(&session.metadata).unwrap();
        assert_eq!(audit.audit_revision, 2);
        assert_eq!(audit.resolution.requested, SessionPermissionMode::Default);
        assert_eq!(storage.load_count(), 2, "one load per sequential call");
    }

    #[tokio::test]
    async fn sequential_tool_boundary_fails_closed_before_call_b_on_storage_loss() {
        for transition in [
            BoundaryTransition::FailNextLoad,
            BoundaryTransition::RemoveSession,
        ] {
            let session =
                permission_session("boundary-storage-loss", SessionPermissionMode::Auto, 1);
            let storage = Arc::new(BoundaryStorage::new(session.clone()));
            let executor = Arc::new(PermissionBoundaryExecutor::new(
                storage.clone(),
                "prepare",
                transition,
            ));
            let calls = [
                named_call("call-a", "prepare"),
                named_call("call-b", "mutation"),
            ];

            let (result, _, _, events) =
                run_permission_boundary_calls(storage.clone(), executor.clone(), session, &calls)
                    .await;

            let error = match result {
                Err(error) => error.to_string(),
                Ok(_) => panic!("unreadable authoritative posture must fail closed"),
            };
            assert!(error.contains("permission posture refresh failed closed"));
            assert!(executor.entered("prepare"));
            assert!(
                !executor.entered("mutation"),
                "call B must never enter the executor after an unreadable authoritative posture"
            );
            assert_eq!(executor.mutations.load(Ordering::SeqCst), 0);
            assert!(events.iter().all(|event| {
                !matches!(event, AgentEvent::ToolStart { tool_call_id, .. } if tool_call_id == "call-b")
            }));
            assert_eq!(storage.load_count(), 2);
        }
    }

    #[tokio::test]
    async fn parallel_batch_refreshes_once_and_freezes_one_permission_snapshot() {
        let session = permission_session("boundary-parallel", SessionPermissionMode::Default, 1);
        let storage = Arc::new(BoundaryStorage::new(session.clone()));
        let executor = Arc::new(PermissionBoundaryExecutor::new(
            storage.clone(),
            "parallel_a",
            BoundaryTransition::Mode(SessionPermissionMode::Auto, 2),
        ));
        let calls = [
            named_call("parallel-a", "parallel_a"),
            named_call("parallel-b", "parallel_b"),
            named_call("after-batch", "after_batch"),
        ];

        let (result, _, _, _) =
            run_permission_boundary_calls(storage.clone(), executor.clone(), session, &calls).await;

        assert!(!result.unwrap().awaiting_clarification);
        assert!(
            !executor.flags_for("parallel_a").auto_approve_permissions
                && !executor.flags_for("parallel_b").auto_approve_permissions,
            "every already-started call in the batch must share its pre-batch Default snapshot"
        );
        assert!(
            executor.flags_for("after_batch").auto_approve_permissions,
            "the next safe boundary must adopt the mid-batch Default-to-Auto transition"
        );
        assert_eq!(
            storage.load_count(),
            2,
            "one load for the two-call parallel batch plus one for the following sequential call"
        );
    }

    #[test]
    fn read_tools_are_parallel_safe() {
        let tools = builtin_tools();
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call("Read"), &tools),
            ToolSchedulingMode::ParallelSafe
        );
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call("read_file"), &tools),
            ToolSchedulingMode::ParallelSafe
        );
    }

    #[test]
    fn all_parallel_safe_tools_are_classified_correctly() {
        let tools = builtin_tools();
        let parallel_tools = [
            "GetFileInfo",
            "Glob",
            "Grep",
            "Read",
            "WebFetch",
            "WebSearch",
            "Workspace",
            "BashOutput",
            "session_history",
            "Sleep",
        ];
        for name in &parallel_tools {
            assert_eq!(
                scheduling_mode_for_tool_call(&tool_call(name), &tools),
                ToolSchedulingMode::ParallelSafe,
                "{name} should be parallel-safe"
            );
        }

        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("session_note", json!({"action": "read"})),
                &tools
            ),
            ToolSchedulingMode::ParallelSafe,
            "session_note read action should be parallel-safe"
        );
        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("session_note", json!({"action": "list_topics"})),
                &tools
            ),
            ToolSchedulingMode::ParallelSafe,
            "session_note list_topics action should be parallel-safe"
        );
        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("session_note", json!({"action": "append", "content": "x"})),
                &tools
            ),
            ToolSchedulingMode::Sequential,
            "session_note append action should be sequential"
        );
    }

    #[test]
    fn aliases_resolve_to_parallel_safe() {
        let tools = builtin_tools();
        let aliases = [
            "read_file",
            "file_exists",
            "fileExists",
            "list_directory",
            "get_file_info",
            "getFileInfo",
            "get_current_dir",
            "getCurrentDir",
        ];
        for alias in &aliases {
            assert_eq!(
                scheduling_mode_for_tool_call(&tool_call(alias), &tools),
                ToolSchedulingMode::ParallelSafe,
                "alias {alias} should resolve to a parallel-safe tool"
            );
        }

        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("memory_note", json!({"action": "read"})),
                &tools
            ),
            ToolSchedulingMode::ParallelSafe,
            "memory_note read alias should be parallel-safe"
        );
        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("memory_note", json!({"action": "list_topics"})),
                &tools
            ),
            ToolSchedulingMode::ParallelSafe,
            "memory_note list_topics alias should be parallel-safe"
        );
        assert_eq!(
            scheduling_mode_for_tool_call(
                &tool_call_with_args("memory_note", json!({"action": "append", "content": "x"})),
                &tools
            ),
            ToolSchedulingMode::Sequential,
            "memory_note append alias should be sequential"
        );
    }

    #[test]
    fn side_effect_tools_remain_sequential() {
        let tools = builtin_tools();
        let sequential_tools = [
            "Write",
            "Edit",
            "Bash",
            "conclusion_with_options",
            "Task",
            "NotebookEdit",
            "KillShell",
            "scheduler",
            "SubSession",
        ];
        for name in &sequential_tools {
            assert_eq!(
                scheduling_mode_for_tool_call(&tool_call(name), &tools),
                ToolSchedulingMode::Sequential,
                "{name} should be sequential"
            );
        }
    }

    #[test]
    fn mcp_tools_are_sequential() {
        let tools = builtin_tools();
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call("mcp__playwright__browser_snapshot"), &tools),
            ToolSchedulingMode::Sequential,
        );
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call("mcp__some_server__some_tool"), &tools),
            ToolSchedulingMode::Sequential,
        );
    }

    #[test]
    fn unknown_tools_are_sequential() {
        let tools = builtin_tools();
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call("totally_unknown_tool"), &tools),
            ToolSchedulingMode::Sequential,
        );
        assert_eq!(
            scheduling_mode_for_tool_call(&tool_call(""), &tools),
            ToolSchedulingMode::Sequential,
        );
    }

    #[test]
    fn plan_mode_exempt_tools_are_correct() {
        for name in [
            "EnterPlanMode",
            "ExitPlanMode",
            "request_permissions",
            "conclusion_with_options",
            "compact_context",
        ] {
            assert!(
                bamboo_tools::orchestrator::plan_mode_allows_tool(name),
                "{name} should be admitted by the shared Plan gate"
            );
        }
    }

    #[test]
    fn plan_mode_blocks_mutating_tools_via_classify() {
        let mutating_tools = [
            "Write",
            "Edit",
            "Bash",
            "NotebookEdit",
            "KillShell",
            "totally_unknown_tool",
        ];
        for name in mutating_tools {
            assert!(
                !bamboo_tools::orchestrator::plan_mode_allows_tool(name),
                "{name} should be blocked in plan mode"
            );
        }
    }

    #[test]
    fn plan_mode_allows_read_only_tools_via_classify() {
        // Read-only tools should pass through plan mode
        let read_only_tools = [
            "Read",
            "GetFileInfo",
            "Glob",
            "Grep",
            "WebFetch",
            "WebSearch",
            "BashOutput",
            "session_history",
            "Sleep",
        ];
        for name in read_only_tools {
            assert!(
                bamboo_tools::orchestrator::plan_mode_allows_tool(name),
                "{name} should be read-only (allowed in plan mode)"
            );
        }
    }

    #[tokio::test]
    async fn plan_mode_gate_remains_authoritative_under_auto() {
        use super::{execute_and_apply_single_tool_call, loop_state::RoundExecutionState, policy};
        use bamboo_agent_core::Session;
        use bamboo_config::PermissionMode;
        use tokio::sync::mpsc;

        let (event_tx, _event_rx) = mpsc::channel(100);
        let mut session = Session::new("test-session", "test-model");
        let tools = builtin_tools();
        let config = crate::runtime::config::AgentLoopConfig {
            permission_mode: Some(PermissionMode::Plan),
            ..Default::default()
        };

        let mut state = RoundExecutionState::default();
        let mut runtime_state = AgentRuntimeState::new("test-session");
        runtime_state.set_permission_mode(bamboo_domain::SessionPermissionMode::Auto);
        let mut policy_guard = policy::ToolPolicyGuard::new(80, 3);

        let tool_call = tool_call_with_args(
            "Write",
            json!({"file_path": "/tmp/plan_mode_test.txt", "content": "test"}),
        );

        let control = execute_and_apply_single_tool_call(
            &tool_call,
            &event_tx,
            None,
            "test-session",
            "test-round-1",
            0,
            &mut session,
            &tools,
            &config,
            tools.list_tools().as_slice(),
            &mut runtime_state,
            &mut None,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await
        .unwrap();

        // Should not break the round, just block the tool
        assert!(!control.should_break);
        assert!(!control.stop_round);

        // The session should have a tool result message with the plan mode error
        let last_msg = session.messages.last().expect("should have a tool result");
        assert!(
            last_msg.content.contains("Plan mode"),
            "Tool result should contain 'Plan mode' error, got: {}",
            last_msg.content
        );
    }

    #[tokio::test]
    async fn plan_mode_gate_allows_read_in_pipeline() {
        use super::{execute_and_apply_single_tool_call, loop_state::RoundExecutionState, policy};
        use bamboo_agent_core::Session;
        use bamboo_config::PermissionMode;
        use tokio::sync::mpsc;

        let (event_tx, _event_rx) = mpsc::channel(100);
        let mut session = Session::new("test-session", "test-model");
        let tools = builtin_tools();
        let config = crate::runtime::config::AgentLoopConfig {
            permission_mode: Some(PermissionMode::Plan),
            ..Default::default()
        };

        let mut state = RoundExecutionState::default();
        let mut runtime_state = AgentRuntimeState::new("test-session");
        let mut policy_guard = policy::ToolPolicyGuard::new(80, 3);

        let temp_dir = std::env::temp_dir().join("bamboo_plan_mode_read_test");
        std::fs::create_dir_all(&temp_dir).ok();
        let file_path = temp_dir.join("test.txt");
        std::fs::write(&file_path, "hello").ok();

        let tool_call =
            tool_call_with_args("Read", json!({"file_path": file_path.to_str().unwrap()}));

        let control = execute_and_apply_single_tool_call(
            &tool_call,
            &event_tx,
            None,
            "test-session",
            "test-round-1",
            0,
            &mut session,
            &tools,
            &config,
            tools.list_tools().as_slice(),
            &mut runtime_state,
            &mut None,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await
        .unwrap();

        assert!(!control.should_break);
        assert!(!control.stop_round);

        let last_msg = session.messages.last().expect("should have a tool result");
        assert!(
            !last_msg.content.contains("Plan mode"),
            "Read should not be blocked in plan mode, got: {}",
            last_msg.content
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    async fn auto_request_permissions_returns_error_without_pending_clarification() {
        use super::{execute_and_apply_single_tool_call, loop_state::RoundExecutionState, policy};
        use bamboo_agent_core::Session;
        use bamboo_config::PermissionMode;
        use tokio::sync::mpsc;

        let (event_tx, mut event_rx) = mpsc::channel(100);
        let mut session = Session::new("auto-no-prompt", "test-model");
        let tools = builtin_tools();
        let config = crate::runtime::config::AgentLoopConfig {
            permission_mode: Some(PermissionMode::Auto),
            ..Default::default()
        };
        let mut state = RoundExecutionState::default();
        let mut runtime_state = AgentRuntimeState::new("auto-no-prompt");
        runtime_state.set_permission_mode(bamboo_domain::SessionPermissionMode::Auto);
        let mut policy_guard = policy::ToolPolicyGuard::new(80, 3);
        let tool_call = tool_call_with_args("request_permissions", json!({}));

        let control = execute_and_apply_single_tool_call(
            &tool_call,
            &event_tx,
            None,
            "auto-no-prompt",
            "auto-round-1",
            0,
            &mut session,
            &tools,
            &config,
            tools.list_tools().as_slice(),
            &mut runtime_state,
            &mut None,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await
        .unwrap();

        assert!(!control.should_break);
        assert!(!control.stop_round);
        assert!(!session.has_pending_question());
        assert!(session.messages.last().is_some_and(|message| message
            .content
            .contains("cannot request expanded permissions")));
        let events = std::iter::from_fn(|| event_rx.try_recv().ok()).collect::<Vec<_>>();
        assert!(events
            .iter()
            .all(|event| !matches!(event, AgentEvent::NeedClarification { .. })));
    }

    #[tokio::test]
    async fn plan_mode_gate_allows_exit_plan_mode_tool() {
        use super::{execute_and_apply_single_tool_call, loop_state::RoundExecutionState, policy};
        use bamboo_agent_core::Session;
        use bamboo_config::PermissionMode;
        use tokio::sync::mpsc;

        let (event_tx, _event_rx) = mpsc::channel(100);
        let mut session = Session::new("test-session", "test-model");
        let tools = builtin_tools();
        let config = crate::runtime::config::AgentLoopConfig {
            permission_mode: Some(PermissionMode::Plan),
            ..Default::default()
        };

        let mut state = RoundExecutionState::default();
        let mut runtime_state = AgentRuntimeState::new("test-session");
        let mut policy_guard = policy::ToolPolicyGuard::new(80, 3);

        let tool_call = tool_call_with_args("ExitPlanMode", json!({"plan": "test plan"}));

        let control = execute_and_apply_single_tool_call(
            &tool_call,
            &event_tx,
            None,
            "test-session",
            "test-round-1",
            0,
            &mut session,
            &tools,
            &config,
            tools.list_tools().as_slice(),
            &mut runtime_state,
            &mut None,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await
        .unwrap();

        assert!(!control.stop_round);
        let last_msg = session.messages.last().expect("should have a tool result");
        assert!(
            !last_msg
                .content
                .contains("Plan mode: ExitPlanMode operation blocked"),
            "ExitPlanMode should be exempt from plan mode gate, got: {}",
            last_msg.content
        );
    }

    #[tokio::test]
    async fn default_mode_does_not_block_write() {
        use super::{execute_and_apply_single_tool_call, loop_state::RoundExecutionState, policy};
        use bamboo_agent_core::Session;
        use tokio::sync::mpsc;

        let (event_tx, _event_rx) = mpsc::channel(100);
        let mut session = Session::new("test-session", "test-model");
        let tools = builtin_tools();
        let config = crate::runtime::config::AgentLoopConfig::default();

        let mut state = RoundExecutionState::default();
        let mut runtime_state = AgentRuntimeState::new("test-session");
        let mut policy_guard = policy::ToolPolicyGuard::new(80, 3);

        let temp_dir = std::env::temp_dir().join("bamboo_default_mode_test");
        std::fs::create_dir_all(&temp_dir).ok();
        let file_path = temp_dir.join("test.txt");

        let tool_call = tool_call_with_args(
            "Write",
            json!({"file_path": file_path.to_str().unwrap(), "content": "test"}),
        );

        let control = execute_and_apply_single_tool_call(
            &tool_call,
            &event_tx,
            None,
            "test-session",
            "test-round-1",
            0,
            &mut session,
            &tools,
            &config,
            tools.list_tools().as_slice(),
            &mut runtime_state,
            &mut None,
            &mut state,
            &mut policy_guard,
            0,
        )
        .await
        .unwrap();

        assert!(!control.stop_round);
        let last_msg = session.messages.last().expect("should have a tool result");
        assert!(
            !last_msg.content.contains("Plan mode"),
            "Write should work in default mode, got: {}",
            last_msg.content
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn detect_manual_compression_request_sets_flag_when_tool_result_exists() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s1", "m1");

        // Assistant message with compact_context tool call
        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![ToolCall {
            id: "call-1".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "compact_context".to_string(),
                arguments: r#"{"instructions":"keep API signatures"}"#.to_string(),
            },
        }]);
        session.messages.push(assistant);

        // Tool result message
        let mut tool_result = Message::tool_result("call-1", "Context compression requested");
        tool_result.id = "msg-2".to_string();
        session.messages.push(tool_result);

        assert!(session.force_manual_compression.is_none());
        detect_manual_compression_request(&mut session);
        assert_eq!(
            session.force_manual_compression.as_deref(),
            Some("keep API signatures")
        );
    }

    #[test]
    fn detect_manual_compression_request_extracts_empty_when_no_instructions() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s2", "m2");

        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![ToolCall {
            id: "call-2".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "compact_context".to_string(),
                arguments: "{}".to_string(),
            },
        }]);
        session.messages.push(assistant);

        let mut tool_result = Message::tool_result("call-2", "ok");
        tool_result.id = "msg-2".to_string();
        session.messages.push(tool_result);

        detect_manual_compression_request(&mut session);
        assert!(session.force_manual_compression.is_some());
        assert_eq!(session.force_manual_compression.as_deref(), Some(""));
    }

    #[test]
    fn detect_manual_compression_request_skips_if_flag_already_set() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s3", "m3");
        session.force_manual_compression = Some("already set".to_string());

        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![ToolCall {
            id: "call-3".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "compact_context".to_string(),
                arguments: r#"{"instructions":"new instructions"}"#.to_string(),
            },
        }]);
        session.messages.push(assistant);

        let mut tool_result = Message::tool_result("call-3", "ok");
        tool_result.id = "msg-2".to_string();
        session.messages.push(tool_result);

        detect_manual_compression_request(&mut session);
        assert_eq!(
            session.force_manual_compression.as_deref(),
            Some("already set")
        );
    }

    #[test]
    fn detect_manual_compression_request_does_nothing_without_tool_result() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s4", "m4");

        // Only the assistant tool call — no tool result yet (tool is in-flight)
        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![ToolCall {
            id: "call-4".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "compact_context".to_string(),
                arguments: "{}".to_string(),
            },
        }]);
        session.messages.push(assistant);

        detect_manual_compression_request(&mut session);
        assert!(session.force_manual_compression.is_none());
    }

    #[test]
    fn detect_manual_compression_request_does_nothing_for_other_tools() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s5", "m5");

        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![ToolCall {
            id: "call-5".to_string(),
            tool_type: "function".to_string(),
            function: FunctionCall {
                name: "Read".to_string(),
                arguments: r#"{"file_path":"/tmp/test"}"#.to_string(),
            },
        }]);
        session.messages.push(assistant);

        let mut tool_result = Message::tool_result("call-5", "file contents");
        tool_result.id = "msg-2".to_string();
        session.messages.push(tool_result);

        detect_manual_compression_request(&mut session);
        assert!(session.force_manual_compression.is_none());
    }

    #[test]
    fn detect_manual_compression_request_finds_call_among_parallel_tool_calls() {
        use super::detect_manual_compression_request;
        use bamboo_agent_core::tools::FunctionCall;
        use bamboo_agent_core::tools::ToolCall;
        use bamboo_agent_core::{Message, Session};

        let mut session = Session::new("s6", "m6");

        // Multiple tool calls in one assistant turn, including compact_context
        let mut assistant = Message::assistant("", None);
        assistant.id = "msg-1".to_string();
        assistant.tool_calls = Some(vec![
            ToolCall {
                id: "call-read".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: "Read".to_string(),
                    arguments: r#"{"file_path":"/tmp/a"}"#.to_string(),
                },
            },
            ToolCall {
                id: "call-compact".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: "compact_context".to_string(),
                    arguments: r#"{"instructions":"preserve error traces"}"#.to_string(),
                },
            },
        ]);
        session.messages.push(assistant);

        let mut read_result = Message::tool_result("call-read", "file a");
        read_result.id = "msg-2".to_string();
        session.messages.push(read_result);

        let mut compact_result = Message::tool_result("call-compact", "ok");
        compact_result.id = "msg-3".to_string();
        session.messages.push(compact_result);

        detect_manual_compression_request(&mut session);
        assert_eq!(
            session.force_manual_compression.as_deref(),
            Some("preserve error traces")
        );
    }
}