bamboo-engine 2026.10.22

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
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
//! Authoritative permission refresh for approved-tool replay.
//!
//! An approval only authorizes the posture that is still active when the
//! suspended tool is about to re-enter the executor. All replay surfaces use
//! this helper so a stale in-memory Auto/Bypass snapshot cannot outrun a newer
//! durable Default/Plan transition.

use bamboo_agent_core::storage::Storage;
use bamboo_agent_core::tools::{
    plan_mode_allows_tool, ExecutingSupervisorObservation, PendingToolOperation,
    RetainedToolExecution, ToolCall, ToolExecutionSessionFlags, ToolExecutor, ToolResult,
    PENDING_TOOL_OPERATION_METADATA_KEY,
};
use bamboo_agent_core::{AgentError, PendingQuestionSource, Session};
use bamboo_domain::{permission_request_generation, AgentRuntimeState, PermissionMode};
use bamboo_tools::permission::{
    PermissionConfig, PermissionDecision, PermissionDecisionKind, PermissionDecisionReceipt,
    PermissionRequest,
};
use serde::{Deserialize, Serialize};

const PERMISSION_REPLAY_APPROVALS_METADATA_KEY: &str = "permission.replay_approvals.v1";

/// Original host dispatch, retained through result application without reading
/// a possibly replaced Session or trusting the tool's display payload.
pub(crate) struct PermissionReplayOrigin {
    caller: Option<bamboo_domain::SessionCallerReference>,
    observation: Option<ExecutingSupervisorObservation>,
    session_id: String,
    tool_call: ToolCall,
    execution_name: String,
    execution_contract: Option<String>,
    contract_known: bool,
}

impl PermissionReplayOrigin {
    pub(crate) fn new(
        caller: Option<bamboo_domain::SessionCallerReference>,
        observation: Option<ExecutingSupervisorObservation>,
        session_id: &str,
        tool_call: &ToolCall,
        execution_name: &str,
        execution_contract: Option<&str>,
        contract_known: bool,
    ) -> Self {
        Self {
            caller,
            observation,
            session_id: session_id.into(),
            tool_call: tool_call.clone(),
            execution_name: execution_name.into(),
            execution_contract: execution_contract.map(str::to_owned),
            contract_known,
        }
    }

    pub(crate) fn has_supervisor_observation(&self) -> bool {
        self.observation.is_some()
    }

    pub(crate) fn bind_waiting_message(&self, message: &mut bamboo_agent_core::Message) {
        let Ok(payload) = serde_json::from_str::<serde_json::Value>(&message.content) else {
            return;
        };
        if payload.get("status").and_then(serde_json::Value::as_str)
            != Some("awaiting_permission_approval")
        {
            return;
        }
        let Some(request) = payload
            .get("permission_request")
            .cloned()
            .and_then(|value| serde_json::from_value::<PermissionRequest>(value).ok())
        else {
            return;
        };
        if request.session_id != self.session_id
            || request.request_id != self.tool_call.id
            || request.tool_name != self.execution_name
            || request.request_generation.trim().is_empty()
            || message.tool_call_id.as_deref() != Some(self.tool_call.id.as_str())
        {
            return;
        }
        let mut metadata = serde_json::json!({"permission_request": request});
        if let Some(caller) = self.caller.as_ref() {
            metadata[PENDING_TOOL_OPERATION_METADATA_KEY] =
                PendingToolOperation::capture_with_contract(
                    caller.clone(),
                    &message.id,
                    &self.tool_call,
                    &self.execution_name,
                    &request.request_generation,
                    self.execution_contract.as_deref(),
                    self.contract_known,
                )
                .metadata_value();
        }
        if let Some(observation) = self.observation {
            metadata[ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY] = observation
                .permission_replay_record(
                    &self.session_id,
                    &message.id,
                    &self.tool_call,
                    &self.execution_name,
                    &request.request_generation,
                );
        }
        message.metadata = Some(metadata);
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct PermissionReplayApproval {
    request: PermissionRequest,
    decision: PermissionDecision,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReparkedPermissionApproval {
    pub question: String,
    pub options: Vec<String>,
    pub allow_custom: bool,
}

/// Result of refreshing permission posture immediately before approval replay.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ApprovalReplayDecision {
    /// The approved call may enter the executor with these exact live flags.
    Execute(ToolExecutionSessionFlags),
    /// The approval became stale because the latest posture is Plan and the
    /// original tool mutates state. Callers consume the marker and record a
    /// failed result, but must not emit `ToolStart` or enter the executor.
    BlockedByPlan(ToolExecutionSessionFlags),
    /// The durable Root tool catalog no longer admits the resolved execution
    /// owner. Callers consume the marker as a failed result without restoring
    /// a remembered grant, emitting ToolStart, or entering the executor.
    BlockedByRootToolAuthority,
    /// The original execution owner is no longer registered. A legacy replay
    /// consumes its stale marker as a failed result without entering a tool.
    BlockedByUnavailableTool,
}

/// Exact history target of one approved tool replay.
///
/// The result-message position is captured together with the closest preceding
/// tool call so a provider-reused tool-call id cannot redirect replay to an
/// older operation or overwrite an older result.
pub struct PermissionReplayTarget {
    tool_call: ToolCall,
    result_message_index: usize,
    result_message_id: String,
    request_generation: Option<String>,
}

impl PermissionReplayTarget {
    pub fn tool_call(&self) -> &ToolCall {
        &self.tool_call
    }

    pub fn request_generation(&self) -> Option<&str> {
        self.request_generation.as_deref()
    }
}

fn retained_operation(
    session: &Session,
    target: &PermissionReplayTarget,
) -> Result<Option<PendingToolOperation>, AgentError> {
    PendingToolOperation::restore(
        session,
        target.result_message_index,
        &target.tool_call,
        target.request_generation(),
    )
    .map_err(|error| AgentError::Tool(error.into()))
}

/// Restore the original generic caller only from the validated host record.
/// Legacy readable history has no generic observation; do not mint one from
/// the Session that happened to be reloaded for this replay.
pub fn restore_permission_replay_caller(
    session: &Session,
    target: &PermissionReplayTarget,
) -> Result<Option<bamboo_domain::SessionCallerReference>, AgentError> {
    retained_operation(session, target)
        .map(|operation| operation.map(|operation| operation.caller().clone()))
}

/// Restore semantic selection only from retained Host evidence. Missing v1
/// provenance cannot identify a canonical v2 spawn owner after a name collision.
pub fn restore_permission_replay_execution(
    session: &Session,
    target: &PermissionReplayTarget,
    execution_name: &str,
) -> Result<Option<RetainedToolExecution>, AgentError> {
    let operation = retained_operation(session, target)?;
    let (known, contract) = if let Some(operation) = operation.as_ref() {
        if operation.execution_name() != execution_name {
            return Err(AgentError::Tool("retained execution owner changed".into()));
        }
        if operation.has_execution_contract_record() {
            (
                operation.execution_contract_known(),
                operation.execution_contract(),
            )
        } else {
            if execution_name == "spawn_session" && session.independent_root_spawn_contract() {
                return Err(unknown_spawn_contract());
            }
            (execution_name == "spawn_session", None)
        }
    } else {
        let legacy_binding = session.messages[target.result_message_index]
            .metadata
            .as_ref()
            .is_some_and(|metadata| {
                metadata
                    .get(ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY)
                    .is_some()
            });
        if !legacy_binding {
            return Ok(None);
        }
        ExecutingSupervisorObservation::restore_permission_replay_record(
            session,
            target.result_message_index,
            &target.tool_call,
            execution_name,
            target.request_generation(),
        )
        .map_err(|error| AgentError::Tool(error.into()))?;
        if execution_name == "spawn_session" && session.independent_root_spawn_contract() {
            return Err(unknown_spawn_contract());
        }
        (execution_name == "spawn_session", None)
    };
    if execution_name == "spawn_session" && !known {
        return Err(unknown_spawn_contract());
    }
    RetainedToolExecution::new(&target.tool_call, execution_name, known, contract)
        .map(Some)
        .map_err(|error| AgentError::Tool(error.to_string()))
}

fn unknown_spawn_contract() -> AgentError {
    AgentError::Tool("retained spawn operation lacks concrete execution-contract provenance; history and pending markers are preserved. Resend explicitly; no Root or Child was started".into())
}

fn retained_request(
    session: &Session,
    target: &PermissionReplayTarget,
) -> Result<Option<PermissionRequest>, AgentError> {
    let message = session
        .messages
        .get(target.result_message_index)
        .filter(|message| message.id == target.result_message_id)
        .ok_or_else(|| AgentError::Tool("permission replay result occurrence changed".into()))?;
    let payload = serde_json::from_str::<serde_json::Value>(&message.content).ok();
    let decode = |value: &serde_json::Value| {
        serde_json::from_value::<PermissionRequest>(value.clone())
            .map_err(|_| AgentError::Tool("permission replay request is malformed".into()))
    };
    let durable = message
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("permission_request"))
        .map(decode)
        .transpose()?;
    let displayed = payload
        .as_ref()
        .and_then(|payload| payload.get("permission_request"))
        .map(decode)
        .transpose()?;
    if matches!((&durable, &displayed), (Some(a), Some(b)) if a != b) {
        return Err(AgentError::Tool(
            "permission replay request payload and metadata disagree".into(),
        ));
    }
    let request = durable.or(displayed);
    if request.as_ref().is_some_and(|request| {
        message.role != bamboo_domain::Role::Tool
            || request.session_id != session.id
            || request.request_id != target.tool_call.id
            || request.request_generation.trim().is_empty()
            || Some(request.request_generation.as_str()) != target.request_generation()
    }) {
        return Err(AgentError::Tool(
            "permission replay request identity changed".into(),
        ));
    }
    Ok(request)
}

/// Retained replay selects its original exact owner, never the fresh-call alias.
/// Old non-spawn calls keep their established resolver only while it agrees
/// with the retained typed owner. Ambiguous historical spawn calls need a new
/// explicit instruction, with their history and pending markers left intact.
pub fn resolve_permission_replay_owner(
    session: &Session,
    target: &PermissionReplayTarget,
    executor: &dyn ToolExecutor,
) -> Result<Option<String>, AgentError> {
    session
        .check_execution_compatibility()
        .map_err(|error| AgentError::Tool(error.to_string()))?;
    let operation = retained_operation(session, target)?;
    let request = retained_request(session, target)?;
    if let Some(operation) = operation {
        let request = request
            .ok_or_else(|| AgentError::Tool("pending operation lacks its typed request".into()))?;
        if operation.execution_name() != request.tool_name {
            return Err(AgentError::Tool(
                "permission replay owner differs from its frozen operation".into(),
            ));
        }
        let execution =
            restore_permission_replay_execution(session, target, operation.execution_name())?
                .expect("retained operation provides execution selection");
        return Ok((execution.owner_is_available(executor)
            && replay_framework_instance_available(
                session,
                operation.execution_name(),
                Some(&execution),
                executor,
            ))
        .then(|| operation.execution_name().to_owned()));
    }
    let legacy_supervisor_binding = session.messages[target.result_message_index]
        .metadata
        .as_ref()
        .is_some_and(|metadata| {
            metadata
                .get(ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY)
                .is_some()
        });
    if legacy_supervisor_binding {
        let request = request.ok_or_else(|| {
            AgentError::Tool("Supervisor pending operation lacks its typed request".into())
        })?;
        ExecutingSupervisorObservation::restore_permission_replay_record(
            session,
            target.result_message_index,
            &target.tool_call,
            &request.tool_name,
            target.request_generation(),
        )
        .map_err(|error| AgentError::Tool(error.into()))?;
        let execution = restore_permission_replay_execution(session, target, &request.tool_name)?
            .expect("validated legacy binding provides execution selection");
        return Ok((execution.owner_is_available(executor)
            && replay_framework_instance_available(
                session,
                &request.tool_name,
                Some(&execution),
                executor,
            ))
        .then_some(request.tool_name));
    }
    if bamboo_domain::independent_root_spawn_reference(&target.tool_call.function.name) {
        return Err(AgentError::Tool("retained spawn operation has no frozen owner/arguments; history and pending state are preserved. Resend the intended operation explicitly; no Root or Child was started".into()));
    }
    let owner = executor.resolve_reference_for_session(session, &target.tool_call.function.name);
    if let (Some(request), Some(owner)) = (&request, &owner) {
        if request.tool_name != *owner {
            return Err(AgentError::Tool(
                "permission replay owner differs from the retained request".into(),
            ));
        }
    }
    Ok(owner.filter(|name| replay_framework_instance_available(session, name, None, executor)))
}

fn replay_framework_instance_available(
    session: &Session,
    name: &str,
    retained: Option<&RetainedToolExecution>,
    executor: &dyn ToolExecutor,
) -> bool {
    let kind = bamboo_agent_core::tools::FrameworkSessionToolKind::from_execution_name(name);
    let root_semantics = retained.and_then(RetainedToolExecution::execution_contract)
        == Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1);
    // A known retained custom/legacy owner remains that exact operation. A
    // normal Child's own frozen ceiling still checks whether it is callable;
    // do not reinterpret it as the newly installed framework Root instance.
    let retained_ordinary_legacy_spawn = name == "spawn_session"
        && !session.model_orchestration_only_enabled()
        && retained.is_some_and(|retained| retained.contract_known() && !root_semantics);
    if kind.is_none()
        || retained_ordinary_legacy_spawn
        || !(root_semantics
            || session.model_orchestration_only_enabled()
            || session.kind == bamboo_domain::SessionKind::Child)
    {
        return true;
    }
    match retained {
        Some(retained) => retained.framework_instance_is_available(executor),
        None => executor
            .framework_session_tool_for_exact(name)
            .is_some_and(|proof| Some(proof.kind()) == kind && proof.is_current()),
    }
}

/// Locate the concrete approved invocation, newest-first and optionally bound
/// to the server-issued permission generation.
pub fn find_permission_replay_target(
    session: &Session,
    tool_call_id: &str,
    request_generation: Option<&str>,
) -> Option<PermissionReplayTarget> {
    let (result_message_index, result_message) =
        session
            .messages
            .iter()
            .enumerate()
            .rev()
            .find(|(_, message)| {
                message.tool_call_id.as_deref() == Some(tool_call_id)
                    && match request_generation {
                        Some(generation) => {
                            permission_request_generation(message).as_deref() == Some(generation)
                        }
                        None => true,
                    }
            })?;
    let tool_call = session.messages[..result_message_index]
        .iter()
        .rev()
        .find_map(|message| {
            message.tool_calls.as_ref().and_then(|calls| {
                calls
                    .iter()
                    .rev()
                    .find(|call| call.id == tool_call_id)
                    .cloned()
            })
        })?;
    let result_generation = permission_request_generation(result_message);
    Some(PermissionReplayTarget {
        tool_call,
        result_message_index,
        result_message_id: result_message.id.clone(),
        request_generation: result_generation,
    })
}

/// Replace only the tool-result message captured by
/// [`find_permission_replay_target`].
pub fn apply_permission_replay_result(
    session: &mut Session,
    target: &PermissionReplayTarget,
    content: String,
    success: bool,
) -> bool {
    let Some(message) = session.messages.get_mut(target.result_message_index) else {
        return false;
    };
    if message.id != target.result_message_id
        || message.tool_call_id.as_deref() != Some(target.tool_call.id.as_str())
        || target
            .request_generation
            .as_deref()
            .is_some_and(|generation| {
                permission_request_generation(message).as_deref() != Some(generation)
            })
    {
        return false;
    }
    message.content = content;
    message.tool_success = Some(success);
    true
}

fn message_permission_contract(
    session: &Session,
    target: &PermissionReplayTarget,
) -> Result<(PermissionRequest, PermissionDecisionReceipt), AgentError> {
    let message = session
        .messages
        .get(target.result_message_index)
        .filter(|message| message.id == target.result_message_id)
        .ok_or_else(|| {
            AgentError::Tool("permission replay result occurrence changed".to_string())
        })?;
    let metadata = message.metadata.as_ref().ok_or_else(|| {
        AgentError::Tool("permission replay is missing durable typed metadata".to_string())
    })?;
    let request = metadata
        .get("permission_request")
        .cloned()
        .and_then(|value| serde_json::from_value::<PermissionRequest>(value).ok())
        .ok_or_else(|| {
            AgentError::Tool("permission replay is missing its durable request".to_string())
        })?;
    let receipt = metadata
        .get("permission_decision_receipt")
        .cloned()
        .and_then(|value| serde_json::from_value::<PermissionDecisionReceipt>(value).ok())
        .ok_or_else(|| {
            AgentError::Tool(
                "permission replay is missing its durable decision receipt".to_string(),
            )
        })?;
    Ok((request, receipt))
}

fn validate_replay_approval(
    session: &Session,
    tool_call_id: &str,
    approval: &PermissionReplayApproval,
) -> Result<(), AgentError> {
    let request = &approval.request;
    let decision = &approval.decision;
    // expected_policy_revision was checked as an ingress CAS. A refresh can
    // retain this request generation while the durable request has its old revision.
    if request.session_id != session.id
        || request.request_id != tool_call_id
        || request.request_generation.trim().is_empty()
        || decision.request_id != request.request_id
        || decision.request_generation != request.request_generation
        || !request.allowed_decisions.contains(&decision.decision)
    {
        return Err(AgentError::Tool(
            "permission replay approval identity is invalid".to_string(),
        ));
    }
    if decision.decision == PermissionDecisionKind::AllowGlobal && !decision.confirm_global {
        return Err(AgentError::Tool(
            "permission replay global approval lacks explicit confirmation".to_string(),
        ));
    }
    Ok(())
}

fn selected_replay_matcher(
    approval: &PermissionReplayApproval,
) -> Result<bamboo_tools::permission::PermissionMatcher, AgentError> {
    let matcher_id = approval.decision.matcher_id.as_deref().ok_or_else(|| {
        AgentError::Tool("remembered permission replay lacks matcher identity".to_string())
    })?;
    approval
        .request
        .suggested_matchers
        .iter()
        .find(|matcher| matcher.id == matcher_id)
        .cloned()
        .ok_or_else(|| {
            AgentError::Tool("remembered permission replay matcher is unavailable".to_string())
        })
}

/// Pure admission, including present-invalid authority on legacy and Plan
/// paths. Run this before changing replay markers or installing any grants.
pub fn validate_permission_replay_authority(
    session: &Session,
    target: &PermissionReplayTarget,
    execution_name: &str,
) -> Result<Option<ExecutingSupervisorObservation>, AgentError> {
    session
        .check_execution_compatibility()
        .map_err(|error| AgentError::Tool(error.to_string()))?;
    if let Some(operation) = retained_operation(session, target)? {
        if operation.execution_name() != execution_name {
            return Err(AgentError::Tool(
                "permission replay owner differs from its frozen operation".into(),
            ));
        }
    }
    let observation = ExecutingSupervisorObservation::restore_permission_replay_record(
        session,
        target.result_message_index,
        &target.tool_call,
        execution_name,
        target.request_generation(),
    )
    .map_err(|error| AgentError::Tool(error.into()))?;
    if target.request_generation().is_some() {
        let approvals = validated_replay_approvals(session, target)?;
        if approvals.is_empty()
            || approvals
                .iter()
                .any(|approval| approval.request.tool_name != execution_name)
        {
            return Err(AgentError::Tool(
                "permission replay approval owner does not match dispatch".into(),
            ));
        }
    }
    Ok(observation)
}

/// An unanswered native approval can be displayed again without a receipt,
/// but its host identity must already match the waiting operation. This pure
/// check never returns an executable observation or installs a permission.
pub fn validate_pending_permission_replay_authority(
    session: &Session,
    target: &PermissionReplayTarget,
    execution_name: &str,
) -> Result<(), AgentError> {
    if let Some(operation) = retained_operation(session, target)? {
        if operation.execution_name() != execution_name {
            return Err(AgentError::Tool(
                "pending approval owner differs from its frozen operation".into(),
            ));
        }
    }
    let observation = ExecutingSupervisorObservation::restore_permission_replay_record(
        session,
        target.result_message_index,
        &target.tool_call,
        execution_name,
        target.request_generation(),
    )
    .map_err(|error| AgentError::Tool(error.into()))?;
    if observation.is_some() {
        let metadata = session.messages[target.result_message_index]
            .metadata
            .as_ref()
            .expect("validated host metadata");
        let request = metadata
            .get("permission_request")
            .cloned()
            .and_then(|value| serde_json::from_value::<PermissionRequest>(value).ok())
            .ok_or_else(|| {
                AgentError::Tool(
                    "Supervisor waiting approval is missing its durable request".into(),
                )
            })?;
        if request.session_id != session.id
            || request.request_id != target.tool_call.id
            || request.tool_name != execution_name
            || target.request_generation() != Some(request.request_generation.as_str())
            || metadata.get("permission_decision_receipt").is_some()
        {
            return Err(AgentError::Tool(
                "Supervisor waiting approval does not match its request".into(),
            ));
        }
    }
    Ok(())
}

fn validated_replay_approvals(
    session: &Session,
    target: &PermissionReplayTarget,
) -> Result<Vec<PermissionReplayApproval>, AgentError> {
    let Some(replay_generation) = target.request_generation() else {
        return Ok(Vec::new());
    };
    let message = session
        .messages
        .get(target.result_message_index)
        .filter(|message| message.id == target.result_message_id)
        .ok_or_else(|| AgentError::Tool("permission replay result occurrence changed".into()))?;
    let mut approvals = message
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get(PERMISSION_REPLAY_APPROVALS_METADATA_KEY))
        .cloned()
        .map(serde_json::from_value::<Vec<PermissionReplayApproval>>)
        .transpose()
        .map_err(|error| {
            AgentError::Tool(format!(
                "permission replay approval ledger is invalid: {error}"
            ))
        })?
        .unwrap_or_default();
    let (request, receipt) = message_permission_contract(session, target)?;
    if receipt.session_id != session.id || request.request_generation != replay_generation {
        return Err(AgentError::Tool(
            "permission replay receipt does not match the active generation".into(),
        ));
    }
    approvals.push(PermissionReplayApproval {
        request,
        decision: receipt.decision,
    });
    if approvals.len() > 64 {
        return Err(AgentError::Tool(
            "permission replay approval ledger exceeded its safety bound".into(),
        ));
    }
    for approval in &approvals {
        validate_replay_approval(session, &target.tool_call.id, approval)?;
        match approval.decision.decision {
            PermissionDecisionKind::AllowOnce => {}
            PermissionDecisionKind::AllowSession | PermissionDecisionKind::AllowGlobal => {
                selected_replay_matcher(approval)?;
            }
            PermissionDecisionKind::AllowWorkspace => {
                let workspace = session
                    .workspace
                    .as_deref()
                    .map(str::trim)
                    .filter(|workspace| !workspace.is_empty());
                if workspace != approval.request.workspace_path.as_deref() {
                    return Err(AgentError::Tool(
                        "workspace permission replay does not match the durable session workspace"
                            .into(),
                    ));
                }
                selected_replay_matcher(approval)?;
            }
            PermissionDecisionKind::DenyOnce | PermissionDecisionKind::DenySession => {
                return Err(AgentError::Tool(
                    "denied permission unexpectedly carried an execution replay marker".into(),
                ));
            }
        }
    }
    Ok(approvals)
}

/// Rebuild the exact runtime capabilities needed by a typed approved replay.
///
/// The current receipt and any earlier contexts approved for the same concrete
/// invocation live on the generation-bound result message. This lets a daemon
/// restart recover an AllowOnce/AllowSession without broadening it, and lets a
/// tool with multiple permission contexts restart its checks while retaining
/// only the contexts the operator already approved.
pub fn restore_permission_replay_authorization(
    config: &PermissionConfig,
    session: &Session,
    target: &PermissionReplayTarget,
    execution_name: &str,
) -> Result<(), AgentError> {
    validate_permission_replay_authority(session, target, execution_name)?;
    let approvals = validated_replay_approvals(session, target)?;
    let Some(replay_generation) = target.request_generation() else {
        return Ok(());
    };
    config.set_session_workspace(
        session.id.clone(),
        session
            .workspace
            .as_deref()
            .map(str::trim)
            .filter(|workspace| !workspace.is_empty())
            .map(ToOwned::to_owned),
    );
    // Every record and matcher was validated before the first installation.
    for approval in &approvals {
        match approval.decision.decision {
            PermissionDecisionKind::AllowOnce => config
                .grant_once_for_generation(
                    &session.id,
                    &target.tool_call.id,
                    replay_generation,
                    approval.request.permission_type,
                    approval.request.resource.clone(),
                )
                .map_err(AgentError::Tool)?,
            PermissionDecisionKind::AllowSession => config
                .grant_typed_scoped_session_permission(
                    &session.id,
                    approval.request.permission_type,
                    selected_replay_matcher(approval)?,
                )
                .map_err(AgentError::Tool)?,
            PermissionDecisionKind::AllowWorkspace | PermissionDecisionKind::AllowGlobal => {}
            PermissionDecisionKind::DenyOnce | PermissionDecisionKind::DenySession => {
                unreachable!("validated above")
            }
        }
    }
    Ok(())
}

/// Convert a second typed permission gate encountered during replay into a new
/// durable pending question. The prior approval is appended to a bounded
/// per-invocation ledger; no model successor may start until every context has
/// been separately approved and the tool returns a real result.
pub fn repark_permission_replay(
    session: &mut Session,
    target: &PermissionReplayTarget,
    result: &ToolResult,
    execution_name: &str,
) -> Result<Option<ReparkedPermissionApproval>, AgentError> {
    let payload = match serde_json::from_str::<serde_json::Value>(&result.result) {
        Ok(payload)
            if result.display_preference.as_deref() == Some("request_permissions")
                && payload.get("status").and_then(serde_json::Value::as_str)
                    == Some("awaiting_permission_approval") =>
        {
            payload
        }
        _ => return Ok(None),
    };
    // Validate the old durable identity/receipt without installing grants again.
    let original_observation =
        validate_permission_replay_authority(session, target, execution_name)?;
    let original_operation = retained_operation(session, target)?;
    let prior_approvals = validated_replay_approvals(session, target)?;
    if payload
        .get(ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY)
        .is_some()
        || payload.get(PENDING_TOOL_OPERATION_METADATA_KEY).is_some()
    {
        return Err(AgentError::Tool(
            "Supervisor authority cannot originate in a replay result payload".into(),
        ));
    }
    let new_request = payload
        .get("permission_request")
        .cloned()
        .and_then(|value| serde_json::from_value::<PermissionRequest>(value).ok())
        .ok_or_else(|| {
            AgentError::Tool("replayed permission gate omitted typed request".to_string())
        })?;
    if new_request.session_id != session.id
        || new_request.request_id != target.tool_call.id
        || new_request.request_generation.trim().is_empty()
        || new_request.tool_name != execution_name
        || target.request_generation() == Some(new_request.request_generation.as_str())
        || prior_approvals
            .iter()
            .any(|approval| approval.request.request_generation == new_request.request_generation)
    {
        return Err(AgentError::Tool(
            "replayed permission gate returned an invalid next-generation identity".to_string(),
        ));
    }
    let question = payload
        .get("question")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("Permission required")
        .to_string();
    let options = payload
        .get("options")
        .and_then(serde_json::Value::as_array)
        .map(|options| {
            options
                .iter()
                .filter_map(serde_json::Value::as_str)
                .map(ToOwned::to_owned)
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    let allow_custom = payload
        .get("allow_custom")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    let (old_request, old_receipt) = message_permission_contract(session, target)?;
    if old_receipt.session_id != session.id {
        return Err(AgentError::Tool(
            "permission replay receipt session identity changed".to_string(),
        ));
    }
    let old_approval = PermissionReplayApproval {
        request: old_request,
        decision: old_receipt.decision,
    };
    validate_replay_approval(session, target.tool_call.id.as_str(), &old_approval)?;

    let message = session
        .messages
        .get_mut(target.result_message_index)
        .filter(|message| {
            message.id == target.result_message_id
                && message.tool_call_id.as_deref() == Some(target.tool_call.id.as_str())
        })
        .ok_or_else(|| {
            AgentError::Tool("permission replay result occurrence changed".to_string())
        })?;
    let metadata = message
        .metadata
        .get_or_insert_with(|| serde_json::Value::Object(Default::default()));
    let object = metadata.as_object_mut().ok_or_else(|| {
        AgentError::Tool("permission replay result metadata is malformed".to_string())
    })?;
    let mut approvals = object
        .get(PERMISSION_REPLAY_APPROVALS_METADATA_KEY)
        .cloned()
        .map(serde_json::from_value::<Vec<PermissionReplayApproval>>)
        .transpose()
        .map_err(|error| {
            AgentError::Tool(format!(
                "permission replay approval ledger is invalid: {error}"
            ))
        })?
        .unwrap_or_default();
    if !approvals.iter().any(|approval| approval == &old_approval) {
        approvals.push(old_approval);
    }
    if approvals.len() > 64 {
        return Err(AgentError::Tool(
            "permission replay approval ledger exceeded its safety bound".to_string(),
        ));
    }
    object.insert(
        PERMISSION_REPLAY_APPROVALS_METADATA_KEY.to_string(),
        serde_json::to_value(approvals).expect("permission replay approvals serialize"),
    );
    if let Some(original) = original_operation {
        object.insert(
            PENDING_TOOL_OPERATION_METADATA_KEY.to_string(),
            original
                .for_generation(&new_request.request_generation)
                .metadata_value(),
        );
    }
    if let Some(original) = original_observation {
        object.insert(
            ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY.to_string(),
            original.permission_replay_record(
                &session.id,
                &target.result_message_id,
                &target.tool_call,
                execution_name,
                &new_request.request_generation,
            ),
        );
    }
    object.insert(
        "permission_request".to_string(),
        serde_json::to_value(&new_request).expect("permission request serializes"),
    );
    object.remove("permission_decision_receipt");
    message.content.clone_from(&result.result);
    message.tool_success = Some(result.success);

    session.set_pending_question_with_source(
        target.tool_call.id.clone(),
        target.tool_call.function.name.clone(),
        question.clone(),
        options.clone(),
        allow_custom,
        PendingQuestionSource::PauseTool,
    );
    session
        .metadata
        .remove(crate::session_app::respond::PERMISSION_REEXECUTE_METADATA_KEY);
    session
        .metadata
        .remove(crate::session_app::respond::PERMISSION_REEXECUTE_GENERATION_METADATA_KEY);
    for stale_resume_marker in [
        "clarification_resume_pending",
        "conclusion_with_options_resume_pending",
        "execute.startup_handoff_at",
    ] {
        session.metadata.remove(stale_resume_marker);
    }
    session.metadata.insert(
        "runtime.suspend_reason".to_string(),
        "awaiting_clarification".to_string(),
    );
    Ok(Some(ReparkedPermissionApproval {
        question,
        options,
        allow_custom,
    }))
}

/// Strictly reload and adopt the authoritative permission posture for an
/// approved tool call. `execution_name` is the resolved exact execution owner,
/// or `None` when a legacy call's owner is no longer registered.
///
/// Storage errors, missing sessions, and malformed typed posture fail closed.
/// This function does not touch the replay marker, so callers can retain it
/// when returning the error. The coherent typed-mode/audit pair and Plan state
/// are committed to `session` only after every fallible validation succeeds.
pub async fn refresh_approval_replay_posture(
    storage: &dyn Storage,
    session: &mut Session,
    configured_mode: PermissionMode,
    execution_name: Option<&str>,
) -> Result<ApprovalReplayDecision, AgentError> {
    session
        .check_execution_compatibility()
        .map_err(|error| AgentError::Tool(error.to_string()))?;
    let latest = storage
        .load_execution_admission_snapshot(&session.id)
        .await
        .map_err(|error| {
            AgentError::Tool(format!(
                "authoritative approval replay posture refresh failed closed: {error}"
            ))
        })?
        .ok_or_else(|| {
            AgentError::Tool(
                "authoritative approval replay posture refresh failed closed: session missing"
                    .to_string(),
            )
        })?;
    latest
        .check_execution_compatibility()
        .map_err(|error| AgentError::Tool(error.to_string()))?;
    let latest_runtime = latest.agent_runtime_state.as_ref().ok_or_else(|| {
        AgentError::Tool(
            "authoritative approval replay posture refresh failed closed: typed mode missing"
                .to_string(),
        )
    })?;
    let disk_mode = latest_runtime.effective_permission_mode();
    let current_mode = session
        .agent_runtime_state
        .as_ref()
        .map(AgentRuntimeState::effective_permission_mode)
        .unwrap_or_default();

    let should_adopt_audit = bamboo_domain::disk_permission_posture_is_fresher(
        current_mode,
        &session.metadata,
        disk_mode,
        &latest.metadata,
    );
    let fresher_audit = bamboo_domain::fresher_disk_permission_audit(
        current_mode,
        &session.metadata,
        disk_mode,
        &latest.metadata,
    );
    if should_adopt_audit && fresher_audit.is_none() {
        return Err(AgentError::Tool(
            "authoritative approval replay posture refresh failed closed: complete audit unavailable"
                .to_string(),
        ));
    }

    // A replay may arrive after this Root ID was deleted and recreated, or
    // after a host narrowed its tool catalog. Validate the same durable birth
    // and revision proof used by normal tool dispatch before any grant or
    // replay-marker mutation.
    session
        .adopt_root_tool_authority_from(&latest)
        .map_err(|error| {
            AgentError::Tool(format!(
                "authoritative approval replay Root tool authority failed closed: {error}"
            ))
        })?;
    if let Some(audit) = fresher_audit {
        audit.write_to(&mut session.metadata);
    }
    let runtime = session
        .agent_runtime_state
        .get_or_insert_with(|| AgentRuntimeState::new(latest_runtime.run_id.clone()));
    runtime.set_permission_mode(disk_mode);
    runtime.plan_mode = latest_runtime.plan_mode.clone();

    let flags =
        ToolExecutionSessionFlags::from_session_and_configured_mode(session, configured_mode);
    let Some(execution_name) = execution_name else {
        return Ok(ApprovalReplayDecision::BlockedByUnavailableTool);
    };
    if !session.allows_model_tool_execution(execution_name) {
        Ok(ApprovalReplayDecision::BlockedByRootToolAuthority)
    } else if flags.plan_read_only && !plan_mode_allows_tool(execution_name) {
        Ok(ApprovalReplayDecision::BlockedByPlan(flags))
    } else {
        Ok(ApprovalReplayDecision::Execute(flags))
    }
}

/// Refresh the live policy, then preserve the historical custom-owner mode
/// boundary. The common spawn name is for the proven framework Root tool;
/// joining that allowlist cannot promote a retained custom implementation.
pub async fn refresh_retained_approval_replay_posture(
    storage: &dyn Storage,
    session: &mut Session,
    configured_mode: PermissionMode,
    execution_name: Option<&str>,
    execution: Option<&RetainedToolExecution>,
) -> Result<ApprovalReplayDecision, AgentError> {
    let decision =
        refresh_approval_replay_posture(storage, session, configured_mode, execution_name).await?;
    if matches!(decision, ApprovalReplayDecision::Execute(_))
        && execution_name == Some("spawn_session")
        && session.model_orchestration_only_enabled()
        && execution.and_then(RetainedToolExecution::execution_contract)
            != Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1)
    {
        return Ok(ApprovalReplayDecision::BlockedByRootToolAuthority);
    }
    Ok(decision)
}

#[cfg(test)]
pub(crate) mod framework_fixture;

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use bamboo_agent_core::storage::Storage;
    use bamboo_agent_core::tools::{FunctionCall, ToolCall, ToolResult};
    use bamboo_agent_core::{Message, Session};
    use bamboo_domain::{
        record_permission_audit, resolve_permission_mode, AgentRuntimeState, PermissionAuditSeed,
        PermissionMode, PlanModeState, PlanModeStatus, SessionPermissionMode,
    };
    use bamboo_tools::permission::{
        PermissionConfig, PermissionDecision, PermissionDecisionKind, PermissionDecisionReceipt,
        PermissionMatcher, PermissionMatcherKind, PermissionReasonCode, PermissionRequest,
        PermissionType, RiskLevel,
    };
    use tokio::sync::RwLock;

    use super::*;

    struct ReplayStorage {
        session: RwLock<Option<Session>>,
        fail_load: bool,
    }

    #[async_trait::async_trait]
    impl Storage for ReplayStorage {
        async fn save_session(&self, _session: &Session) -> std::io::Result<()> {
            Ok(())
        }

        async fn load_session(&self, _session_id: &str) -> std::io::Result<Option<Session>> {
            unreachable!("approval replay must use an explicit canonical/control-plane read")
        }

        async fn load_execution_admission_snapshot(
            &self,
            session_id: &str,
        ) -> std::io::Result<Option<Session>> {
            self.load_runtime_control_plane(session_id).await
        }

        async fn load_runtime_control_plane(
            &self,
            _session_id: &str,
        ) -> std::io::Result<Option<Session>> {
            if self.fail_load {
                return Err(std::io::Error::other("injected posture read failure"));
            }
            Ok(self.session.read().await.clone())
        }

        async fn delete_session(&self, _session_id: &str) -> std::io::Result<bool> {
            Ok(false)
        }
    }

    fn session_with_mode(id: &str, mode: SessionPermissionMode) -> Session {
        let mut session = Session::new(id, "model");
        let mut runtime = AgentRuntimeState::new("run");
        runtime.set_permission_mode(mode);
        session.agent_runtime_state = Some(runtime);
        let resolution = resolve_permission_mode(mode, PermissionMode::Default);
        record_permission_audit(
            &mut session.metadata,
            &PermissionAuditSeed::bamboo_runtime(1, resolution),
            Some("2026-07-31T00:00:00Z"),
        )
        .unwrap();
        session
    }

    fn permission_request(
        session_id: &str,
        generation: &str,
        resource: &str,
        decisions: Vec<PermissionDecisionKind>,
    ) -> PermissionRequest {
        PermissionRequest {
            request_id: "call-1".to_string(),
            request_generation: generation.to_string(),
            session_id: session_id.to_string(),
            workspace_path: Some("/workspace/a".to_string()),
            tool_name: "multi_context".to_string(),
            permission_type: PermissionType::ExecuteCommand,
            resource: resource.to_string(),
            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: 0,
            matched_rule: None,
            allowed_decisions: decisions,
            suggested_matchers: vec![PermissionMatcher {
                id: "exact_resource".to_string(),
                kind: PermissionMatcherKind::ExactResource,
                value: resource.to_string(),
            }],
        }
    }

    fn decision_receipt(
        session_id: &str,
        generation: &str,
        decision: PermissionDecisionKind,
    ) -> PermissionDecisionReceipt {
        PermissionDecisionReceipt {
            session_id: session_id.to_string(),
            decision: PermissionDecision {
                request_id: "call-1".to_string(),
                request_generation: generation.to_string(),
                decision,
                matcher_id: matches!(
                    decision,
                    PermissionDecisionKind::AllowSession
                        | PermissionDecisionKind::AllowWorkspace
                        | PermissionDecisionKind::AllowGlobal
                        | PermissionDecisionKind::DenySession
                )
                .then(|| "exact_resource".to_string()),
                expected_policy_revision: None,
                confirm_global: decision == PermissionDecisionKind::AllowGlobal,
            },
            decided_at: chrono::Utc::now(),
        }
    }

    fn approved_replay_session(
        generation: &str,
        resource: &str,
        decision: PermissionDecisionKind,
    ) -> Session {
        approved_replay_session_for("replay", "multi_context", generation, resource, decision)
    }

    fn approved_replay_session_for(
        session_id: &str,
        tool_name: &str,
        generation: &str,
        resource: &str,
        decision: PermissionDecisionKind,
    ) -> Session {
        let mut session = session_with_mode(session_id, SessionPermissionMode::Default);
        session.workspace = Some("/workspace/a".to_string());
        session.add_message(Message::assistant(
            "",
            Some(vec![ToolCall {
                id: "call-1".to_string(),
                tool_type: "function".to_string(),
                function: FunctionCall {
                    name: tool_name.to_string(),
                    arguments: "{}".to_string(),
                },
            }]),
        ));
        let mut request = permission_request(
            &session.id,
            generation,
            resource,
            vec![
                PermissionDecisionKind::AllowOnce,
                PermissionDecisionKind::AllowSession,
                PermissionDecisionKind::AllowWorkspace,
                PermissionDecisionKind::AllowGlobal,
                PermissionDecisionKind::DenyOnce,
                PermissionDecisionKind::DenySession,
            ],
        );
        request.tool_name = tool_name.to_string();
        let receipt = decision_receipt(&session.id, generation, decision);
        let mut result = Message::tool_result("call-1", "Selected response: Approve");
        result.id = "result-1".to_string();
        result.metadata = Some(serde_json::json!({
            "permission_request": request,
            "permission_decision_receipt": receipt,
        }));
        session.add_message(result);
        session.metadata.insert(
            crate::session_app::respond::PERMISSION_REEXECUTE_METADATA_KEY.to_string(),
            "call-1".to_string(),
        );
        session.metadata.insert(
            crate::session_app::respond::PERMISSION_REEXECUTE_GENERATION_METADATA_KEY.to_string(),
            generation.to_string(),
        );
        session.metadata.insert(
            "clarification_resume_pending".to_string(),
            "true".to_string(),
        );
        session.metadata.insert(
            "conclusion_with_options_resume_pending".to_string(),
            "true".to_string(),
        );
        session.metadata.insert(
            "execute.startup_handoff_at".to_string(),
            "2026-08-14T00:00:00Z".to_string(),
        );
        session
    }

    #[tokio::test]
    async fn common_spawn_name_does_not_promote_retained_custom_after_live_ultra_selection() {
        for version in [None, Some(1), Some(2)] {
            for contract in [
                None,
                Some("custom.spawn.v1"),
                Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1),
            ] {
                let mut owned =
                    session_with_mode("replay-original-owner", SessionPermissionMode::Default);
                owned.session_version = version;
                owned.metadata.insert(
                    "permission_reexecute_tool_call_id".into(),
                    "retained-custom".into(),
                );
                owned.add_message(Message::user("keep the original work"));
                let markers = owned.metadata.clone();
                let messages = serde_json::to_value(&owned.messages).unwrap();
                let mut latest = owned.clone();
                latest.set_root_orchestration_only(true).unwrap();
                let storage = ReplayStorage {
                    session: RwLock::new(Some(latest)),
                    fail_load: false,
                };
                let call = ToolCall {
                    id: "retained-custom".into(),
                    tool_type: "function".into(),
                    function: FunctionCall {
                        name: "spawn_session".into(),
                        arguments: "{}".into(),
                    },
                };
                let execution =
                    RetainedToolExecution::new(&call, "spawn_session", true, contract).unwrap();
                let decision = refresh_retained_approval_replay_posture(
                    &storage,
                    &mut owned,
                    PermissionMode::Default,
                    Some("spawn_session"),
                    Some(&execution),
                )
                .await
                .unwrap();
                if contract == Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1) {
                    assert!(matches!(decision, ApprovalReplayDecision::Execute(_)));
                } else {
                    assert_eq!(decision, ApprovalReplayDecision::BlockedByRootToolAuthority);
                }
                assert!(owned.root_orchestration_only_enabled());
                assert_eq!(owned.metadata, markers);
                assert_eq!(serde_json::to_value(&owned.messages).unwrap(), messages);
            }
        }
    }

    #[tokio::test]
    async fn latest_plan_blocks_mutating_replay_before_executor_entry() {
        let mut latest = session_with_mode("plan", SessionPermissionMode::Auto);
        latest.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
            entered_at: chrono::Utc::now(),
            pre_permission_mode: "auto".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::Exploring,
        });
        let mut owned = session_with_mode("plan", SessionPermissionMode::Bypass);
        owned.created_at = latest.created_at;
        let storage: Arc<dyn Storage> = Arc::new(ReplayStorage {
            session: RwLock::new(Some(latest)),
            fail_load: false,
        });

        let decision = refresh_approval_replay_posture(
            storage.as_ref(),
            &mut owned,
            PermissionMode::Default,
            Some("Write"),
        )
        .await
        .unwrap();

        assert_eq!(
            decision,
            ApprovalReplayDecision::BlockedByPlan(
                bamboo_agent_core::tools::ToolExecutionSessionFlags {
                    bypass_permissions: false,
                    auto_approve_permissions: true,
                    plan_read_only: true,
                }
            )
        );
    }

    #[tokio::test]
    async fn latest_auto_and_bypass_map_to_distinct_executor_flags() {
        for (mode, expected_bypass, expected_auto) in [
            (SessionPermissionMode::Auto, false, true),
            (SessionPermissionMode::Bypass, true, false),
        ] {
            let latest = session_with_mode("flags", mode);
            let mut owned = session_with_mode("flags", SessionPermissionMode::Default);
            owned.created_at = latest.created_at;
            let storage: Arc<dyn Storage> = Arc::new(ReplayStorage {
                session: RwLock::new(Some(latest)),
                fail_load: false,
            });

            let decision = refresh_approval_replay_posture(
                storage.as_ref(),
                &mut owned,
                PermissionMode::Default,
                Some("Write"),
            )
            .await
            .unwrap();
            let ApprovalReplayDecision::Execute(flags) = decision else {
                panic!("non-Plan replay must remain executable");
            };
            assert_eq!(flags.bypass_permissions, expected_bypass);
            assert_eq!(flags.auto_approve_permissions, expected_auto);
            assert!(!flags.plan_read_only);
        }
    }

    #[tokio::test]
    async fn supervisor_delegation_first_blocks_implementation_approval_replay_in_both_modes() {
        use bamboo_domain::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        for ultra in [false, true] {
            let mut owned =
                session_with_mode(DEFAULT_SUPERVISOR_SESSION_ID, SessionPermissionMode::Auto);
            owned.authority_identity = SessionAuthorityIdentity::Supervisor {
                incarnation_id: uuid::Uuid::new_v4(),
            };
            owned.set_root_orchestration_only(ultra).unwrap();
            let storage = ReplayStorage {
                session: RwLock::new(Some(owned.clone())),
                fail_load: false,
            };
            for name in [
                "Read",
                "Grep",
                "Glob",
                "GetFileInfo",
                "ViewImage",
                "Write",
                "Edit",
                "exec_command",
                "write_stdin",
                "load_skill",
                "workflow_run",
            ] {
                assert_eq!(
                    refresh_approval_replay_posture(
                        &storage,
                        &mut owned,
                        PermissionMode::Default,
                        Some(name)
                    )
                    .await
                    .unwrap(),
                    ApprovalReplayDecision::BlockedByRootToolAuthority,
                    "{ultra}: {name}"
                );
            }
            for name in ["Plan", "SubAgent", "session_control"] {
                assert!(
                    matches!(
                        refresh_approval_replay_posture(
                            &storage,
                            &mut owned,
                            PermissionMode::Default,
                            Some(name)
                        )
                        .await
                        .unwrap(),
                        ApprovalReplayDecision::Execute(_)
                    ),
                    "{ultra}: {name}"
                );
            }
        }
    }

    #[tokio::test]
    async fn supervisor_retained_once_cannot_override_role_or_consume_replay_markers() {
        use bamboo_domain::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        for ultra in [false, true] {
            let mut owned = approved_replay_session_for(
                DEFAULT_SUPERVISOR_SESSION_ID,
                "exec_command",
                "retained-generation",
                "echo isolated-probe",
                PermissionDecisionKind::AllowOnce,
            );
            owned.authority_identity = SessionAuthorityIdentity::Supervisor {
                incarnation_id: uuid::Uuid::new_v4(),
            };
            owned.set_root_orchestration_only(ultra).unwrap();
            let target =
                find_permission_replay_target(&owned, "call-1", Some("retained-generation"))
                    .unwrap();
            let original =
                ExecutingSupervisorObservation::capture_from_executing_session(&owned).unwrap();
            let record = original.permission_replay_record(
                &owned.id,
                &target.result_message_id,
                &target.tool_call,
                "exec_command",
                "retained-generation",
            );
            owned.messages[target.result_message_index]
                .metadata
                .as_mut()
                .unwrap()["permission.executing_supervisor.v1"] = record;
            assert_eq!(
                validate_permission_replay_authority(&owned, &target, "exec_command").unwrap(),
                Some(original),
                "the retained typed receipt is valid, not the refusal cause"
            );
            let permissions = PermissionConfig::new();
            // An isolated historical in-memory grant is present before refresh.
            restore_permission_replay_authorization(&permissions, &owned, &target, "exec_command")
                .unwrap();
            let storage = ReplayStorage {
                session: RwLock::new(Some(owned.clone())),
                fail_load: false,
            };
            let markers = owned.metadata.clone();
            let history = serde_json::to_value(&owned.messages).unwrap();
            let execution =
                RetainedToolExecution::new(&target.tool_call, "exec_command", true, None).unwrap();
            assert_eq!(
                refresh_retained_approval_replay_posture(
                    &storage,
                    &mut owned,
                    PermissionMode::Default,
                    Some("exec_command"),
                    Some(&execution),
                )
                .await
                .unwrap(),
                ApprovalReplayDecision::BlockedByRootToolAuthority
            );
            assert_eq!(owned.metadata, markers);
            assert_eq!(serde_json::to_value(&owned.messages).unwrap(), history);
            assert!(
                permissions.consume_once_for_generation(
                    &owned.id,
                    "call-1",
                    "retained-generation",
                    PermissionType::ExecuteCommand,
                    "echo isolated-probe",
                ),
                "role refusal must not consume the old grant"
            );
        }
    }

    #[tokio::test]
    async fn durable_root_tool_authority_blocks_denied_replay_owner() {
        let mut owned = session_with_mode("root-replay", SessionPermissionMode::Auto);
        let mut latest = owned.clone();
        latest.set_root_orchestration_only(true).unwrap();
        let storage = ReplayStorage {
            session: RwLock::new(Some(latest)),
            fail_load: false,
        };

        assert_eq!(
            refresh_approval_replay_posture(
                &storage,
                &mut owned,
                PermissionMode::Default,
                Some("Write"),
            )
            .await
            .unwrap(),
            ApprovalReplayDecision::BlockedByRootToolAuthority
        );
        assert!(owned.root_orchestration_only_enabled());
        assert!(matches!(
            refresh_approval_replay_posture(
                &storage,
                &mut owned,
                PermissionMode::Default,
                Some("Read")
            )
            .await
            .unwrap(),
            ApprovalReplayDecision::Execute(_)
        ));
        assert_eq!(
            refresh_approval_replay_posture(&storage, &mut owned, PermissionMode::Default, None)
                .await
                .unwrap(),
            ApprovalReplayDecision::BlockedByUnavailableTool
        );
    }

    #[tokio::test]
    async fn stale_or_corrupt_root_authority_keeps_replay_retryable() {
        for invalid_birth in [true, false] {
            let mut latest = session_with_mode("stale-root-replay", SessionPermissionMode::Auto);
            let mut owned = latest.clone();
            owned.metadata.insert(
                crate::session_app::respond::PERMISSION_REEXECUTE_METADATA_KEY.into(),
                "call-1".into(),
            );
            if invalid_birth {
                latest.created_at += chrono::Duration::microseconds(1);
            } else {
                latest.root_orchestration_only = true;
            }
            let storage = ReplayStorage {
                session: RwLock::new(Some(latest)),
                fail_load: false,
            };
            let before = owned.clone();
            let error = refresh_approval_replay_posture(
                &storage,
                &mut owned,
                PermissionMode::Default,
                Some("Write"),
            )
            .await
            .expect_err("stale Root authority must fail closed");
            assert!(error
                .to_string()
                .contains("Root tool authority failed closed"));
            assert_eq!(owned.created_at, before.created_at);
            assert_eq!(owned.metadata, before.metadata);
        }
    }

    #[tokio::test]
    async fn real_v2_missing_or_corrupt_root_proof_keeps_replay_marker() {
        for corrupt in [false, true] {
            let directory = tempfile::tempdir().unwrap();
            let store = bamboo_storage::SessionStoreV2::new(directory.path().to_path_buf())
                .await
                .unwrap();
            let mut owned = session_with_mode("v2-root-replay", SessionPermissionMode::Auto);
            owned.metadata.insert(
                crate::session_app::respond::PERMISSION_REEXECUTE_METADATA_KEY.into(),
                "call-1".into(),
            );
            store.save_session(&owned).await.unwrap();
            let mut latest = owned.clone();
            latest.set_root_orchestration_only(true).unwrap();
            store.save_session(&latest).await.unwrap();
            let proof = store
                .sessions_root_dir()
                .join(&owned.id)
                .join("root-tool-authority.json");
            if corrupt {
                tokio::fs::write(&proof, b"{").await.unwrap();
            } else {
                tokio::fs::remove_file(&proof).await.unwrap();
            }

            let before = owned.clone();
            let error = refresh_approval_replay_posture(
                &store,
                &mut owned,
                PermissionMode::Default,
                Some("Write"),
            )
            .await
            .expect_err("invalid durable Root proof must fail closed");
            assert!(error.to_string().contains("failed closed"));
            assert_eq!(owned.metadata, before.metadata);
            assert_eq!(
                owned.root_tool_authority_revision,
                before.root_tool_authority_revision
            );
        }
    }

    #[tokio::test]
    async fn missing_or_failed_authoritative_load_fails_closed_without_mutation() {
        for storage in [
            ReplayStorage {
                session: RwLock::new(None),
                fail_load: false,
            },
            ReplayStorage {
                session: RwLock::new(None),
                fail_load: true,
            },
        ] {
            let mut owned = session_with_mode("missing", SessionPermissionMode::Auto);
            let before = owned.clone();
            let error = refresh_approval_replay_posture(
                &storage,
                &mut owned,
                PermissionMode::Default,
                Some("Write"),
            )
            .await
            .expect_err("unavailable durable posture must fail closed");
            assert!(error.to_string().contains("failed closed"));
            assert_eq!(owned.agent_runtime_state, before.agent_runtime_state);
            assert_eq!(owned.metadata, before.metadata);
        }
    }

    #[test]
    fn restart_restores_refreshed_typed_allow_once_and_session_authorizations() {
        for expected_policy_revision in [None, Some(0), Some(1)] {
            let mut allow_once = approved_replay_session(
                "generation-1",
                "context-one",
                PermissionDecisionKind::AllowOnce,
            );
            // A same-generation refresh leaves the original durable request at 0.
            allow_once
                .messages
                .last_mut()
                .unwrap()
                .metadata
                .as_mut()
                .unwrap()["permission_decision_receipt"]["decision"]["expected_policy_revision"] =
                serde_json::json!(expected_policy_revision);
            let target =
                find_permission_replay_target(&allow_once, "call-1", Some("generation-1")).unwrap();
            assert!(
                validate_permission_replay_authority(&allow_once, &target, "multi_context")
                    .unwrap()
                    .is_none()
            );
            let restarted = PermissionConfig::new();
            restore_permission_replay_authorization(
                &restarted,
                &allow_once,
                &target,
                "multi_context",
            )
            .unwrap();
            assert!(!restarted.consume_once_for_generation(
                "replay",
                "call-1",
                "generation-1",
                PermissionType::ExecuteCommand,
                "different-context"
            ));
            assert!(restarted.consume_once_for_generation(
                "replay",
                "call-1",
                "generation-1",
                PermissionType::ExecuteCommand,
                "context-one"
            ));
            assert!(!restarted.consume_once_for_generation(
                "replay",
                "call-1",
                "generation-1",
                PermissionType::ExecuteCommand,
                "context-one"
            ));
        }

        let allow_session = approved_replay_session(
            "generation-session",
            "git status",
            PermissionDecisionKind::AllowSession,
        );
        let target =
            find_permission_replay_target(&allow_session, "call-1", Some("generation-session"))
                .unwrap();
        let restarted = PermissionConfig::new();
        restore_permission_replay_authorization(
            &restarted,
            &allow_session,
            &target,
            "multi_context",
        )
        .unwrap();
        assert!(restarted.is_scoped_session_granted(
            "replay",
            PermissionType::ExecuteCommand,
            "git status"
        ));
    }

    #[test]
    fn typed_replay_rejects_changed_execution_owner_before_restoring_grants() {
        let session = approved_replay_session(
            "generation-owner",
            "git status",
            PermissionDecisionKind::AllowOnce,
        );
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-owner")).unwrap();
        let restarted = PermissionConfig::new();
        let error = restore_permission_replay_authorization(
            &restarted,
            &session,
            &target,
            "new_exact_custom_owner",
        )
        .unwrap_err();
        assert!(error.to_string().contains("approval owner"));
        assert!(!restarted.consume_once_for_generation(
            "replay",
            "call-1",
            "generation-owner",
            PermissionType::ExecuteCommand,
            "git status"
        ));
    }

    #[test]
    fn workspace_replay_uses_only_durable_session_workspace() {
        let session = approved_replay_session(
            "generation-workspace",
            "cargo test",
            PermissionDecisionKind::AllowWorkspace,
        );
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-workspace"))
                .unwrap();
        let restarted = PermissionConfig::new();
        restore_permission_replay_authorization(&restarted, &session, &target, "multi_context")
            .unwrap();
        assert_eq!(
            restarted.session_workspace("replay").as_deref(),
            Some("/workspace/a")
        );

        let mut mismatched = session;
        mismatched.workspace = Some("/workspace/b".to_string());
        let target =
            find_permission_replay_target(&mismatched, "call-1", Some("generation-workspace"))
                .unwrap();
        assert!(restore_permission_replay_authorization(
            &PermissionConfig::new(),
            &mismatched,
            &target,
            "multi_context"
        )
        .is_err());
    }

    #[test]
    fn second_permission_context_reparks_and_accumulates_exact_approvals() {
        let mut session = approved_replay_session(
            "generation-1",
            "context-one",
            PermissionDecisionKind::AllowOnce,
        );
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        let next_request = permission_request(
            &session.id,
            "generation-2",
            "context-two",
            vec![
                PermissionDecisionKind::AllowOnce,
                PermissionDecisionKind::DenyOnce,
            ],
        );
        let next_result = ToolResult {
            success: true,
            result: serde_json::json!({
                "status": "awaiting_permission_approval",
                "question": "Approve context two?",
                "options": ["Approve", "Deny"],
                "allow_custom": false,
                "permission_request": next_request,
            })
            .to_string(),
            display_preference: Some("request_permissions".to_string()),
            images: Vec::new(),
        };

        let reparked =
            repark_permission_replay(&mut session, &target, &next_result, "multi_context")
                .unwrap()
                .expect("second context must park");
        assert_eq!(reparked.question, "Approve context two?");
        assert_eq!(
            session
                .pending_question
                .as_ref()
                .map(|pending| pending.tool_call_id.as_str()),
            Some("call-1")
        );
        for marker in [
            crate::session_app::respond::PERMISSION_REEXECUTE_METADATA_KEY,
            crate::session_app::respond::PERMISSION_REEXECUTE_GENERATION_METADATA_KEY,
            "clarification_resume_pending",
            "conclusion_with_options_resume_pending",
            "execute.startup_handoff_at",
        ] {
            assert!(
                !session.metadata.contains_key(marker),
                "stale marker {marker}"
            );
        }

        let message = session.messages.last_mut().unwrap();
        message.content = "Selected response: Approve".to_string();
        message
            .metadata
            .as_mut()
            .unwrap()
            .as_object_mut()
            .unwrap()
            .insert(
                "permission_decision_receipt".to_string(),
                serde_json::to_value(decision_receipt(
                    "replay",
                    "generation-2",
                    PermissionDecisionKind::AllowOnce,
                ))
                .unwrap(),
            );
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-2")).unwrap();
        let restarted = PermissionConfig::new();
        restore_permission_replay_authorization(&restarted, &session, &target, "multi_context")
            .unwrap();
        for resource in ["context-one", "context-two"] {
            assert!(restarted.consume_once_for_generation(
                "replay",
                "call-1",
                "generation-2",
                PermissionType::ExecuteCommand,
                resource,
            ));
        }
    }

    struct FrozenOwnerProbe {
        names: Vec<&'static str>,
        resolver_queries: std::sync::atomic::AtomicUsize,
    }

    #[test]
    fn retained_framework_replay_needs_actual_instance_not_same_contract_and_keeps_original_bytes()
    {
        use framework_fixture::{park, FixtureTools};
        for version in [None, Some(1), Some(2)] {
            let mut session = Session::new("proof-replay", "model");
            session.session_version = version;
            let call = ToolCall {
                id: "parked-root".into(),
                tool_type: "function".into(),
                function: FunctionCall {
                    name: "default::spawnSession".into(),
                    arguments: "{ \"message\":\"retained original bytes\" }".into(),
                },
            };
            let host = FixtureTools::new(&["spawn_session"]);
            let target = park(
                &mut session,
                &call,
                "spawn_session",
                true,
                Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1),
            );
            let original = serde_json::to_value(&session).unwrap();
            assert_eq!(
                resolve_permission_replay_owner(&session, &target, host.as_ref())
                    .unwrap()
                    .as_deref(),
                Some("spawn_session")
            );
            host.proofs_enabled
                .store(false, std::sync::atomic::Ordering::SeqCst);
            assert_eq!(
                host.execution_contract_for_exact("spawn_session"),
                Some(bamboo_agent_core::tools::FRAMEWORK_ROOT_SPAWN_CONTRACT_V1)
            );
            assert!(
                resolve_permission_replay_owner(&session, &target, host.as_ref())
                    .unwrap()
                    .is_none()
            );
            let shadow = FrozenOwnerProbe {
                names: vec!["spawn_session"],
                resolver_queries: Default::default(),
            };
            assert!(resolve_permission_replay_owner(&session, &target, &shadow)
                .unwrap()
                .is_none());
            assert_eq!(
                shadow
                    .resolver_queries
                    .load(std::sync::atomic::Ordering::SeqCst),
                0
            );
            assert_eq!(target.tool_call(), &call);
            assert_eq!(serde_json::to_value(&session).unwrap(), original);
            assert_eq!(host.gates(), 0);
            assert!(host.invocations().is_empty());
        }
    }

    #[async_trait::async_trait]
    impl ToolExecutor for FrozenOwnerProbe {
        async fn execute(&self, _: &ToolCall) -> Result<ToolResult, bamboo_agent_core::ToolError> {
            panic!("pure owner inspection must not enter any executor")
        }
        fn list_tools(&self) -> Vec<bamboo_agent_core::ToolSchema> {
            self.names.iter().map(|name| serde_json::from_value(serde_json::json!({
                "type":"function", "function":{"name":name, "description":"fixture", "parameters":{"type":"object"}}
            })).unwrap()).collect()
        }
        fn resolve_reference_for_session(&self, _: &Session, _: &str) -> Option<String> {
            self.resolver_queries
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            // Simulate the future fresh-call contract or a newly shadowing
            // exact custom registration. Retained replay must not consult it.
            Some("spawn_session".into())
        }
        fn exact_tool_owner(&self, name: &str) -> Option<&dyn ToolExecutor> {
            self.names
                .contains(&name)
                .then_some(self as &dyn ToolExecutor)
        }
    }

    fn frozen_spawn_session(version: Option<u32>, owner: &str) -> Session {
        let mut session = approved_replay_session(
            "generation-1",
            "first-context",
            PermissionDecisionKind::AllowOnce,
        );
        session.session_version = version;
        let call = session.messages[0]
            .tool_calls
            .as_mut()
            .unwrap()
            .first_mut()
            .unwrap();
        call.function.name = "default::spawnSession".into();
        call.function.arguments = "{ \"prompt\":\"retained bytes\" }".into();
        let call = call.clone();
        let caller = bamboo_domain::SessionCallerReference::from(&session);
        let result = session.messages.last_mut().unwrap();
        result.metadata.as_mut().unwrap()["permission_request"]["tool_name"] =
            serde_json::json!(owner);
        result.metadata.as_mut().unwrap()[PENDING_TOOL_OPERATION_METADATA_KEY] =
            PendingToolOperation::capture(caller, &result.id, &call, owner, "generation-1")
                .metadata_value();
        session
    }

    #[test]
    fn frozen_spawn_owner_is_independent_of_fresh_alias_and_durable_reopen() {
        for version in [None, Some(1), Some(2)] {
            for owner in ["SubAgent", "spawn_session", "spawnSession"] {
                let session = frozen_spawn_session(version, owner);
                let session: Session =
                    serde_json::from_value(serde_json::to_value(session).unwrap()).unwrap();
                let target =
                    find_permission_replay_target(&session, "call-1", Some("generation-1"))
                        .unwrap();
                let probe = FrozenOwnerProbe {
                    names: vec!["SubAgent", "spawn_session", "spawnSession"],
                    resolver_queries: Default::default(),
                };
                if version == Some(2) && owner == "spawn_session" {
                    let before = serde_json::to_value(&session).unwrap();
                    assert!(resolve_permission_replay_owner(&session, &target, &probe).is_err());
                    assert_eq!(serde_json::to_value(&session).unwrap(), before);
                    continue;
                }
                assert_eq!(
                    resolve_permission_replay_owner(&session, &target, &probe)
                        .unwrap()
                        .as_deref(),
                    Some(owner)
                );
                assert_eq!(
                    probe
                        .resolver_queries
                        .load(std::sync::atomic::Ordering::SeqCst),
                    0
                );
                assert_eq!(target.tool_call().function.name, "default::spawnSession");
                assert_eq!(
                    target.tool_call().function.arguments,
                    "{ \"prompt\":\"retained bytes\" }"
                );
            }
        }
    }

    #[test]
    fn replay_caller_requires_its_original_host_record_and_never_recaptures() {
        let session = frozen_spawn_session(None, "SubAgent");
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        let original = bamboo_domain::SessionCallerReference::from(&session);
        assert_eq!(
            restore_permission_replay_caller(&session, &target).unwrap(),
            Some(original)
        );

        let mut replacement = session.clone();
        replacement.created_at += chrono::Duration::seconds(1);
        let before = serde_json::to_value(&replacement).unwrap();
        assert!(restore_permission_replay_caller(&replacement, &target).is_err());
        assert_eq!(serde_json::to_value(&replacement).unwrap(), before);

        let mut legacy = session.clone();
        legacy
            .messages
            .last_mut()
            .unwrap()
            .metadata
            .as_mut()
            .unwrap()
            .as_object_mut()
            .unwrap()
            .remove(PENDING_TOOL_OPERATION_METADATA_KEY);
        assert!(restore_permission_replay_caller(&legacy, &target)
            .unwrap()
            .is_none());
        let mut forged = legacy;
        forged.messages.last_mut().unwrap().content = session
            .messages
            .last()
            .unwrap()
            .metadata
            .as_ref()
            .unwrap()
            .to_string();
        assert!(restore_permission_replay_caller(&forged, &target).is_err());
    }

    #[test]
    fn unknown_legacy_spawn_refuses_without_consuming_markers_or_reinterpreting() {
        for version in [None, Some(1), Some(2)] {
            for typed in [false, true] {
                let mut session = frozen_spawn_session(version, "SubAgent");
                let metadata = session
                    .messages
                    .last_mut()
                    .unwrap()
                    .metadata
                    .as_mut()
                    .unwrap()
                    .as_object_mut()
                    .unwrap();
                metadata.remove(PENDING_TOOL_OPERATION_METADATA_KEY);
                if !typed {
                    metadata.clear();
                }
                let target = find_permission_replay_target(&session, "call-1", None).unwrap();
                let before = serde_json::to_value(&session).unwrap();
                let probe = FrozenOwnerProbe {
                    names: vec!["SubAgent", "spawn_session"],
                    resolver_queries: Default::default(),
                };
                let error = resolve_permission_replay_owner(&session, &target, &probe).unwrap_err();
                assert!(error.to_string().contains("Resend"), "{error}");
                assert_eq!(serde_json::to_value(&session).unwrap(), before);
                assert_eq!(
                    probe
                        .resolver_queries
                        .load(std::sync::atomic::Ordering::SeqCst),
                    0
                );
            }
        }
    }

    #[test]
    fn frozen_owner_missing_or_changed_arguments_never_fall_through_to_new_root() {
        let mut session = frozen_spawn_session(None, "SubAgent");
        let probe = FrozenOwnerProbe {
            names: vec!["spawn_session"],
            resolver_queries: Default::default(),
        };
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        assert!(resolve_permission_replay_owner(&session, &target, &probe)
            .unwrap()
            .is_none());
        session.messages[0].tool_calls.as_mut().unwrap()[0]
            .function
            .arguments = "{\"project_id\":\"unapproved\"}".into();
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        let before = serde_json::to_value(&session).unwrap();
        assert!(resolve_permission_replay_owner(&session, &target, &probe).is_err());
        assert_eq!(serde_json::to_value(&session).unwrap(), before);
        assert_eq!(
            probe
                .resolver_queries
                .load(std::sync::atomic::Ordering::SeqCst),
            0
        );
    }

    #[test]
    fn initial_permission_park_binds_ordinary_call_and_rejects_payload_authority_before_answer() {
        let mut session = Session::new("ordinary", "model");
        let call = ToolCall {
            id: "call-1".into(),
            tool_type: "function".into(),
            function: FunctionCall {
                name: "default::spawnSession".into(),
                arguments: "{ \"prompt\": \"bounded\" }".into(),
            },
        };
        session.add_message(Message::assistant("", Some(vec![call.clone()])));
        let mut request = permission_request(
            &session.id,
            "generation-1",
            "first-context",
            vec![PermissionDecisionKind::AllowOnce],
        );
        request.tool_name = "SubAgent".into();
        let mut result = Message::tool_result(&call.id, serde_json::json!({"status":"awaiting_permission_approval", "permission_request": request}).to_string());
        PermissionReplayOrigin::new(
            Some(bamboo_domain::SessionCallerReference::from(&session)),
            None,
            &session.id,
            &call,
            "SubAgent",
            None,
            true,
        )
        .bind_waiting_message(&mut result);
        assert!(result
            .metadata
            .as_ref()
            .unwrap()
            .get(PENDING_TOOL_OPERATION_METADATA_KEY)
            .is_some());
        session.add_message(result);
        let target = find_permission_replay_target(&session, "call-1", None).unwrap();
        assert!(retained_operation(&session, &target).unwrap().is_some());
        let payload: serde_json::Value =
            serde_json::from_str(&session.messages[1].content).unwrap();
        let mut injected = payload;
        injected[PENDING_TOOL_OPERATION_METADATA_KEY] = serde_json::json!({"version":1});
        session.messages[1].content = injected.to_string();
        let before = serde_json::to_value(&session).unwrap();
        assert!(retained_operation(&session, &target).is_err());
        assert_eq!(serde_json::to_value(&session).unwrap(), before);
    }

    #[test]
    fn second_permission_gate_preserves_frozen_operation_and_rotates_only_generation() {
        let mut session = approved_replay_session(
            "generation-1",
            "context-one",
            PermissionDecisionKind::AllowOnce,
        );
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        let original = PendingToolOperation::capture(
            bamboo_domain::SessionCallerReference::from(&session),
            &session.messages.last().unwrap().id,
            target.tool_call(),
            "multi_context",
            "generation-1",
        );
        session
            .messages
            .last_mut()
            .unwrap()
            .metadata
            .as_mut()
            .unwrap()[PENDING_TOOL_OPERATION_METADATA_KEY] = original.metadata_value();
        let next = ToolResult {
            success: true,
            result: serde_json::json!({"status":"awaiting_permission_approval", "question":"second context", "options":["Approve","Deny"],
                "permission_request":permission_request(&session.id, "generation-2", "context-two", vec![PermissionDecisionKind::AllowOnce])}).to_string(),
            display_preference: Some("request_permissions".into()), images: Vec::new(),
        };
        assert!(
            repark_permission_replay(&mut session, &target, &next, "multi_context")
                .unwrap()
                .is_some()
        );
        let next_target =
            find_permission_replay_target(&session, "call-1", Some("generation-2")).unwrap();
        assert_eq!(
            retained_operation(&session, &next_target)
                .unwrap()
                .unwrap()
                .metadata_value(),
            original.for_generation("generation-2").metadata_value()
        );
        assert!(retained_operation(&session, &target).is_err());
    }

    #[test]
    fn legacy_supervisor_exact_binding_is_read_without_migration_or_live_alias_resolution() {
        let mut session = frozen_spawn_session(Some(1), "SubAgent");
        session.id = bamboo_domain::DEFAULT_SUPERVISOR_SESSION_ID.into();
        session.root_session_id = session.id.clone();
        session.authority_identity = bamboo_domain::SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        let target =
            find_permission_replay_target(&session, "call-1", Some("generation-1")).unwrap();
        let observation =
            ExecutingSupervisorObservation::capture_from_executing_session(&session).unwrap();
        let record = observation.permission_replay_record(
            &session.id,
            &session.messages.last().unwrap().id,
            target.tool_call(),
            "SubAgent",
            "generation-1",
        );
        let id = session.id.clone();
        let metadata = session
            .messages
            .last_mut()
            .unwrap()
            .metadata
            .as_mut()
            .unwrap();
        metadata
            .as_object_mut()
            .unwrap()
            .remove(PENDING_TOOL_OPERATION_METADATA_KEY);
        metadata["permission_request"]["session_id"] = serde_json::json!(&id);
        metadata["permission_decision_receipt"]["session_id"] = serde_json::json!(&id);
        metadata[ExecutingSupervisorObservation::PERMISSION_REPLAY_METADATA_KEY] = record;
        let before = serde_json::to_value(&session).unwrap();
        let probe = FrozenOwnerProbe {
            names: vec!["SubAgent", "spawn_session"],
            resolver_queries: Default::default(),
        };
        assert_eq!(
            resolve_permission_replay_owner(&session, &target, &probe)
                .unwrap()
                .as_deref(),
            Some("SubAgent")
        );
        assert_eq!(
            validate_permission_replay_authority(&session, &target, "SubAgent").unwrap(),
            Some(observation)
        );
        assert_eq!(
            probe
                .resolver_queries
                .load(std::sync::atomic::Ordering::SeqCst),
            0
        );
        assert_eq!(serde_json::to_value(&session).unwrap(), before);
    }
}