bamboo-engine 2026.9.19

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
//! Respond use case: submit a user response to a pending question.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};

use bamboo_agent_core::{Message, PendingQuestion, Session};
use bamboo_domain::session::runtime_state::{AgentRuntimeState, PlanModeState, PlanModeStatus};
use bamboo_domain::{
    latest_response_occurrence, ResponseOccurrence, SessionPermissionMode,
    CONSUMED_CLARIFICATION_IDS_KEY, CONSUMED_RESPONSE_OCCURRENCES_KEY,
};
use bamboo_tools::permission::{PermissionDecisionKind, PermissionDecisionReceipt, PermissionType};
use chrono::Utc;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use tokio::sync::{Mutex, OwnedMutexGuard};

use super::errors::RespondError;
use super::execute::mark_startup_handoff;
use super::provider_model::{derive_model_ref, persist_legacy_model_provider, persist_model_ref};
use super::repository::SessionAccess;
use super::types::RespondInput;

const CLARIFICATION_RESUME_PENDING_KEY: &str = "clarification_resume_pending";
const CONCLUSION_WITH_OPTIONS_RESUME_PENDING_KEY: &str = "conclusion_with_options_resume_pending";

type AppliedPendingResponse = (
    String,
    Option<PlanModeTransition>,
    Vec<(PermissionType, String)>,
);

/// Process-local serialization for consuming one pending question. The
/// persistence layer serializes individual loads and saves, but releasing its
/// lock between those operations would let two responders both observe and
/// consume the same question. Every response entrypoint reaches this use case,
/// so holding this gate across load -> validate -> save makes one consumer win
/// and forces later callers to reload the already-consumed state.
struct PendingResponseGate {
    lock: Arc<Mutex<()>>,
    waiters: AtomicUsize,
}

impl PendingResponseGate {
    fn new() -> Self {
        Self {
            lock: Arc::new(Mutex::new(())),
            waiters: AtomicUsize::new(0),
        }
    }
}

struct PendingResponseWaiter(Arc<PendingResponseGate>);

impl Drop for PendingResponseWaiter {
    fn drop(&mut self) {
        self.0.waiters.fetch_sub(1, Ordering::SeqCst);
    }
}

fn pending_response_locks() -> &'static DashMap<String, Weak<PendingResponseGate>> {
    static LOCKS: OnceLock<DashMap<String, Weak<PendingResponseGate>>> = OnceLock::new();
    LOCKS.get_or_init(DashMap::new)
}

fn pending_response_lock(session_id: &str) -> Arc<PendingResponseGate> {
    let locks = pending_response_locks();
    locks.retain(|_, lock| lock.strong_count() > 0);
    match locks.entry(session_id.to_string()) {
        Entry::Occupied(mut entry) => {
            if let Some(lock) = entry.get().upgrade() {
                lock
            } else {
                let lock = Arc::new(PendingResponseGate::new());
                entry.insert(Arc::downgrade(&lock));
                lock
            }
        }
        Entry::Vacant(entry) => {
            let lock = Arc::new(PendingResponseGate::new());
            entry.insert(Arc::downgrade(&lock));
            lock
        }
    }
}

/// Process-local ownership for one session's complete response transaction.
/// High-level HTTP, Connect, and Gold paths hold this from authoritative
/// preflight through successor dispatch, so a stale duplicate cannot reserve
/// and later cancel a phantom runner after the real successor has completed.
pub struct PendingResponseGuard {
    session_id: String,
    _gate: Arc<PendingResponseGate>,
    _guard: OwnedMutexGuard<()>,
}

impl PendingResponseGuard {
    fn ensure_session(&self, session_id: &str) -> Result<(), RespondError> {
        if self.session_id == session_id {
            Ok(())
        } else {
            Err(RespondError::InvalidResponse(
                "response transaction guard belongs to a different session".to_string(),
            ))
        }
    }
}

/// Acquire the shared response single-flight used by every response source.
pub async fn acquire_pending_response_guard(session_id: &str) -> PendingResponseGuard {
    let gate = pending_response_lock(session_id);
    gate.waiters.fetch_add(1, Ordering::SeqCst);
    let waiter = PendingResponseWaiter(gate.clone());
    let guard = gate.lock.clone().lock_owned().await;
    drop(waiter);
    PendingResponseGuard {
        session_id: session_id.to_string(),
        _gate: gate,
        _guard: guard,
    }
}

/// Number of callers currently waiting to enter a session's response gate.
/// Exposed for deterministic concurrency tests and lightweight diagnostics.
#[doc(hidden)]
pub fn pending_response_waiter_count(session_id: &str) -> usize {
    pending_response_locks()
        .get(session_id)
        .and_then(|entry| entry.upgrade())
        .map(|gate| gate.waiters.load(Ordering::SeqCst))
        .unwrap_or(0)
}

/// Reload the exact snapshot a response CAS would mutate while holding the
/// shared response single-flight. This must happen before successor
/// reservation so an already-consumed/stale response allocates no runner.
pub async fn inspect_pending_response_guarded(
    repo: &dyn SessionAccess,
    session_id: &str,
    guard: &PendingResponseGuard,
) -> Result<Option<Session>, RespondError> {
    guard.ensure_session(session_id)?;
    Ok(repo.inspect_for_response(session_id).await?)
}

/// Session-metadata key marking a tool call that was approved through a permission
/// prompt and must be RE-EXECUTED on resume. The gated tool never actually ran
/// (the permission gate intercepted it before execution), so on approval the
/// server resume adapter re-runs it and writes the real output back — instead of
/// leaving the model to infer/fabricate it. Value = the tool_call_id.
pub const PERMISSION_REEXECUTE_METADATA_KEY: &str = "permission.reexecute_tool_call_id";
pub const PERMISSION_REEXECUTE_GENERATION_METADATA_KEY: &str =
    "permission.reexecute_request_generation";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseSource {
    Human,
    Gold,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanModeTransition {
    Entered {
        reason: Option<String>,
        pre_permission_mode: String,
        entered_at: chrono::DateTime<chrono::Utc>,
        status: PlanModeStatus,
        plan_file_path: Option<String>,
    },
    Exited {
        approved: bool,
        restored_mode: String,
        plan: Option<String>,
    },
}

/// Submit a pending response: load session, validate, update messages,
/// apply plan mode transitions, persist, and return the updated session.
///
/// The caller (handler) is responsible for auto-resume triggering.
pub async fn submit_pending_response(
    repo: &dyn SessionAccess,
    input: RespondInput,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_checked(repo, input, None).await
}

/// Submit a response guarded by the exact pending tool-call identity displayed
/// to a typed client. The separate parameter keeps the established public
/// [`RespondInput`] struct source-compatible for SDK/in-process callers.
pub async fn submit_pending_response_checked(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_with_source_checked(
        repo,
        input,
        expected_tool_call_id,
        ResponseSource::Human,
    )
    .await
}

/// Human-response variant for callers that already hold the shared response
/// transaction guard across preflight, reservation, CAS, and dispatch.
pub async fn submit_pending_response_checked_guarded(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
    guard: &PendingResponseGuard,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_with_source_checked_guarded(
        repo,
        input,
        expected_tool_call_id,
        ResponseSource::Human,
        guard,
    )
    .await
}

/// Typed-permission variant that persists the exact decision receipt in the
/// same durable session mutation that consumes the pending question.
pub async fn submit_pending_permission_response_checked_guarded(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
    permission_receipt: PermissionDecisionReceipt,
    guard: &PendingResponseGuard,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_with_source_checked_guarded_inner(
        repo,
        input,
        expected_tool_call_id,
        ResponseSource::Human,
        Some(permission_receipt),
        guard,
    )
    .await
}

pub async fn submit_pending_response_with_source(
    repo: &dyn SessionAccess,
    input: RespondInput,
    response_source: ResponseSource,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_with_source_checked(repo, input, None, response_source).await
}

pub async fn submit_pending_response_with_source_checked(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
    response_source: ResponseSource,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    let guard = acquire_pending_response_guard(&input.session_id).await;
    submit_pending_response_with_source_checked_guarded(
        repo,
        input,
        expected_tool_call_id,
        response_source,
        &guard,
    )
    .await
}

/// Guarded form for high-level response + resume transactions. The caller
/// must retain `guard` until the exact successor reservation has been handed
/// to its detached execution owner.
pub async fn submit_pending_response_with_source_checked_guarded(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
    response_source: ResponseSource,
    guard: &PendingResponseGuard,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    submit_pending_response_with_source_checked_guarded_inner(
        repo,
        input,
        expected_tool_call_id,
        response_source,
        None,
        guard,
    )
    .await
}

async fn submit_pending_response_with_source_checked_guarded_inner(
    repo: &dyn SessionAccess,
    input: RespondInput,
    expected_tool_call_id: Option<String>,
    response_source: ResponseSource,
    permission_receipt: Option<PermissionDecisionReceipt>,
    guard: &PendingResponseGuard,
) -> Result<
    (
        Session,
        String,
        Option<PlanModeTransition>,
        Vec<(PermissionType, String)>,
    ),
    RespondError,
> {
    guard.ensure_session(&input.session_id)?;

    let applied = Arc::new(StdMutex::new(None));
    let mutation_outcome = applied.clone();
    let mutation_input = input.clone();
    let mutation_expected_tool_call_id = expected_tool_call_id.clone();
    let mutation_permission_receipt = permission_receipt.clone();
    let session = repo
        .mutate_for_response(
            &input.session_id,
            Box::new(move |session| {
                let outcome = apply_pending_response(
                    session,
                    &mutation_input,
                    mutation_expected_tool_call_id.as_deref(),
                    response_source,
                    mutation_permission_receipt.as_ref(),
                )?;
                *mutation_outcome
                    .lock()
                    .expect("response outcome lock poisoned") = Some(outcome);
                Ok(())
            }),
        )
        .await?
        .ok_or_else(|| RespondError::NotFound(input.session_id.clone()))?;
    let (user_response, plan_mode_transition, permission_grants) = applied
        .lock()
        .expect("response outcome lock poisoned")
        .take()
        .expect("successful response mutation records its outcome");

    tracing::info!(
        "[{}] Response processed successfully, agent loop can resume",
        input.session_id
    );

    Ok((
        session,
        user_response,
        plan_mode_transition,
        permission_grants,
    ))
}

fn apply_pending_response(
    session: &mut Session,
    input: &RespondInput,
    expected_tool_call_id: Option<&str>,
    response_source: ResponseSource,
    permission_receipt: Option<&PermissionDecisionReceipt>,
) -> Result<AppliedPendingResponse, RespondError> {
    let pending = session
        .pending_question
        .take()
        .ok_or(RespondError::NoPendingQuestion)?;

    if session
        .messages
        .iter()
        .rev()
        .find(|message| message.tool_call_id.as_deref() == Some(pending.tool_call_id.as_str()))
        .is_some_and(result_payload_has_supervisor_authority)
    {
        session.pending_question = Some(pending);
        return Err(RespondError::InvalidResponse(
            "Supervisor authority cannot originate in a tool result payload".into(),
        ));
    }

    if let Some(expected) = expected_tool_call_id {
        if pending.tool_call_id != expected {
            let actual = pending.tool_call_id.clone();
            session.pending_question = Some(pending);
            return Err(RespondError::PendingQuestionMismatch {
                expected: expected.to_string(),
                actual,
            });
        }
    }

    if let Some(receipt) = permission_receipt {
        if receipt.session_id != input.session_id
            || receipt.decision.request_id != pending.tool_call_id
        {
            session.pending_question = Some(pending);
            return Err(RespondError::InvalidResponse(
                "permission receipt identity does not match the pending question".to_string(),
            ));
        }
        let current_generation = session
            .messages
            .iter()
            .rev()
            .find(|message| message.tool_call_id.as_deref() == Some(pending.tool_call_id.as_str()))
            .and_then(permission_request_generation);
        if current_generation.as_deref() != Some(receipt.decision.request_generation.as_str()) {
            session.pending_question = Some(pending);
            return Err(RespondError::InvalidResponse(
                "permission receipt generation does not match the pending operation".to_string(),
            ));
        }
    }

    // Typed permission control flow comes exclusively from the structured
    // receipt. Display strings and localized options remain transcript-only.
    // Legacy clarifications still validate their selected display option.
    if permission_receipt.is_none() {
        if let Err(error_message) = validate_pending_response(&pending, &input.user_response) {
            // Put the pending question back when validation fails.
            session.pending_question = Some(pending);
            return Err(RespondError::InvalidResponse(error_message));
        }
    }

    let tool_call_id = pending.tool_call_id.clone();
    tracing::debug!(
        "[{}] Looking for tool result message with tool_call_id: {}",
        input.session_id,
        tool_call_id
    );

    let reviewed_plan = extract_exit_plan_from_tool_result_message(session, &tool_call_id);

    // Permission grants implied by approving a permission prompt. Read from the
    // (still-unmodified) synthesized tool-result payload, BEFORE it is overwritten
    // by the user's selection below.
    let typed_permission_approved = permission_receipt.is_some_and(|receipt| {
        matches!(
            receipt.decision.decision,
            PermissionDecisionKind::AllowOnce
                | PermissionDecisionKind::AllowSession
                | PermissionDecisionKind::AllowWorkspace
                | PermissionDecisionKind::AllowGlobal
        )
    });
    let permission_approved = permission_receipt
        .map(|_| typed_permission_approved)
        .unwrap_or_else(|| is_permission_approval(&input.user_response));
    let permission_grants = if permission_approved {
        extract_permission_grants_from_tool_result_message(session, &tool_call_id)
    } else {
        Vec::new()
    };
    let should_reexecute = permission_receipt
        .map(|_| typed_permission_approved)
        .unwrap_or(!permission_grants.is_empty());
    if should_reexecute {
        // Approved a permission prompt: mark the gated tool call for re-execution
        // on resume so the operation actually runs (real output) rather than the
        // model inferring it. Consumed by the server resume adapter.
        session.metadata.insert(
            PERMISSION_REEXECUTE_METADATA_KEY.to_string(),
            tool_call_id.clone(),
        );
        if let Some(receipt) = permission_receipt {
            session.metadata.insert(
                PERMISSION_REEXECUTE_GENERATION_METADATA_KEY.to_string(),
                receipt.decision.request_generation.clone(),
            );
        } else {
            session
                .metadata
                .remove(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY);
        }
    } else if permission_receipt.is_some() {
        // A typed deny cannot inherit replay markers from an older occurrence.
        session.metadata.remove(PERMISSION_REEXECUTE_METADATA_KEY);
        session
            .metadata
            .remove(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY);
    }

    // ---- Update or append tool result message ----
    let found = update_or_append_tool_result_message(
        session,
        &tool_call_id,
        &input.user_response,
        response_source,
    );
    if let Some(receipt) = permission_receipt {
        if !persist_permission_decision_receipt(session, &tool_call_id, receipt) {
            return Err(RespondError::InvalidResponse(
                "permission receipt could not be persisted for the pending operation".to_string(),
            ));
        }
    }
    if found {
        tracing::info!(
            "[{}] Updated existing tool result message",
            input.session_id
        );
    } else {
        tracing::warn!(
            "[{}] Tool result message not found for tool_call_id: {}, added fallback message",
            input.session_id,
            tool_call_id
        );
    }

    // ---- Plan mode state transitions ----
    let plan_mode_transition =
        apply_plan_mode_transition(session, &pending, &input.user_response, reviewed_plan);

    // ---- Clear pending question and set resume marker ----
    session.clear_pending_question();
    record_consumed_clarification(session, &tool_call_id);
    session.metadata.remove("runtime.suspend_reason");
    session.metadata.insert(
        CLARIFICATION_RESUME_PENDING_KEY.to_string(),
        "true".to_string(),
    );
    session.metadata.insert(
        CONCLUSION_WITH_OPTIONS_RESUME_PENDING_KEY.to_string(),
        "true".to_string(),
    );
    mark_startup_handoff(session);

    // ---- Merge model/reasoning from request ----
    let request_model_ref = derive_model_ref(
        input.model_ref.as_ref(),
        input.provider.as_deref(),
        input.model.as_deref(),
    );
    if let Some(model_ref) = request_model_ref.as_ref() {
        persist_model_ref(session, model_ref);
    } else {
        persist_legacy_model_provider(session, input.model.as_deref(), input.provider.as_deref());
    }
    if let Some(reasoning_effort) = input.reasoning_effort {
        session.reasoning_effort = Some(reasoning_effort);
    }

    Ok((
        input.user_response.clone(),
        plan_mode_transition,
        permission_grants,
    ))
}

fn record_consumed_clarification(session: &mut Session, tool_call_id: &str) {
    let mut legacy_consumed = session
        .metadata
        .get(CONSUMED_CLARIFICATION_IDS_KEY)
        .and_then(|value| serde_json::from_str::<Vec<String>>(value).ok())
        .unwrap_or_default();
    legacy_consumed.retain(|existing| existing != tool_call_id);
    legacy_consumed.push(tool_call_id.to_string());
    if legacy_consumed.len() > 64 {
        legacy_consumed.drain(..legacy_consumed.len() - 64);
    }
    if let Ok(serialized) = serde_json::to_string(&legacy_consumed) {
        session
            .metadata
            .insert(CONSUMED_CLARIFICATION_IDS_KEY.to_string(), serialized);
    }

    let Some(occurrence) = latest_response_occurrence(session, tool_call_id) else {
        return;
    };
    let mut consumed = session
        .metadata
        .get(CONSUMED_RESPONSE_OCCURRENCES_KEY)
        .and_then(|value| serde_json::from_str::<Vec<ResponseOccurrence>>(value).ok())
        .unwrap_or_default();
    consumed.retain(|existing| existing != &occurrence);
    consumed.push(occurrence);
    if consumed.len() > 64 {
        consumed.drain(..consumed.len() - 64);
    }
    if let Ok(serialized) = serde_json::to_string(&consumed) {
        session
            .metadata
            .insert(CONSUMED_RESPONSE_OCCURRENCES_KEY.to_string(), serialized);
    }
}

/// Apply plan mode state transitions based on the pending question tool and user response.
fn apply_plan_mode_transition(
    session: &mut Session,
    pending: &PendingQuestion,
    user_response: &str,
    reviewed_plan: Option<String>,
) -> Option<PlanModeTransition> {
    match pending.tool_name.as_str() {
        "EnterPlanMode" if user_response.to_lowercase().contains("enter plan mode") => {
            let pre_mode = session
                .agent_runtime_state
                .as_ref()
                .map(|state| state.effective_permission_mode().as_str().to_string())
                .unwrap_or_else(|| SessionPermissionMode::Default.as_str().to_string());

            let entered_at = Utc::now();
            let status = PlanModeStatus::Exploring;
            let runtime_state = session
                .agent_runtime_state
                .get_or_insert_with(|| AgentRuntimeState::new(uuid::Uuid::new_v4().to_string()));
            runtime_state.plan_mode = Some(PlanModeState {
                entered_at,
                pre_permission_mode: pre_mode.clone(),
                plan_file_path: None,
                status,
            });
            tracing::info!(
                session_id = %session.id,
                "Entered plan mode"
            );
            Some(PlanModeTransition::Entered {
                reason: Some(pending.question.clone()),
                pre_permission_mode: pre_mode,
                entered_at,
                status,
                plan_file_path: None,
            })
        }
        "ExitPlanMode" if is_exit_plan_mode_approved(user_response) => {
            let restored_mode = session
                .agent_runtime_state
                .as_ref()
                .map(|state| state.effective_permission_mode().as_str().to_string())
                .unwrap_or_else(|| "default".to_string());
            if let Some(ref mut runtime_state) = session.agent_runtime_state {
                // The typed requested mode remains live while Plan is active and
                // may have been changed by a newer PATCH. Exiting Plan clears
                // only the overlay; the old pre-mode is event history, never a
                // write authority that may roll back the newer request.
                runtime_state.plan_mode = None;
            }
            tracing::info!(
                session_id = %session.id,
                "Exited plan mode"
            );
            Some(PlanModeTransition::Exited {
                approved: true,
                restored_mode,
                plan: reviewed_plan,
            })
        }
        _ => None,
    }
}

/// Check if the user response approves exiting plan mode.
fn is_exit_plan_mode_approved(user_response: &str) -> bool {
    let lower = user_response.to_lowercase();
    lower.contains("approve") && !lower.contains("stay in plan mode")
}

// ---- Internal helpers ----

pub fn validate_pending_response(
    pending: &PendingQuestion,
    user_response: &str,
) -> Result<(), String> {
    if pending.allow_custom {
        return Ok(());
    }

    let valid = pending.options.iter().any(|option| option == user_response);
    if valid {
        Ok(())
    } else {
        let options_str = pending.options.join(", ");
        Err(format!("Response must be one of: {options_str}"))
    }
}

pub fn update_or_append_tool_result_message(
    session: &mut Session,
    tool_call_id: &str,
    user_response: &str,
    response_source: ResponseSource,
) -> bool {
    for message in session.messages.iter_mut().rev() {
        if message.tool_call_id.as_deref() == Some(tool_call_id) {
            // Retain invalid input for fail-closed inspection; replacing the
            // payload must not disguise forged authority as absent legacy data.
            if result_payload_has_supervisor_authority(message) {
                return false;
            }
            // Preserve the server-issued typed permission contract outside the
            // model-visible content before replacing the synthetic waiting
            // payload with the selected answer. This lets an exact durable
            // decision receipt be reconstructed after a daemon restart without
            // trusting display strings or replaying an already-consumed run.
            if let Ok(payload) = serde_json::from_str::<serde_json::Value>(&message.content) {
                if payload.get("status").and_then(serde_json::Value::as_str)
                    == Some("awaiting_permission_approval")
                {
                    if let Some(request) = payload.get("permission_request") {
                        insert_message_metadata(message, "permission_request", request.clone());
                    }
                }
            }
            message.content = selected_message_content(user_response, response_source);
            message.tool_success = Some(true);
            return true;
        }
    }

    session.add_message(bamboo_agent_core::Message::tool_result_with_status(
        tool_call_id,
        selected_message_content(user_response, response_source),
        true,
    ));
    false
}

fn result_payload_has_supervisor_authority(message: &Message) -> bool {
    serde_json::from_str::<serde_json::Value>(&message.content).ok().is_some_and(|payload| {
        payload.get(bamboo_agent_core::tools::ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY).is_some()
    })
}

fn insert_message_metadata(message: &mut Message, key: &str, value: serde_json::Value) {
    let metadata = message
        .metadata
        .get_or_insert_with(|| serde_json::Value::Object(Default::default()));
    if !metadata.is_object() {
        let previous = std::mem::replace(metadata, serde_json::Value::Object(Default::default()));
        metadata
            .as_object_mut()
            .expect("replacement metadata is an object")
            .insert("previous_metadata".to_string(), previous);
    }
    metadata
        .as_object_mut()
        .expect("message metadata is an object")
        .insert(key.to_string(), value);
}

fn permission_request_generation(message: &Message) -> Option<String> {
    message
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("permission_request"))
        .and_then(|request| request.get("request_generation"))
        .and_then(serde_json::Value::as_str)
        .map(ToOwned::to_owned)
        .or_else(|| {
            serde_json::from_str::<serde_json::Value>(&message.content)
                .ok()?
                .get("permission_request")?
                .get("request_generation")?
                .as_str()
                .map(ToOwned::to_owned)
        })
}

fn persist_permission_decision_receipt(
    session: &mut Session,
    tool_call_id: &str,
    receipt: &PermissionDecisionReceipt,
) -> bool {
    let Some(message) = session
        .messages
        .iter_mut()
        .rev()
        .find(|message| message.tool_call_id.as_deref() == Some(tool_call_id))
    else {
        return false;
    };
    if permission_request_generation(message).as_deref()
        != Some(receipt.decision.request_generation.as_str())
    {
        return false;
    }
    insert_message_metadata(
        message,
        "permission_decision_receipt",
        serde_json::to_value(receipt).expect("permission receipt is serializable"),
    );
    true
}

fn selected_message_content(user_response: &str, response_source: ResponseSource) -> String {
    match response_source {
        ResponseSource::Human => format!("Selected response: {}", user_response),
        ResponseSource::Gold => format!("Auto-selected response (gold): {}", user_response),
    }
}

fn extract_exit_plan_from_tool_result_message(
    session: &Session,
    tool_call_id: &str,
) -> Option<String> {
    let message = session
        .messages
        .iter()
        .rev()
        .find(|message| message.tool_call_id.as_deref() == Some(tool_call_id))?;
    let payload = serde_json::from_str::<serde_json::Value>(&message.content).ok()?;
    payload
        .get("plan")
        .and_then(|value| value.as_str())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
}

/// Detect whether the user response approves a pending permission request.
///
/// Permission prompts (synthesized by the permission gate, and the
/// `request_permissions` tool) offer exactly `["Approve", "Deny"]`.
fn is_permission_approval(user_response: &str) -> bool {
    user_response.trim().eq_ignore_ascii_case("approve")
}

/// Extract the permission grants implied by an approved permission prompt.
///
/// Reads the pending tool-result message (still the synthesized
/// `awaiting_permission_approval` payload, before it is overwritten by the
/// user's selection) and returns the `(PermissionType, resource)` pairs the
/// caller should grant for the session. Handles both the single-gated-tool shape
/// (top-level `permission_type` + `resource`) and the `request_permissions` shape
/// (a `permissions` array).
fn extract_permission_grants_from_tool_result_message(
    session: &Session,
    tool_call_id: &str,
) -> Vec<(PermissionType, String)> {
    let message = match session
        .messages
        .iter()
        .rev()
        .find(|message| message.tool_call_id.as_deref() == Some(tool_call_id))
    {
        Some(message) => message,
        None => return Vec::new(),
    };
    let payload = match serde_json::from_str::<serde_json::Value>(&message.content) {
        Ok(payload) => payload,
        Err(_) => return Vec::new(),
    };
    if payload.get("status").and_then(|value| value.as_str())
        != Some("awaiting_permission_approval")
    {
        return Vec::new();
    }

    let parse_one = |value: &serde_json::Value| -> Option<(PermissionType, String)> {
        let type_value = value
            .get("permission_type")
            .or_else(|| value.get("type"))?
            .clone();
        let perm_type: PermissionType = serde_json::from_value(type_value).ok()?;
        let resource = value.get("resource")?.as_str()?.trim().to_string();
        if resource.is_empty() {
            return None;
        }
        Some((perm_type, resource))
    };

    if let Some(array) = payload
        .get("permissions")
        .and_then(|value| value.as_array())
    {
        array.iter().filter_map(parse_one).collect()
    } else {
        parse_one(&payload).into_iter().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::Mutex;
    use tokio::sync::Notify;

    struct TestSessionAccess {
        session: Mutex<Session>,
        loads: AtomicUsize,
        saves: AtomicUsize,
        block_first_save: AtomicBool,
        save_started: Notify,
        release_save: Notify,
    }

    impl TestSessionAccess {
        fn with_pending() -> Self {
            Self::with_pending_and_blocked_save(false)
        }

        fn with_pending_and_blocked_save(block_first_save: bool) -> Self {
            let mut session = Session::new("sess-1", "test-model");
            session.pending_question = Some(make_pending("ConclusionWithOptions"));
            Self {
                session: Mutex::new(session),
                loads: AtomicUsize::new(0),
                saves: AtomicUsize::new(0),
                block_first_save: AtomicBool::new(block_first_save),
                save_started: Notify::new(),
                release_save: Notify::new(),
            }
        }
    }

    #[async_trait::async_trait]
    impl SessionAccess for TestSessionAccess {
        async fn load_session(
            &self,
            _id: &str,
        ) -> Result<Option<Session>, super::super::errors::SessionLoadError> {
            Ok(Some(self.session.lock().unwrap().clone()))
        }

        async fn load_or_create(
            &self,
            _id: &str,
            _model: &str,
        ) -> Result<Session, super::super::errors::SessionLoadError> {
            Ok(self.session.lock().unwrap().clone())
        }

        async fn load_merged(
            &self,
            _id: &str,
        ) -> Result<Option<Session>, super::super::errors::SessionLoadError> {
            self.loads.fetch_add(1, Ordering::SeqCst);
            Ok(Some(self.session.lock().unwrap().clone()))
        }

        async fn save_session(
            &self,
            session: &mut Session,
        ) -> Result<(), super::super::errors::SessionSaveError> {
            if self.block_first_save.swap(false, Ordering::SeqCst) {
                self.save_started.notify_one();
                self.release_save.notified().await;
            }
            *self.session.lock().unwrap() = session.clone();
            self.saves.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

        async fn save_and_cache(
            &self,
            session: &mut Session,
        ) -> Result<(), super::super::errors::SessionSaveError> {
            self.save_session(session).await
        }
    }

    fn respond_input() -> RespondInput {
        RespondInput {
            session_id: "sess-1".to_string(),
            user_response: "A".to_string(),
            model: None,
            model_ref: None,
            provider: None,
            reasoning_effort: None,
        }
    }

    fn make_pending(tool_name: &str) -> PendingQuestion {
        PendingQuestion {
            tool_call_id: "call-1".to_string(),
            tool_name: tool_name.to_string(),
            question: "Question?".to_string(),
            options: vec!["A".to_string(), "B".to_string()],
            allow_custom: false,
            source: bamboo_agent_core::PendingQuestionSource::PauseTool,
        }
    }

    #[tokio::test]
    async fn expected_tool_call_id_accepts_the_current_question() {
        let repo = TestSessionAccess::with_pending();

        submit_pending_response_checked(&repo, respond_input(), Some("call-1".to_string()))
            .await
            .expect("matching identity should submit");

        assert_eq!(repo.saves.load(Ordering::SeqCst), 1);
        assert!(repo.session.lock().unwrap().pending_question.is_none());
    }

    #[tokio::test]
    async fn stale_tool_call_id_is_rejected_without_consuming_the_question() {
        let repo = TestSessionAccess::with_pending();

        let error =
            submit_pending_response_checked(&repo, respond_input(), Some("stale-call".to_string()))
                .await
                .expect_err("stale identity must fail");

        assert!(matches!(
            error,
            RespondError::PendingQuestionMismatch {
                ref expected,
                ref actual,
            } if expected == "stale-call" && actual == "call-1"
        ));
        assert_eq!(repo.saves.load(Ordering::SeqCst), 0);
        assert_eq!(
            repo.session
                .lock()
                .unwrap()
                .pending_question
                .as_ref()
                .map(|question| question.tool_call_id.as_str()),
            Some("call-1")
        );
    }

    #[tokio::test]
    async fn omitted_tool_call_guard_remains_backwards_compatible() {
        let repo = TestSessionAccess::with_pending();

        submit_pending_response(&repo, respond_input())
            .await
            .expect("legacy client should remain accepted");

        assert_eq!(repo.saves.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn concurrent_responses_consume_a_pending_question_once() {
        let repo = Arc::new(TestSessionAccess::with_pending_and_blocked_save(true));

        let first_repo = repo.clone();
        let first = tokio::spawn(async move {
            submit_pending_response_checked(
                first_repo.as_ref(),
                respond_input(),
                Some("call-1".to_string()),
            )
            .await
        });
        repo.save_started.notified().await;

        let second_entered = Arc::new(Notify::new());
        let second_repo = repo.clone();
        let second_entered_task = second_entered.clone();
        let second = tokio::spawn(async move {
            second_entered_task.notify_one();
            submit_pending_response_checked(
                second_repo.as_ref(),
                respond_input(),
                Some("call-1".to_string()),
            )
            .await
        });
        second_entered.notified().await;
        tokio::task::yield_now().await;

        assert_eq!(
            repo.loads.load(Ordering::SeqCst),
            1,
            "the second responder must wait before loading the pending question"
        );
        repo.release_save.notify_one();

        first.await.unwrap().expect("first response should win");
        let error = second
            .await
            .unwrap()
            .expect_err("second response must observe the consumed question");
        assert!(matches!(error, RespondError::NoPendingQuestion));
        assert_eq!(repo.loads.load(Ordering::SeqCst), 2);
        assert_eq!(repo.saves.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn cancelled_response_waiter_does_not_leak_diagnostics_or_the_gate() {
        let session_id = "cancelled-response-waiter";
        let owner = acquire_pending_response_guard(session_id).await;
        let waiter = tokio::spawn(async move { acquire_pending_response_guard(session_id).await });
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while pending_response_waiter_count(session_id) != 1 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("waiter should reach the gate");

        waiter.abort();
        let _ = waiter.await;
        assert_eq!(pending_response_waiter_count(session_id), 0);
        drop(owner);

        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            acquire_pending_response_guard(session_id),
        )
        .await
        .expect("cancelled waiter must not retain the gate");
    }

    #[test]
    fn enter_plan_mode_activates_plan_mode_state() {
        let mut session = Session::new("sess-1", "test-model");
        let pending = make_pending("EnterPlanMode");

        apply_plan_mode_transition(&mut session, &pending, "Enter plan mode", None);

        assert!(session.agent_runtime_state.is_some());
        let state = session.agent_runtime_state.unwrap();
        assert!(state.plan_mode.is_some());
        let plan = state.plan_mode.unwrap();
        assert_eq!(plan.status, PlanModeStatus::Exploring);
        assert_eq!(plan.pre_permission_mode, "default");
    }

    #[test]
    fn enter_plan_mode_does_nothing_when_not_approved() {
        let mut session = Session::new("sess-1", "test-model");
        let pending = make_pending("EnterPlanMode");

        apply_plan_mode_transition(&mut session, &pending, "Stay in normal mode", None);

        assert!(session.agent_runtime_state.is_none());
    }

    #[test]
    fn plan_mode_preserves_and_restores_typed_auto_request() {
        let mut session = Session::new("sess-auto-plan", "test-model");
        session
            .agent_runtime_state
            .get_or_insert_with(|| AgentRuntimeState::new("run-1"))
            .set_permission_mode(SessionPermissionMode::Auto);
        let enter = make_pending("EnterPlanMode");
        let transition =
            apply_plan_mode_transition(&mut session, &enter, "Enter plan mode", None).unwrap();
        assert!(matches!(
            transition,
            PlanModeTransition::Entered {
                ref pre_permission_mode,
                ..
            } if pre_permission_mode == "auto"
        ));
        assert_eq!(
            session
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .plan_mode
                .as_ref()
                .unwrap()
                .pre_permission_mode,
            "auto"
        );

        let exit = make_pending("ExitPlanMode");
        let transition = apply_plan_mode_transition(
            &mut session,
            &exit,
            "Approve (Auto mode)",
            Some("Reviewed plan".to_string()),
        )
        .unwrap();
        assert!(matches!(
            transition,
            PlanModeTransition::Exited {
                ref restored_mode,
                ..
            } if restored_mode == "auto"
        ));
        assert_eq!(
            session
                .agent_runtime_state
                .as_ref()
                .unwrap()
                .effective_permission_mode(),
            SessionPermissionMode::Auto
        );
    }

    #[test]
    fn exit_plan_mode_does_not_restore_over_a_newer_typed_mode() {
        let mut session = Session::new("sess-plan-patch", "test-model");
        let state = session
            .agent_runtime_state
            .get_or_insert_with(|| AgentRuntimeState::new("run-1"));
        state.set_permission_mode(SessionPermissionMode::Auto);
        state.plan_mode = Some(PlanModeState {
            entered_at: Utc::now(),
            pre_permission_mode: "auto".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::AwaitingApproval,
        });
        // Simulate a newer PATCH while the Plan overlay is still active.
        state.set_permission_mode(SessionPermissionMode::Bypass);

        let transition = apply_plan_mode_transition(
            &mut session,
            &make_pending("ExitPlanMode"),
            "Approve (Default mode)",
            None,
        )
        .unwrap();

        assert!(matches!(
            transition,
            PlanModeTransition::Exited {
                ref restored_mode,
                ..
            } if restored_mode == "bypass"
        ));
        let state = session.agent_runtime_state.unwrap();
        assert!(state.plan_mode.is_none());
        assert_eq!(
            state.effective_permission_mode(),
            SessionPermissionMode::Bypass
        );
    }

    #[test]
    fn exit_plan_mode_clears_plan_mode_state() {
        let mut session = Session::new("sess-1", "test-model");
        session.agent_runtime_state = Some(AgentRuntimeState::new("run-1"));
        session.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
            entered_at: Utc::now(),
            pre_permission_mode: "default".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::AwaitingApproval,
        });
        let pending = make_pending("ExitPlanMode");

        apply_plan_mode_transition(
            &mut session,
            &pending,
            "Approve (Default mode)",
            Some("Reviewed plan".to_string()),
        );

        assert!(session.agent_runtime_state.unwrap().plan_mode.is_none());
    }

    #[test]
    fn exit_plan_mode_keeps_plan_mode_when_not_approved() {
        let mut session = Session::new("sess-1", "test-model");
        session.agent_runtime_state = Some(AgentRuntimeState::new("run-1"));
        session.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
            entered_at: Utc::now(),
            pre_permission_mode: "default".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::AwaitingApproval,
        });
        let pending = make_pending("ExitPlanMode");

        apply_plan_mode_transition(&mut session, &pending, "Stay in plan mode", None);

        assert!(session.agent_runtime_state.unwrap().plan_mode.is_some());
    }

    #[test]
    fn exit_plan_mode_ignores_other_tools() {
        let mut session = Session::new("sess-1", "test-model");
        let pending = make_pending("ConclusionWithOptions");

        apply_plan_mode_transition(&mut session, &pending, "Approve", None);

        assert!(session.agent_runtime_state.is_none());
    }

    #[test]
    fn is_exit_plan_mode_approved_detects_approval() {
        assert!(is_exit_plan_mode_approved("Approve (Default mode)"));
        assert!(is_exit_plan_mode_approved("Approve (Accept edits mode)"));
        assert!(!is_exit_plan_mode_approved("Stay in plan mode"));
        assert!(!is_exit_plan_mode_approved("Edit plan first"));
    }

    #[test]
    fn extract_exit_plan_from_tool_result_message_reads_plan_payload() {
        let mut session = Session::new("sess-1", "test-model");
        let mut tool_message = bamboo_agent_core::Message::tool_result(
            "call-1",
            serde_json::json!({
                "plan": "# Plan\n\n1. Step"
            })
            .to_string(),
        );
        tool_message.tool_success = Some(true);
        session.add_message(tool_message);

        let plan = extract_exit_plan_from_tool_result_message(&session, "call-1");
        assert_eq!(plan.as_deref(), Some("# Plan\n\n1. Step"));
    }

    #[test]
    fn selected_permission_preserves_typed_request_and_receipt_in_non_visible_metadata() {
        let mut session = Session::new("sess-1", "test-model");
        session.add_message(bamboo_agent_core::Message::tool_result(
            "permission-1",
            serde_json::json!({
                "status": "awaiting_permission_approval",
                "permission_request": {
                    "request_id": "permission-1",
                    "request_generation": "generation-1",
                    "session_id": "sess-1",
                    "allowed_decisions": ["allow_once", "deny_once"]
                }
            })
            .to_string(),
        ));
        session
            .messages
            .last_mut()
            .expect("permission tool result")
            .metadata = Some(serde_json::json!("legacy-metadata"));

        assert!(update_or_append_tool_result_message(
            &mut session,
            "permission-1",
            "Approve",
            ResponseSource::Human,
        ));
        let receipt = PermissionDecisionReceipt {
            session_id: "sess-1".to_string(),
            decision: bamboo_tools::permission::PermissionDecision {
                request_id: "permission-1".to_string(),
                request_generation: "generation-1".to_string(),
                decision: bamboo_tools::permission::PermissionDecisionKind::AllowOnce,
                matcher_id: None,
                expected_policy_revision: Some(4),
                confirm_global: false,
            },
            decided_at: Utc::now(),
        };
        assert!(persist_permission_decision_receipt(
            &mut session,
            "permission-1",
            &receipt
        ));

        let message = session
            .messages
            .iter()
            .find(|message| message.tool_call_id.as_deref() == Some("permission-1"))
            .expect("permission tool result");
        assert_eq!(message.content, "Selected response: Approve");
        assert_eq!(
            message
                .metadata
                .as_ref()
                .and_then(|metadata| metadata.get("permission_request"))
                .and_then(|request| request.get("request_id"))
                .and_then(serde_json::Value::as_str),
            Some("permission-1")
        );
        assert_eq!(
            message
                .metadata
                .as_ref()
                .and_then(|metadata| metadata.get("previous_metadata")),
            Some(&serde_json::json!("legacy-metadata"))
        );
        assert_eq!(
            message
                .metadata
                .as_ref()
                .and_then(|metadata| metadata.get("permission_decision_receipt"))
                .cloned()
                .and_then(|receipt| {
                    serde_json::from_value::<PermissionDecisionReceipt>(receipt).ok()
                }),
            Some(receipt)
        );
    }

    #[test]
    fn reused_tool_call_id_requires_current_permission_generation() {
        let mut session = Session::new("sess-1", "test-model");
        for generation in ["generation-old", "generation-current"] {
            session.add_message(bamboo_agent_core::Message::tool_result(
                "permission-reused",
                serde_json::json!({
                    "status": "awaiting_permission_approval",
                    "permission_type": "execute_command",
                    "resource": format!("resource-{generation}"),
                    "permission_request": {
                        "request_id": "permission-reused",
                        "request_generation": generation,
                        "session_id": "sess-1",
                        "allowed_decisions": ["allow_once", "deny_once"]
                    }
                })
                .to_string(),
            ));
        }
        session.set_pending_question_with_source(
            "permission-reused".to_string(),
            "Bash".to_string(),
            "Allow the current operation?".to_string(),
            vec!["Approve".to_string(), "Deny".to_string()],
            false,
            bamboo_agent_core::PendingQuestionSource::PauseTool,
        );
        let input = RespondInput {
            session_id: "sess-1".to_string(),
            user_response: "Approve".to_string(),
            model: None,
            model_ref: None,
            provider: None,
            reasoning_effort: None,
        };
        let receipt = |generation: &str| PermissionDecisionReceipt {
            session_id: "sess-1".to_string(),
            decision: bamboo_tools::permission::PermissionDecision {
                request_id: "permission-reused".to_string(),
                request_generation: generation.to_string(),
                decision: bamboo_tools::permission::PermissionDecisionKind::AllowOnce,
                matcher_id: None,
                expected_policy_revision: None,
                confirm_global: false,
            },
            decided_at: Utc::now(),
        };

        let stale = receipt("generation-old");
        assert!(matches!(
            apply_pending_response(
                &mut session,
                &input,
                Some("permission-reused"),
                ResponseSource::Human,
                Some(&stale),
            ),
            Err(RespondError::InvalidResponse(message))
                if message.contains("generation")
        ));
        assert!(session.pending_question.is_some());

        let current = receipt("generation-current");
        apply_pending_response(
            &mut session,
            &input,
            Some("permission-reused"),
            ResponseSource::Human,
            Some(&current),
        )
        .expect("current generation resolves the parked operation");
        assert!(session.pending_question.is_none());
        assert_eq!(
            session
                .metadata
                .get(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY)
                .map(String::as_str),
            Some("generation-current")
        );
        assert!(session.messages[0].content.contains("generation-old"));
        assert_eq!(session.messages[1].content, "Selected response: Approve");
        assert_eq!(
            session.messages[1]
                .metadata
                .as_ref()
                .and_then(|metadata| metadata.get("permission_decision_receipt"))
                .and_then(|receipt| receipt.get("decision"))
                .and_then(|decision| decision.get("request_generation"))
                .and_then(serde_json::Value::as_str),
            Some("generation-current")
        );
    }

    #[test]
    fn typed_permission_receipt_controls_replay_independent_of_display_options() {
        let session = || {
            let mut session = Session::new("sess-typed", "test-model");
            session.add_message(bamboo_agent_core::Message::tool_result(
                "permission-localized",
                serde_json::json!({
                    "status": "awaiting_permission_approval",
                    "permission_type": "execute_command",
                    "resource": "cargo test --workspace",
                    "permission_request": {
                        "request_id": "permission-localized",
                        "request_generation": "generation-localized",
                        "session_id": "sess-typed",
                        "allowed_decisions": ["allow_once", "deny_once"]
                    }
                })
                .to_string(),
            ));
            session.set_pending_question_with_source(
                "permission-localized".to_string(),
                "Bash".to_string(),
                "允许执行吗?".to_string(),
                vec!["允许".to_string(), "拒绝".to_string()],
                false,
                bamboo_agent_core::PendingQuestionSource::PauseTool,
            );
            session
        };
        let receipt = |decision| PermissionDecisionReceipt {
            session_id: "sess-typed".to_string(),
            decision: bamboo_tools::permission::PermissionDecision {
                request_id: "permission-localized".to_string(),
                request_generation: "generation-localized".to_string(),
                decision,
                matcher_id: None,
                expected_policy_revision: None,
                confirm_global: false,
            },
            decided_at: Utc::now(),
        };

        let mut allowed = session();
        let allow_input = RespondInput {
            session_id: "sess-typed".to_string(),
            user_response: "已由结构化决定允许".to_string(),
            model: None,
            model_ref: None,
            provider: None,
            reasoning_effort: None,
        };
        apply_pending_response(
            &mut allowed,
            &allow_input,
            Some("permission-localized"),
            ResponseSource::Human,
            Some(&receipt(PermissionDecisionKind::AllowOnce)),
        )
        .expect("typed allow must not depend on localized display options");
        assert_eq!(
            allowed
                .metadata
                .get(PERMISSION_REEXECUTE_METADATA_KEY)
                .map(String::as_str),
            Some("permission-localized")
        );
        assert_eq!(
            allowed
                .metadata
                .get(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY)
                .map(String::as_str),
            Some("generation-localized")
        );

        let mut denied = session();
        denied.metadata.insert(
            PERMISSION_REEXECUTE_METADATA_KEY.to_string(),
            "stale-call".to_string(),
        );
        denied.metadata.insert(
            PERMISSION_REEXECUTE_GENERATION_METADATA_KEY.to_string(),
            "stale-generation".to_string(),
        );
        let deny_input = RespondInput {
            session_id: "sess-typed".to_string(),
            // Deliberately approval-looking: the receipt enum must win.
            user_response: "Approve".to_string(),
            model: None,
            model_ref: None,
            provider: None,
            reasoning_effort: None,
        };
        apply_pending_response(
            &mut denied,
            &deny_input,
            Some("permission-localized"),
            ResponseSource::Human,
            Some(&receipt(PermissionDecisionKind::DenyOnce)),
        )
        .expect("typed deny must not depend on display text");
        assert!(!denied
            .metadata
            .contains_key(PERMISSION_REEXECUTE_METADATA_KEY));
        assert!(!denied
            .metadata
            .contains_key(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY));

        let mut legacy = session();
        assert!(matches!(
            apply_pending_response(
                &mut legacy,
                &allow_input,
                Some("permission-localized"),
                ResponseSource::Human,
                None,
            ),
            Err(RespondError::InvalidResponse(_))
        ));
        assert!(legacy.pending_question.is_some());
    }
}

#[cfg(test)]
mod receipt_persistence_tests {
    use super::*;
    use crate::session_app::approval_replay::{
        find_permission_replay_target, restore_permission_replay_authorization,
    };
    use crate::{read_cached_session, SessionCache, SessionRepository};
    use bamboo_agent_core::storage::Storage;
    use bamboo_agent_core::tools::{FunctionCall, ToolCall};
    use bamboo_storage::{LockedSessionStore, SessionStoreV2};
    use bamboo_tools::permission::{
        PermissionConfig, PermissionDecision, PermissionMode, PermissionReasonCode,
        PermissionRequest, RiskLevel,
    };

    fn pending_permission(
        session_id: &str,
    ) -> (Session, PermissionRequest, PermissionDecisionReceipt) {
        let mut session = Session::new(session_id, "test-model");
        session.agent_runtime_state = Some(AgentRuntimeState::new("receipt-test-run"));
        let request = |generation: &str, resource: &str| PermissionRequest {
            request_id: "permission-reused".into(),
            request_generation: generation.into(),
            session_id: session_id.into(),
            workspace_path: None,
            tool_name: "Bash".into(),
            permission_type: PermissionType::ExecuteCommand,
            resource: resource.into(),
            operation_summary: format!("execute {resource}"),
            risk_level: RiskLevel::High,
            reason_code: PermissionReasonCode::RiskThreshold,
            effective_mode: PermissionMode::Default,
            bypass_requested: false,
            auto_approve_requested: false,
            policy_revision: 4,
            matched_rule: None,
            allowed_decisions: vec![
                PermissionDecisionKind::AllowOnce,
                PermissionDecisionKind::DenyOnce,
            ],
            suggested_matchers: vec![],
        };
        let current = request("generation-current", "current-command");
        for (name, request) in [
            ("old", request("generation-old", "old-command")),
            ("current", current.clone()),
        ] {
            session.add_message(Message::assistant(
                "",
                Some(vec![ToolCall {
                    id: request.request_id.clone(),
                    tool_type: "function".into(),
                    function: FunctionCall {
                        name: request.tool_name.clone(),
                        arguments: serde_json::json!({"command": request.resource}).to_string(),
                    },
                }]),
            ));
            let mut result = Message::tool_result_with_status(
                &request.request_id,
                serde_json::json!({
                    "status": "awaiting_permission_approval",
                    "permission_type": request.permission_type,
                    "resource": request.resource,
                    "permission_request": request,
                })
                .to_string(),
                false,
            );
            result.id = format!("result-{name}");
            session.add_message(result);
        }
        session.set_pending_question_with_source(
            current.request_id.clone(),
            current.tool_name.clone(),
            "允许本次操作?".into(),
            vec!["允许".into(), "拒绝".into()],
            false,
            bamboo_agent_core::PendingQuestionSource::PauseTool,
        );
        session.metadata.insert(
            "runtime.suspend_reason".into(),
            "awaiting_clarification".into(),
        );
        let receipt = PermissionDecisionReceipt {
            session_id: session_id.into(),
            decision: PermissionDecision {
                request_id: current.request_id.clone(),
                request_generation: current.request_generation.clone(),
                decision: PermissionDecisionKind::AllowOnce,
                matcher_id: None,
                expected_policy_revision: Some(current.policy_revision),
                confirm_global: false,
            },
            decided_at: Utc::now(),
        };
        (session, current, receipt)
    }

    async fn repository(
        session: &mut Session,
    ) -> (tempfile::TempDir, Arc<SessionStoreV2>, SessionRepository) {
        let directory = tempfile::tempdir().unwrap();
        let store = Arc::new(
            SessionStoreV2::new(directory.path().to_path_buf())
                .await
                .unwrap(),
        );
        let storage: Arc<dyn Storage> = store.clone();
        let repo = SessionRepository::new(
            SessionCache::default(),
            storage.clone(),
            Arc::new(LockedSessionStore::new(storage)),
        );
        repo.save(session).await.unwrap();
        (directory, store, repo)
    }

    fn input(session_id: &str) -> RespondInput {
        RespondInput {
            session_id: session_id.into(),
            user_response: "允许".into(),
            model: None,
            model_ref: None,
            provider: None,
            reasoning_effort: None,
        }
    }

    #[tokio::test]
    async fn typed_response_round_trip_restores_only_the_exact_allow_once() {
        eprintln!("debug_assertions={}", cfg!(debug_assertions));
        let (mut session, request, receipt) = pending_permission("receipt-round-trip");
        let (_directory, store, repo) = repository(&mut session).await;
        let old_occurrence = serde_json::to_value(&session.messages[..2]).unwrap();
        let guard = acquire_pending_response_guard(&session.id).await;
        let (accepted, _, _, _) = submit_pending_permission_response_checked_guarded(
            &repo,
            input(&session.id),
            Some(request.request_id.clone()),
            receipt.clone(),
            &guard,
        )
        .await
        .expect("public typed response accepts the current occurrence");
        let durable = store.load_session(&session.id).await.unwrap().unwrap();
        let restarted: Session =
            serde_json::from_slice(&serde_json::to_vec(&durable).unwrap()).unwrap();
        assert!(accepted.pending_question.is_none() && restarted.pending_question.is_none());
        assert_eq!(
            serde_json::to_value(&restarted.messages[..2]).unwrap(),
            old_occurrence
        );
        let message = restarted
            .messages
            .iter()
            .find(|message| message.id == "result-current")
            .unwrap();
        assert_eq!(
            message.tool_call_id.as_deref(),
            Some(request.request_id.as_str())
        );
        assert_eq!(message.content, "Selected response: 允许");
        assert_eq!(message.tool_success, Some(true));
        let metadata = message
            .metadata
            .as_ref()
            .expect("preserved typed request metadata");
        assert_eq!(
            metadata.get("permission_request"),
            Some(&serde_json::to_value(&request).unwrap())
        );
        assert_eq!(
            metadata.get("permission_decision_receipt"),
            Some(&serde_json::to_value(&receipt).unwrap()),
            "the public response must persist the complete receipt, including decided_at"
        );
        assert_eq!(
            restarted.metadata.get(PERMISSION_REEXECUTE_METADATA_KEY),
            Some(&request.request_id)
        );
        assert_eq!(
            restarted
                .metadata
                .get(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY),
            Some(&request.request_generation)
        );

        let target = find_permission_replay_target(
            &restarted,
            &request.request_id,
            Some(&request.request_generation),
        )
        .expect("replay resolves the exact current occurrence after reload");
        assert_eq!(
            target.request_generation(),
            Some(request.request_generation.as_str())
        );
        assert_eq!(
            target.tool_call().function.arguments,
            serde_json::json!({"command":"current-command"}).to_string()
        );
        let config = PermissionConfig::new();
        restore_permission_replay_authorization(&config, &restarted, &target, "Bash").unwrap();
        // Try mismatches before consuming the valid grant, so these assertions
        // cannot pass merely because the one-shot grant was already exhausted.
        for (session_id, call_id, generation, resource) in [
            (
                restarted.id.as_str(),
                request.request_id.as_str(),
                "generation-old",
                request.resource.as_str(),
            ),
            (
                restarted.id.as_str(),
                request.request_id.as_str(),
                request.request_generation.as_str(),
                "other-command",
            ),
            (
                "other-session",
                request.request_id.as_str(),
                request.request_generation.as_str(),
                request.resource.as_str(),
            ),
        ] {
            assert!(!config.consume_once_for_generation(
                session_id,
                call_id,
                generation,
                request.permission_type,
                resource
            ));
        }
        assert!(config.consume_once_for_generation(
            &restarted.id,
            &request.request_id,
            &request.request_generation,
            request.permission_type,
            &request.resource
        ));
        assert!(!config.consume_once_for_generation(
            &restarted.id,
            &request.request_id,
            &request.request_generation,
            request.permission_type,
            &request.resource
        ));
    }

    #[tokio::test]
    async fn typed_deny_round_trip_retains_receipt_without_grants_or_replay() {
        eprintln!("debug_assertions={}", cfg!(debug_assertions));
        let (mut session, request, mut receipt) = pending_permission("receipt-deny");
        receipt.decision.decision = PermissionDecisionKind::DenyOnce;
        session.metadata.insert(
            PERMISSION_REEXECUTE_METADATA_KEY.into(),
            "stale-call".into(),
        );
        session.metadata.insert(
            PERMISSION_REEXECUTE_GENERATION_METADATA_KEY.into(),
            "stale-generation".into(),
        );
        let (_directory, store, repo) = repository(&mut session).await;
        let old_occurrence = serde_json::to_value(&session.messages[..2]).unwrap();
        let mut response = input(&session.id);
        response.user_response = "Approve".into();
        let guard = acquire_pending_response_guard(&session.id).await;
        let (_, display_response, _, grants) = submit_pending_permission_response_checked_guarded(
            &repo,
            response,
            Some(request.request_id.clone()),
            receipt.clone(),
            &guard,
        )
        .await
        .expect("typed deny accepts display text without granting permission");
        assert_eq!(display_response, "Approve");
        assert!(grants.is_empty());
        let durable = store.load_session(&session.id).await.unwrap().unwrap();
        let restarted: Session =
            serde_json::from_slice(&serde_json::to_vec(&durable).unwrap()).unwrap();
        assert!(restarted.pending_question.is_none());
        assert_eq!(
            serde_json::to_value(&restarted.messages[..2]).unwrap(),
            old_occurrence
        );
        let message = restarted.messages.last().unwrap();
        assert_eq!(message.id, "result-current");
        assert_eq!(message.content, "Selected response: Approve");
        let metadata = message.metadata.as_ref().unwrap();
        assert_eq!(
            metadata.get("permission_request"),
            Some(&serde_json::to_value(&request).unwrap())
        );
        assert_eq!(
            metadata.get("permission_decision_receipt"),
            Some(&serde_json::to_value(&receipt).unwrap())
        );
        assert!(!restarted
            .metadata
            .contains_key(PERMISSION_REEXECUTE_METADATA_KEY));
        assert!(!restarted
            .metadata
            .contains_key(PERMISSION_REEXECUTE_GENERATION_METADATA_KEY));
    }

    #[tokio::test]
    async fn failed_typed_receipt_does_not_publish_a_partial_response() {
        eprintln!("debug_assertions={}", cfg!(debug_assertions));
        let (mut session, request, receipt) = pending_permission("receipt-conflict");
        let current = session.messages.last_mut().unwrap();
        current.metadata = Some(serde_json::json!({"permission_request": request}));
        let mut payload: serde_json::Value = serde_json::from_str(&current.content).unwrap();
        payload["permission_request"]["request_generation"] =
            "generation-conflicting-payload".into();
        current.content = payload.to_string();
        let (_directory, store, repo) = repository(&mut session).await;
        let durable_before = store.load_session(&session.id).await.unwrap().unwrap();
        // The real preflight reads metadata A, while display migration will
        // preserve payload B. This reaches a failed receipt write without a
        // test-only writer hook or a new storage failure protocol.
        assert_eq!(
            permission_request_generation(durable_before.messages.last().unwrap()).as_deref(),
            Some(receipt.decision.request_generation.as_str())
        );
        let cache_before =
            serde_json::to_value(read_cached_session(repo.cache(), &session.id).unwrap()).unwrap();
        let durable_before = serde_json::to_value(durable_before).unwrap();
        let guard = acquire_pending_response_guard(&session.id).await;
        let result = submit_pending_permission_response_checked_guarded(
            &repo,
            input(&session.id),
            Some(request.request_id),
            receipt,
            &guard,
        )
        .await;
        assert!(
            matches!(result, Err(RespondError::InvalidResponse(ref message)) if message.contains("receipt")),
            "failed receipt persistence must be an explicit response error: {result:?}"
        );
        assert_eq!(
            serde_json::to_value(store.load_session(&session.id).await.unwrap().unwrap()).unwrap(),
            durable_before,
            "pending question, result and all durable markers stay unchanged"
        );
        assert_eq!(
            serde_json::to_value(read_cached_session(repo.cache(), &session.id).unwrap()).unwrap(),
            cache_before,
            "a rejected response must not publish a cache snapshot"
        );
    }
}