mentra 0.27.0

An agent runtime for tool-using LLM applications
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
mod pattern;

use std::cmp::Ordering as CmpOrdering;
use std::collections::HashMap;
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicU64, Ordering},
};
use std::time::Duration;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;

use super::{
    event::{PermissionRuleScope, SessionEvent},
    handle::SessionPermissionHandle,
};
use crate::{
    runtime::RuntimeError,
    tool::{
        ToolAuthorizationDecision, ToolAuthorizationOutcome, ToolAuthorizationRequest,
        ToolAuthorizer,
    },
};

/// A pending permission request awaiting a UI decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PermissionRequest {
    pub request_id: String,
    pub tool_call_id: String,
    pub tool_name: String,
    pub description: String,
    /// JSON-encoded preview data. Stored as `String` because
    /// `serde_json::Value` does not implement `Eq`.
    pub preview: String,
}

/// What a refusal says when the deciding layer offered no reason of its own.
const DENIED_BY_SESSION_APPROVER: &str = "denied by session approver";

/// What a remembered refusal says when the rule it was stored as kept no reason.
const BLOCKED_BY_REMEMBERED_RULE: &str = "blocked by remembered session rule";

/// What the model reads when a remembered rule refuses a call.
///
/// The words the host first refused with come back in front, because they are
/// the part that says what to do instead; the rest says the answer is standing,
/// because a model told only that something was blocked asks again, and asking
/// again is the one thing that cannot change a remembered rule.
fn remembered_denial(reason: Option<&str>) -> String {
    match reason {
        Some(reason) => format!(
            "{reason} — remembered from an earlier refusal, so asking again will not change it"
        ),
        None => BLOCKED_BY_REMEMBERED_RULE.to_string(),
    }
}

/// The response to a permission request from the UI layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionDecision {
    pub allow: bool,
    pub remember_as: Option<PermissionRuleScope>,
    /// Why the call was refused, in the words the model will read.
    ///
    /// A denial reaches the model as the tool's result, so what it says
    /// changes what the model does next: told only that something was denied
    /// it tries the write again, told that this run does not allow writes it
    /// stops and reports. Set it with [`PermissionDecision::with_reason`].
    /// Ignored when `allow` is set, and a refusal that leaves it unset still
    /// reads "denied by session approver" as it always has.
    pub reason: Option<String>,
}

impl PermissionDecision {
    /// Allow the tool call without remembering.
    pub fn allow() -> Self {
        Self {
            allow: true,
            remember_as: None,
            reason: None,
        }
    }

    /// Deny the tool call without remembering.
    pub fn deny() -> Self {
        Self {
            allow: false,
            remember_as: None,
            reason: None,
        }
    }

    /// Allow the tool call and remember the decision for the given scope.
    pub fn allow_and_remember(scope: PermissionRuleScope) -> Self {
        Self {
            allow: true,
            remember_as: Some(scope),
            reason: None,
        }
    }

    /// Deny the tool call and remember the decision for the given scope.
    pub fn deny_and_remember(scope: PermissionRuleScope) -> Self {
        Self {
            allow: false,
            remember_as: Some(scope),
            reason: None,
        }
    }

    /// The same decision, carrying the reason the model should read.
    ///
    /// Only refusals have anything to explain: an allowed call explains
    /// itself by happening.
    pub fn with_reason(self, reason: impl Into<String>) -> Self {
        Self {
            reason: Some(reason.into()),
            ..self
        }
    }
}

/// Key for looking up remembered permission rules.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RuleKey {
    pub tool_name: String,
    /// Wildcard pattern matched against the JSON encoding of the call's
    /// structured input, or `None` to answer every call to the tool.
    ///
    /// Matched as data rather than as a path: `*` matches any run of
    /// characters including `/`, `**` means the same as `*`, `?` matches one
    /// character, and every other character — JSON's braces, brackets and
    /// commas included — is literal. Matching is anchored, so a rule about a
    /// fragment is written `*fragment*`.
    ///
    /// Path-glob semantics were wrong here: `*` stopped at `/`, so any preview
    /// carrying an absolute path made every key serialized after it
    /// unmatchable, and a rule written against one silently answered nothing.
    pub pattern: Option<String>,
}

/// Exact in-memory identity of one remembered permission rule.
///
/// Scope is part of the address rather than metadata on the stored value, so
/// the same tool and pattern can carry independent process, session, project,
/// and global answers. Construct this from a listed [`RememberedRule`] with
/// `PermissionRuleAddress::from(&rule)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PermissionRuleAddress {
    pub scope: PermissionRuleScope,
    pub key: RuleKey,
}

/// A remembered permission rule that was previously decided by the user.
///
/// Process rules live only in a [`SessionPermissionHandle`]'s in-memory
/// binding. Session, project, and global rules are stored in the runtime's
/// [`PermissionRuleStore`](crate::PermissionRuleStore).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RememberedRule {
    pub key: RuleKey,
    pub allow: bool,
    pub scope: PermissionRuleScope,
    /// Why the remembered refusal refused, in the words the model will read.
    ///
    /// A remembered rule answers a later `Prompt` without reaching the session
    /// approver again, so a rule that keeps the verdict and drops the reason
    /// lets the host explain itself exactly once: every repeat after that reads
    /// only that something was blocked. Written from
    /// [`PermissionDecision::reason`] when the remembered decision is a
    /// refusal, and left unset for an allow, which explains itself by
    /// happening. A refusal that kept no reason still reads "blocked by
    /// remembered session rule" as it always has.
    ///
    /// `serde(default)` keeps rules persisted before this field existed
    /// deserializing unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl From<&RememberedRule> for PermissionRuleAddress {
    fn from(rule: &RememberedRule) -> Self {
        Self {
            scope: rule.scope,
            key: rule.key.clone(),
        }
    }
}

const SCOPE_PRECEDENCE: [PermissionRuleScope; 4] = [
    PermissionRuleScope::Process,
    PermissionRuleScope::Session,
    PermissionRuleScope::Project,
    PermissionRuleScope::Global,
];

fn scope_rank(scope: PermissionRuleScope) -> u8 {
    match scope {
        PermissionRuleScope::Process => 0,
        PermissionRuleScope::Session => 1,
        PermissionRuleScope::Project => 2,
        PermissionRuleScope::Global => 3,
    }
}

fn compare_rule_keys(left: &RuleKey, right: &RuleKey) -> CmpOrdering {
    left.tool_name
        .cmp(&right.tool_name)
        .then_with(|| left.pattern.cmp(&right.pattern))
}

fn compare_rules_for_listing(left: &RememberedRule, right: &RememberedRule) -> CmpOrdering {
    scope_rank(left.scope)
        .cmp(&scope_rank(right.scope))
        .then_with(|| left.key.tool_name.cmp(&right.key.tool_name))
        .then_with(|| match (&left.key.pattern, &right.key.pattern) {
            // Patterned rules are considered before the bare fallback within
            // one scope and tool, matching lookup semantics.
            (Some(_), None) => CmpOrdering::Less,
            (None, Some(_)) => CmpOrdering::Greater,
            (left, right) => left.cmp(right),
        })
}

fn compare_pattern_candidates(
    left: (&PermissionRuleAddress, &RememberedRule),
    right: (&PermissionRuleAddress, &RememberedRule),
) -> CmpOrdering {
    // `false < true`, so a denial wins an overlapping-pattern tie. Exact
    // addresses are unique; stable RuleKey order breaks every remaining tie
    // without depending on HashMap iteration order.
    left.1
        .allow
        .cmp(&right.1.allow)
        .then_with(|| compare_rule_keys(&left.0.key, &right.0.key))
}

/// Thread-safe in-memory store for remembered permission rules.
///
/// Rules are addressed by [`PermissionRuleAddress`]. Lookup considers scopes
/// in process, session, project, then global order. Within one scope a matching
/// pattern precedes the bare rule; overlapping patterns prefer a denial and
/// then stable [`RuleKey`] order.
#[derive(Debug, Clone)]
pub struct RuleStore {
    inner: Arc<Mutex<HashMap<PermissionRuleAddress, RememberedRule>>>,
}

impl Default for RuleStore {
    fn default() -> Self {
        Self::new()
    }
}

impl RuleStore {
    /// Creates an empty rule store.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Adds or overwrites the rule at its exact scope and key.
    pub fn add_rule(&self, rule: RememberedRule) {
        let mut rules = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        rules.insert(PermissionRuleAddress::from(&rule), rule);
    }

    /// Checks whether a tool is allowed by a remembered rule.
    ///
    /// Scopes are considered in process, session, project, then global order.
    /// Within one scope, pattern rules are matched against `input_json` with
    /// the wildcard syntax documented on [`RuleKey::pattern`] and take
    /// precedence over the bare (no-pattern) rule. Overlapping patterns prefer
    /// denial, then stable key order. Returns `Some(true)` if allowed,
    /// `Some(false)` if denied, or `None` if no matching rule exists.
    /// Use [`RuleStore::matching_rule`] when the rule's own reason matters.
    pub fn check(&self, tool_name: &str, input_json: Option<&str>) -> Option<bool> {
        self.matching_rule(tool_name, input_json)
            .map(|rule| rule.allow)
    }

    /// The remembered rule that answers a call, if one does.
    ///
    /// Matches exactly as [`RuleStore::check`] does and hands back the whole
    /// rule, so a refusal can restate the reason it was remembered with rather
    /// than only its verdict.
    pub fn matching_rule(
        &self,
        tool_name: &str,
        input_json: Option<&str>,
    ) -> Option<RememberedRule> {
        let rules = self.inner.lock().unwrap_or_else(|e| e.into_inner());

        for scope in SCOPE_PRECEDENCE {
            if let Some((_, rule)) = rules
                .iter()
                .filter(|(address, _)| {
                    address.scope == scope
                        && address.key.tool_name == tool_name
                        && address.key.pattern.as_deref().is_some_and(|rule_pattern| {
                            input_json.is_some_and(|json| pattern::matches(rule_pattern, json))
                        })
                })
                .min_by(|left, right| compare_pattern_candidates(*left, *right))
            {
                return Some(rule.clone());
            }

            if let Some((_, rule)) = rules.iter().find(|(address, _)| {
                address.scope == scope
                    && address.key.tool_name == tool_name
                    && address.key.pattern.is_none()
            }) {
                return Some(rule.clone());
            }
        }

        None
    }

    /// Returns all remembered rules in deterministic lookup-oriented order.
    ///
    /// Process rules precede session, project, and global rules. Within one
    /// scope, tools and patterns use stable lexical ordering, with patterned
    /// rules before a tool's bare fallback.
    pub fn rules(&self) -> Vec<RememberedRule> {
        let rules = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        let mut listed: Vec<_> = rules.values().cloned().collect();
        listed.sort_by(compare_rules_for_listing);
        listed
    }

    /// Revokes the rule at `address`, returning whether one existed.
    pub fn revoke_rule(&self, address: &PermissionRuleAddress) -> bool {
        let mut rules = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        rules.remove(address).is_some()
    }

    /// Removes every rule at `scope`, returning how many were removed.
    pub fn clear_scope(&self, scope: PermissionRuleScope) -> usize {
        let mut rules = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        let before = rules.len();
        rules.retain(|address, _| address.scope != scope);
        before - rules.len()
    }
}

/// Thread-safe store for pending permission requests that can be resolved later.
#[derive(Debug, Clone, Default)]
pub(crate) struct PendingPermissionStore {
    inner: Arc<Mutex<HashMap<String, StoredPendingPermission>>>,
    next_generation: Arc<AtomicU64>,
}

impl PendingPermissionStore {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    #[must_use = "the wait guard must live until the permission future completes"]
    #[cfg(test)]
    pub(crate) fn insert(
        &self,
        request_id: String,
        entry: PendingPermissionEntry,
    ) -> PendingPermissionWaitGuard {
        let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
        self.insert_with_generation(request_id, generation, entry)
    }

    pub(crate) fn insert_unique(
        &self,
        tool_call_id: &str,
        entry: PendingPermissionEntry,
    ) -> (String, PendingPermissionWaitGuard) {
        let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
        let request_id = format!("perm-{tool_call_id}-{generation:016x}");
        let guard = self.insert_with_generation(request_id.clone(), generation, entry);
        (request_id, guard)
    }

    fn insert_with_generation(
        &self,
        request_id: String,
        generation: u64,
        entry: PendingPermissionEntry,
    ) -> PendingPermissionWaitGuard {
        let lifecycle = Arc::new(Mutex::new(true));
        let stored = StoredPendingPermission {
            generation,
            lifecycle: lifecycle.clone(),
            entry,
        };
        let replaced = {
            let mut pending = self.inner.lock().unwrap_or_else(|e| e.into_inner());
            pending.insert(request_id.clone(), stored)
        };
        if let Some(replaced) = replaced {
            *replaced.lifecycle.lock().unwrap_or_else(|e| e.into_inner()) = false;
        }
        PendingPermissionWaitGuard {
            store: self.clone(),
            request_id,
            generation,
            lifecycle,
        }
    }

    pub(crate) fn claim(&self, request_id: &str) -> Option<ClaimedPendingPermission> {
        let mut pending = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        pending
            .remove(request_id)
            .map(ClaimedPendingPermission::from)
    }

    pub(crate) fn restore(&self, request_id: String, claim: ClaimedPendingPermission) -> bool {
        let mut pending = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        if pending.contains_key(&request_id) {
            return false;
        }
        pending.insert(request_id, claim.into());
        true
    }

    fn cancel_if_generation(&self, request_id: &str, generation: u64) {
        let mut pending = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        if pending
            .get(request_id)
            .is_some_and(|entry| entry.generation == generation)
        {
            pending.remove(request_id);
        }
    }

    #[cfg(test)]
    pub(crate) fn contains(&self, request_id: &str) -> bool {
        let pending = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        pending.contains_key(request_id)
    }
}

#[derive(Debug)]
struct StoredPendingPermission {
    generation: u64,
    lifecycle: Arc<Mutex<bool>>,
    entry: PendingPermissionEntry,
}

pub(crate) struct ClaimedPendingPermission {
    pub(crate) generation: u64,
    pub(crate) lifecycle: Arc<Mutex<bool>>,
    pub(crate) entry: PendingPermissionEntry,
}

impl From<StoredPendingPermission> for ClaimedPendingPermission {
    fn from(stored: StoredPendingPermission) -> Self {
        Self {
            generation: stored.generation,
            lifecycle: stored.lifecycle,
            entry: stored.entry,
        }
    }
}

impl From<ClaimedPendingPermission> for StoredPendingPermission {
    fn from(claim: ClaimedPendingPermission) -> Self {
        Self {
            generation: claim.generation,
            lifecycle: claim.lifecycle,
            entry: claim.entry,
        }
    }
}

pub(crate) struct PendingPermissionWaitGuard {
    store: PendingPermissionStore,
    request_id: String,
    generation: u64,
    lifecycle: Arc<Mutex<bool>>,
}

impl Drop for PendingPermissionWaitGuard {
    fn drop(&mut self) {
        let mut active = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
        if !*active {
            return;
        }
        *active = false;
        self.store
            .cancel_if_generation(&self.request_id, self.generation);
    }
}

/// Internal entry tracking a pending permission with its oneshot response channel.
#[derive(Debug)]
pub(crate) struct PendingPermissionEntry {
    pub(crate) tool_call_id: String,
    pub(crate) tool_name: String,
    pub(crate) sender: oneshot::Sender<PermissionDecision>,
}

/// Session-scoped wrapper around the runtime tool authorizer.
///
/// This is the bridge that first asks the current authorizer, then lets a
/// remembered rule from the session's live binding or runtime store answer
/// only its `Prompt` outcome. Durable-store failures fail closed. An
/// authoritative `Allow` or `Deny` is returned unchanged. A prompt with no
/// remembered answer becomes a typed `SessionEvent::PermissionRequested` event
/// and suspends execution until a matching decision arrives.
#[derive(Clone)]
pub(crate) struct SessionToolAuthorizer {
    inner: Option<Arc<dyn ToolAuthorizer>>,
    permissions: SessionPermissionHandle,
}

impl SessionToolAuthorizer {
    pub(crate) fn new(
        inner: Option<Arc<dyn ToolAuthorizer>>,
        permissions: SessionPermissionHandle,
    ) -> Self {
        Self { inner, permissions }
    }
}

#[async_trait]
impl ToolAuthorizer for SessionToolAuthorizer {
    async fn authorize(
        &self,
        request: &ToolAuthorizationRequest,
    ) -> Result<ToolAuthorizationDecision, RuntimeError> {
        let Some(inner) = self.inner.as_ref().cloned() else {
            return Ok(ToolAuthorizationDecision::allow());
        };

        // Sample one authorizer for this call before awaiting it. A stateful
        // session policy may change while a permission dialog is open; that
        // change governs the next call, while this call keeps the policy that
        // decided it needed a prompt.
        let decision = inner.authorize(request).await?;
        if decision.outcome != ToolAuthorizationOutcome::Prompt {
            return Ok(decision);
        }

        let input_json = serde_json::to_string(&request.preview.structured_input).ok();
        if let Some(rule) = self
            .permissions
            .matching_rule(&request.tool_name, input_json.as_deref())?
        {
            return Ok(if rule.allow {
                ToolAuthorizationDecision::allow()
            } else {
                // The session approver is not consulted again, so the rule is
                // the only place the original reason can still come from.
                ToolAuthorizationDecision::deny(remembered_denial(rule.reason.as_deref()))
            });
        }

        let description = decision
            .reason
            .clone()
            .unwrap_or_else(|| format!("Approval required for {}", request.tool_name));
        let preview = serde_json::to_string(&request.preview.structured_input)
            .unwrap_or_else(|_| "{}".to_string());
        let (sender, receiver) = oneshot::channel();

        let (request_id, _pending_guard) = self.permissions.pending_permissions().insert_unique(
            &request.tool_call_id,
            PendingPermissionEntry {
                tool_call_id: request.tool_call_id.clone(),
                tool_name: request.tool_name.clone(),
                sender,
            },
        );

        let _ = self
            .permissions
            .event_tx()
            .send(SessionEvent::PermissionRequested {
                request_id: request_id.clone(),
                tool_call_id: request.tool_call_id.clone(),
                tool_name: request.tool_name.clone(),
                description,
                preview,
                // Nothing downstream can work this out again: this is the last
                // layer holding the preview the authorizer was given.
                classification: Some(request.preview.classification()),
            });

        let resolved = receiver
            .await
            .unwrap_or_else(|_| PermissionDecision::deny());
        Ok(if resolved.allow {
            ToolAuthorizationDecision::allow()
        } else {
            // Whoever answered gets to say why, because that text is what the
            // model reads; a refusal that explains nothing keeps the wording
            // this has always used.
            ToolAuthorizationDecision::deny(
                resolved
                    .reason
                    .unwrap_or_else(|| DENIED_BY_SESSION_APPROVER.to_string()),
            )
        })
    }

    fn timeout(&self) -> Option<Duration> {
        self.inner
            .as_ref()
            .and_then(|authorizer| authorizer.timeout())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
    use tokio::sync::broadcast;

    use crate::runtime::{PermissionRuleStore, RuntimeStore, VolatileRuntimeStore};
    use crate::tool::{
        ToolApprovalCategory, ToolAuthorizationPreview, ToolCapability, ToolClassification,
        ToolDurability, ToolExecutionCategory, ToolSideEffectLevel,
    };

    #[derive(Clone)]
    struct PromptAuthorizer;

    #[async_trait]
    impl ToolAuthorizer for PromptAuthorizer {
        async fn authorize(
            &self,
            _request: &ToolAuthorizationRequest,
        ) -> Result<ToolAuthorizationDecision, RuntimeError> {
            Ok(ToolAuthorizationDecision::prompt("needs manual review"))
        }
    }

    #[derive(Clone)]
    struct CountingAuthorizer {
        outcome: ToolAuthorizationOutcome,
        calls: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl ToolAuthorizer for CountingAuthorizer {
        async fn authorize(
            &self,
            _request: &ToolAuthorizationRequest,
        ) -> Result<ToolAuthorizationDecision, RuntimeError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(match self.outcome {
                ToolAuthorizationOutcome::Allow => ToolAuthorizationDecision::allow(),
                ToolAuthorizationOutcome::Prompt => {
                    ToolAuthorizationDecision::prompt("needs manual review")
                }
                ToolAuthorizationOutcome::Deny => {
                    ToolAuthorizationDecision::deny("the current policy refuses")
                }
            })
        }
    }

    #[derive(Clone)]
    struct SwitchingAuthorizer {
        outcome: Arc<AtomicU8>,
        calls: Arc<AtomicUsize>,
    }

    impl SwitchingAuthorizer {
        const PROMPT: u8 = 0;
        const DENY: u8 = 1;

        fn prompting() -> Self {
            Self {
                outcome: Arc::new(AtomicU8::new(Self::PROMPT)),
                calls: Arc::new(AtomicUsize::new(0)),
            }
        }

        fn deny(&self) {
            self.outcome.store(Self::DENY, Ordering::SeqCst);
        }
    }

    #[async_trait]
    impl ToolAuthorizer for SwitchingAuthorizer {
        async fn authorize(
            &self,
            _request: &ToolAuthorizationRequest,
        ) -> Result<ToolAuthorizationDecision, RuntimeError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(if self.outcome.load(Ordering::SeqCst) == Self::PROMPT {
                ToolAuthorizationDecision::prompt("needs manual review")
            } else {
                ToolAuthorizationDecision::deny("the current policy refuses")
            })
        }
    }

    fn sample_request() -> ToolAuthorizationRequest {
        ToolAuthorizationRequest {
            agent_id: "agent-1".to_string(),
            agent_name: "agent".to_string(),
            model: "mock-model".to_string(),
            history_len: 3,
            tool_call_id: "tool-1".to_string(),
            tool_name: "shell".to_string(),
            preview: ToolAuthorizationPreview {
                working_directory: std::env::temp_dir(),
                capabilities: vec![ToolCapability::ProcessExec],
                side_effect_level: ToolSideEffectLevel::Process,
                durability: ToolDurability::Ephemeral,
                execution_category: ToolExecutionCategory::ExclusiveLocalMutation,
                approval_category: ToolApprovalCategory::Process,
                raw_input: json!({ "command": "cargo test" }),
                structured_input: json!({ "kind": "shell", "command": "cargo test" }),
            },
        }
    }

    fn test_authorizer(
        inner: Option<Arc<dyn ToolAuthorizer>>,
        rules: RuleStore,
    ) -> (
        SessionToolAuthorizer,
        broadcast::Receiver<SessionEvent>,
        PendingPermissionStore,
        SessionPermissionHandle,
    ) {
        let store = VolatileRuntimeStore::new();
        let context = crate::runtime::PermissionRuleContext {
            session_id: "agent-1".to_owned(),
            project_id: None,
        };
        for rule in rules.rules() {
            store
                .upsert_rule(&context, &rule)
                .expect("seed remembered rule");
        }
        let store: Arc<dyn RuntimeStore> = Arc::new(store);
        let (event_tx, rx) = broadcast::channel(8);
        let pending = PendingPermissionStore::new();
        let permissions = SessionPermissionHandle::new(
            "agent-1".to_owned(),
            None,
            store,
            event_tx,
            pending.clone(),
        );
        (
            SessionToolAuthorizer::new(inner, permissions.clone()),
            rx,
            pending,
            permissions,
        )
    }

    #[tokio::test]
    async fn a_stale_wait_guard_cannot_remove_a_reused_request_id() {
        let pending = PendingPermissionStore::new();
        let (first_sender, first_receiver) = oneshot::channel();
        let first_guard = pending.insert(
            "perm-reused".to_owned(),
            PendingPermissionEntry {
                tool_call_id: "call-first".to_owned(),
                tool_name: "shell".to_owned(),
                sender: first_sender,
            },
        );
        let (second_sender, second_receiver) = oneshot::channel();
        let second_guard = pending.insert(
            "perm-reused".to_owned(),
            PendingPermissionEntry {
                tool_call_id: "call-second".to_owned(),
                tool_name: "shell".to_owned(),
                sender: second_sender,
            },
        );

        assert!(
            first_receiver.await.is_err(),
            "replacement closes the old wait"
        );
        drop(first_guard);
        assert!(
            pending.contains("perm-reused"),
            "the old generation cannot remove the replacement"
        );
        pending
            .claim("perm-reused")
            .expect("claim replacement")
            .entry
            .sender
            .send(PermissionDecision::allow())
            .expect("resolve replacement");
        assert!(second_receiver.await.expect("receive replacement").allow);
        drop(second_guard);
        assert!(!pending.contains("perm-reused"));
    }

    #[tokio::test]
    async fn a_stale_emitted_id_cannot_resolve_a_new_generation() {
        let (_authorizer, _rx, pending, permissions) = test_authorizer(None, RuleStore::new());
        let (first_sender, first_receiver) = oneshot::channel();
        let (first_id, first_guard) = pending.insert_unique(
            "same-tool-call-id",
            PendingPermissionEntry {
                tool_call_id: "same-tool-call-id".to_owned(),
                tool_name: "shell".to_owned(),
                sender: first_sender,
            },
        );
        drop(first_guard);
        assert!(first_receiver.await.is_err());

        let (second_sender, second_receiver) = oneshot::channel();
        let (second_id, _second_guard) = pending.insert_unique(
            "same-tool-call-id",
            PendingPermissionEntry {
                tool_call_id: "same-tool-call-id".to_owned(),
                tool_name: "files".to_owned(),
                sender: second_sender,
            },
        );
        assert_ne!(first_id, second_id);

        assert!(
            permissions
                .resolve_permission(
                    &first_id,
                    PermissionDecision::allow_and_remember(PermissionRuleScope::Global),
                )
                .is_err(),
            "the first event id cannot answer the replacement request"
        );
        assert!(permissions.remembered_rules().unwrap().is_empty());
        permissions
            .resolve_permission(&second_id, PermissionDecision::deny())
            .expect("the live event id resolves its own request");
        assert!(!second_receiver.await.expect("receive live decision").allow);
    }

    #[tokio::test]
    async fn session_tool_authorizer_emits_permission_request_and_waits() {
        let (authorizer, mut rx, pending, _) =
            test_authorizer(Some(Arc::new(PromptAuthorizer)), RuleStore::new());
        let request = sample_request();

        let authorize_task = tokio::spawn({
            let authorizer = authorizer.clone();
            let request = request.clone();
            async move { authorizer.authorize(&request).await.unwrap() }
        });

        let event = tokio::time::timeout(Duration::from_millis(200), rx.recv())
            .await
            .expect("permission request should arrive")
            .expect("event should be present");

        let request_id = match event {
            SessionEvent::PermissionRequested {
                request_id,
                tool_call_id,
                tool_name,
                ..
            } => {
                assert_eq!(tool_call_id, "tool-1");
                assert_eq!(tool_name, "shell");
                request_id
            }
            other => panic!("expected PermissionRequested, got {other:?}"),
        };

        assert!(pending.contains(&request_id));
        let entry = pending
            .claim(&request_id)
            .expect("pending permission should be registered")
            .entry;
        entry
            .sender
            .send(PermissionDecision::allow())
            .expect("decision send should succeed");

        let decision = tokio::time::timeout(Duration::from_millis(200), authorize_task)
            .await
            .expect("authorization should resume")
            .expect("task should succeed");
        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
    }

    /// The classification is the one thing on this event nothing downstream
    /// can recompute: the session authorizer is the last layer holding the
    /// preview, and everything past it sees only the event.
    #[tokio::test]
    async fn the_emitted_request_carries_the_classification_the_authorizer_saw() {
        let (authorizer, mut rx, pending, _) =
            test_authorizer(Some(Arc::new(PromptAuthorizer)), RuleStore::new());
        let request = sample_request();

        let authorize_task = tokio::spawn({
            let authorizer = authorizer.clone();
            let request = request.clone();
            async move { authorizer.authorize(&request).await.unwrap() }
        });

        let event = tokio::time::timeout(Duration::from_millis(200), rx.recv())
            .await
            .expect("permission request should arrive")
            .expect("event should be present");
        let SessionEvent::PermissionRequested {
            request_id,
            classification,
            ..
        } = event
        else {
            panic!("expected PermissionRequested, got {event:?}");
        };

        assert_eq!(
            classification.as_ref(),
            Some(&ToolClassification::from(&request.preview)),
            "every classification field the authorizer was given has to reach the event"
        );
        assert_eq!(
            classification.map(|classification| classification.side_effect_level),
            Some(ToolSideEffectLevel::Process),
            "a host reading only the event can tell a process launch from a local write"
        );

        pending
            .claim(&request_id)
            .expect("pending permission should be registered")
            .entry
            .sender
            .send(PermissionDecision::allow())
            .expect("decision send should succeed");
        authorize_task.await.expect("task should succeed");
    }

    /// Runs one authorize-and-resolve round trip, answering with `decision`,
    /// and returns what the authorizer handed back to the tool loop.
    async fn resolved_with(decision: PermissionDecision) -> ToolAuthorizationDecision {
        let (authorizer, mut rx, pending, _) =
            test_authorizer(Some(Arc::new(PromptAuthorizer)), RuleStore::new());

        let authorize_task = tokio::spawn({
            let authorizer = authorizer.clone();
            async move { authorizer.authorize(&sample_request()).await.unwrap() }
        });

        let event = tokio::time::timeout(Duration::from_millis(200), rx.recv())
            .await
            .expect("permission request should arrive")
            .expect("event should be present");
        let SessionEvent::PermissionRequested { request_id, .. } = &event else {
            panic!("expected PermissionRequested, got {event:?}");
        };

        pending
            .claim(request_id)
            .expect("pending permission should be registered")
            .entry
            .sender
            .send(decision)
            .expect("decision send should succeed");

        tokio::time::timeout(Duration::from_millis(200), authorize_task)
            .await
            .expect("authorization should resume")
            .expect("task should succeed")
    }

    #[tokio::test]
    async fn a_reasoned_denial_carries_its_words_to_the_tool_result() {
        // The reason becomes the tool result the model reads, so anything
        // rewritten or dropped on the way is a reason it never sees.
        let decision =
            resolved_with(PermissionDecision::deny().with_reason("this run does not allow writes"))
                .await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(
            decision.reason.as_deref(),
            Some("this run does not allow writes")
        );
    }

    #[tokio::test]
    async fn a_denial_with_nothing_to_say_keeps_the_standing_wording() {
        let decision = resolved_with(PermissionDecision::deny()).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(decision.reason.as_deref(), Some(DENIED_BY_SESSION_APPROVER));
    }

    #[tokio::test]
    async fn a_reason_on_an_allowed_call_changes_nothing() {
        let decision = resolved_with(PermissionDecision::allow().with_reason("ignored")).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
        assert_eq!(
            decision.reason, None,
            "an allowed call has nothing to explain"
        );
    }

    /// Answers one prompted authorize call from `store`.
    async fn answered_by_rule(store: RuleStore) -> ToolAuthorizationDecision {
        let (authorizer, _rx, _, _) = test_authorizer(Some(Arc::new(PromptAuthorizer)), store);

        authorizer
            .authorize(&sample_request())
            .await
            .expect("authorization should resolve")
    }

    /// A bare `shell` rule for the session, remembered with `reason` or without.
    fn shell_rule(allow: bool, reason: Option<&str>) -> RememberedRule {
        rule_at(PermissionRuleScope::Session, "shell", None, allow, reason)
    }

    fn rule_at(
        scope: PermissionRuleScope,
        tool_name: &str,
        pattern: Option<&str>,
        allow: bool,
        reason: Option<&str>,
    ) -> RememberedRule {
        RememberedRule {
            key: RuleKey {
                tool_name: tool_name.to_owned(),
                pattern: pattern.map(str::to_owned),
            },
            allow,
            scope,
            reason: reason.map(str::to_owned),
        }
    }

    async fn current_policy_with_rule(
        outcome: ToolAuthorizationOutcome,
        rule: RememberedRule,
    ) -> (ToolAuthorizationDecision, usize, bool) {
        let calls = Arc::new(AtomicUsize::new(0));
        let store = RuleStore::new();
        store.add_rule(rule);
        let (authorizer, mut rx, _, _) = test_authorizer(
            Some(Arc::new(CountingAuthorizer {
                outcome,
                calls: Arc::clone(&calls),
            })),
            store,
        );

        let decision = authorizer
            .authorize(&sample_request())
            .await
            .expect("authorization should resolve");
        let emitted = rx.try_recv().is_ok();
        (decision, calls.load(Ordering::SeqCst), emitted)
    }

    #[tokio::test]
    async fn a_current_denial_beats_a_remembered_allow() {
        let (decision, calls, emitted) =
            current_policy_with_rule(ToolAuthorizationOutcome::Deny, shell_rule(true, None)).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(
            decision.reason.as_deref(),
            Some("the current policy refuses")
        );
        assert_eq!(calls, 1, "the current policy must be consulted first");
        assert!(!emitted, "a policy denial has nothing to ask about");
    }

    #[tokio::test]
    async fn a_current_allow_beats_a_remembered_denial() {
        let (decision, calls, emitted) = current_policy_with_rule(
            ToolAuthorizationOutcome::Allow,
            shell_rule(false, Some("an earlier policy refused")),
        )
        .await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
        assert_eq!(calls, 1, "the current policy must be consulted first");
        assert!(!emitted, "a policy allow has nothing to ask about");
    }

    #[tokio::test]
    async fn a_current_prompt_consults_a_matching_remembered_rule() {
        let (decision, calls, emitted) =
            current_policy_with_rule(ToolAuthorizationOutcome::Prompt, shell_rule(true, None))
                .await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
        assert_eq!(calls, 1, "the current policy must be consulted first");
        assert!(!emitted, "the remembered answer avoids a duplicate prompt");
    }

    #[tokio::test]
    async fn no_inner_authorizer_allows_even_with_a_remembered_denial() {
        let store = RuleStore::new();
        store.add_rule(shell_rule(false, Some("an earlier policy refused")));
        let (authorizer, mut rx, _, _) = test_authorizer(None, store);

        let decision = authorizer
            .authorize(&sample_request())
            .await
            .expect("authorization should resolve");

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
        assert!(rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn a_late_remembered_answer_applies_to_its_call_but_not_the_next_policy() {
        let inner = SwitchingAuthorizer::prompting();
        let (authorizer, mut rx, pending, permissions) =
            test_authorizer(Some(Arc::new(inner.clone())), RuleStore::new());

        let first = tokio::spawn({
            let authorizer = authorizer.clone();
            async move { authorizer.authorize(&sample_request()).await.unwrap() }
        });
        let event = tokio::time::timeout(Duration::from_millis(200), rx.recv())
            .await
            .expect("permission request should arrive")
            .expect("event should be present");
        let SessionEvent::PermissionRequested { request_id, .. } = event else {
            panic!("expected PermissionRequested, got {event:?}");
        };

        inner.deny();
        permissions
            .remember_rule(shell_rule(true, None))
            .expect("remember late answer");
        pending
            .claim(&request_id)
            .expect("pending permission should be registered")
            .entry
            .sender
            .send(PermissionDecision::allow_and_remember(
                PermissionRuleScope::Session,
            ))
            .expect("decision send should succeed");

        let first = first
            .await
            .expect("first authorization task should succeed");
        assert_eq!(
            first.outcome,
            ToolAuthorizationOutcome::Allow,
            "the already-open request keeps the answer given to it"
        );

        let next = authorizer
            .authorize(&sample_request())
            .await
            .expect("next authorization should resolve");
        assert_eq!(next.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(inner.calls.load(Ordering::SeqCst), 2);
        assert!(
            rx.try_recv().is_err(),
            "the stricter next policy must not prompt or consult the stale allow"
        );
    }

    #[tokio::test]
    async fn a_remembered_refusal_restates_the_reason_it_was_remembered_with() {
        // Nothing asks the approver a second time, so the rule is the only
        // thing left that knows why the first answer was no.
        let store = RuleStore::new();
        store.add_rule(shell_rule(false, Some("this run does not allow writes")));

        let decision = answered_by_rule(store).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(
            decision.reason.as_deref(),
            Some(
                "this run does not allow writes — remembered from an earlier refusal, so asking again will not change it"
            )
        );
    }

    #[tokio::test]
    async fn a_refusal_remembered_without_a_reason_keeps_the_standing_wording() {
        let store = RuleStore::new();
        store.add_rule(shell_rule(false, None));

        let decision = answered_by_rule(store).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Deny);
        assert_eq!(decision.reason.as_deref(), Some(BLOCKED_BY_REMEMBERED_RULE));
    }

    #[tokio::test]
    async fn a_remembered_allow_answers_without_words() {
        // Nothing writes a reason onto an allow, but the type permits one, and
        // an allowed call still explains itself by happening.
        let store = RuleStore::new();
        store.add_rule(shell_rule(true, Some("should never be read")));

        let decision = answered_by_rule(store).await;

        assert_eq!(decision.outcome, ToolAuthorizationOutcome::Allow);
        assert_eq!(decision.reason, None);
    }

    #[test]
    fn matching_rule_hands_back_the_reason_of_the_rule_that_won() {
        // Precedence decides which reason the model reads, so the pattern
        // rule's words must come back rather than the bare rule's.
        let store = RuleStore::new();
        store.add_rule(shell_rule(false, Some("shell is refused in this run")));
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: Some("**cargo test**".to_owned()),
            },
            allow: false,
            scope: PermissionRuleScope::Session,
            reason: Some("the test suite is not run from inside a run".to_owned()),
        });

        let matched = store
            .matching_rule("shell", Some(r#"{"command":"cargo test"}"#))
            .expect("a rule should match");

        assert_eq!(
            matched.reason.as_deref(),
            Some("the test suite is not run from inside a run")
        );
    }

    #[test]
    fn check_matches_tool_name_without_pattern() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: None,
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        // Bare rule (no pattern) matches regardless of input_json content.
        assert_eq!(
            store.check("shell", Some(r#"{"command":"ls"}"#)),
            Some(true)
        );
        assert_eq!(store.check("shell", None), Some(true));
    }

    #[test]
    fn check_matches_pattern_against_input_json() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: Some("*cargo test*".to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        assert_eq!(
            store.check("shell", Some(r#"{"command":"cargo test"}"#)),
            Some(true)
        );
    }

    #[test]
    fn check_pattern_rule_does_not_match_without_input() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: Some("*cargo test*".to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        // Pattern rule is ignored when input is None — no bare rule either,
        // so result must be None.
        assert_eq!(store.check("shell", None), None);
    }

    #[test]
    fn check_pattern_rule_takes_precedence_over_no_pattern() {
        let store = RuleStore::new();
        // Bare rule: allow.
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: None,
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        // Pattern rule: deny when input matches. `**` reads the same as `*`
        // now that a pattern is matched as data, and is kept here because a
        // rule persisted with that spelling has to keep answering.
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: Some("**rm -rf**".to_owned()),
            },
            allow: false,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        // Pattern match should win over the bare allow.
        assert_eq!(
            store.check("shell", Some(r#"{"command":"rm -rf /tmp"}"#)),
            Some(false)
        );
    }

    /// The preview a host builds for a routed command, with its keys in the
    /// order `serde_json` writes them: an absolute `cwd` sits before `mode`
    /// and `target`.
    fn spawn_preview() -> &'static str {
        r#"{"body":"cargo test","cwd":"/Users/dev/basis","mode":"command","target":"mac"}"#
    }

    /// A pattern is matched against JSON, and JSON is not a path. Matched by a
    /// path globber, `*` stops dead at the `/` inside an absolute `cwd`, so
    /// every key serialized after `cwd` becomes unreachable — the rule saves,
    /// reports nothing, and silently answers no call it was written for.
    #[test]
    fn a_pattern_reaches_a_key_that_follows_an_absolute_path() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "spawn".to_owned(),
                pattern: Some(r#"**"mode":"command"**"#.to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });

        assert_eq!(store.check("spawn", Some(spawn_preview())), Some(true));
    }

    #[test]
    fn a_pattern_reaches_the_last_key_of_a_preview() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "spawn".to_owned(),
                pattern: Some(r#"**"target":"mac"**"#.to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });

        assert_eq!(store.check("spawn", Some(spawn_preview())), Some(true));
    }

    /// `**` was only ever needed because `*` could not cross a separator.
    /// Both now mean the same thing, so a rule written either way answers.
    #[test]
    fn one_star_and_two_stars_both_cross_a_path_separator() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "spawn".to_owned(),
                pattern: Some(r#"*"target":"mac"*"#.to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });

        assert_eq!(store.check("spawn", Some(spawn_preview())), Some(true));
    }

    /// JSON is punctuation-dense, and a path globber reads some of that
    /// punctuation as syntax: `{`…`}` is brace alternation and `[`…`]` a
    /// character class. A pattern that quotes the front of an object must
    /// match the object it quotes.
    #[test]
    fn json_punctuation_in_a_pattern_is_matched_literally() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "spawn".to_owned(),
                pattern: Some(r#"{"body":"cargo test"*"#.to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });

        assert_eq!(store.check("spawn", Some(spawn_preview())), Some(true));
    }

    #[test]
    fn a_pattern_that_names_another_target_does_not_match() {
        let store = RuleStore::new();
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "spawn".to_owned(),
                pattern: Some(r#"**"target":"linux"**"#.to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });

        assert_eq!(store.check("spawn", Some(spawn_preview())), None);
    }

    #[test]
    fn check_non_matching_pattern_falls_through() {
        let store = RuleStore::new();
        // Only a pattern rule is present; input does not match it.
        store.add_rule(RememberedRule {
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: Some("*cargo test*".to_owned()),
            },
            allow: true,
            scope: PermissionRuleScope::Session,
            reason: None,
        });
        // Non-matching input yields None (no bare fallback).
        assert_eq!(store.check("shell", Some(r#"{"command":"ls"}"#)), None);
    }

    #[test]
    fn the_same_key_coexists_at_every_scope_and_the_narrowest_scope_wins() {
        let store = RuleStore::new();
        store.add_rule(rule_at(
            PermissionRuleScope::Global,
            "shell",
            None,
            false,
            Some("global"),
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Project,
            "shell",
            None,
            false,
            Some("project"),
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "shell",
            None,
            true,
            Some("session"),
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Process,
            "shell",
            None,
            false,
            Some("process"),
        ));

        assert_eq!(store.rules().len(), 4);
        let matched = store
            .matching_rule("shell", None)
            .expect("one scoped rule should match");
        assert_eq!(matched.scope, PermissionRuleScope::Process);
        assert_eq!(matched.reason.as_deref(), Some("process"));
    }

    #[test]
    fn scope_precedence_is_applied_before_pattern_precedence() {
        let store = RuleStore::new();
        store.add_rule(rule_at(
            PermissionRuleScope::Global,
            "shell",
            Some("*cargo test*"),
            false,
            Some("global pattern"),
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "shell",
            Some("*cargo test*"),
            false,
            Some("session pattern"),
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Process,
            "shell",
            None,
            true,
            Some("process bare"),
        ));

        let matched = store
            .matching_rule("shell", Some(r#"{"command":"cargo test"}"#))
            .expect("one scoped rule should match");
        assert_eq!(matched.scope, PermissionRuleScope::Process);
        assert_eq!(matched.reason.as_deref(), Some("process bare"));
    }

    #[test]
    fn overlapping_patterns_prefer_denial_then_stable_key_order() {
        fn populated(
            patterns: impl IntoIterator<Item = (&'static str, bool, &'static str)>,
        ) -> RuleStore {
            let store = RuleStore::new();
            for (pattern, allow, reason) in patterns {
                store.add_rule(rule_at(
                    PermissionRuleScope::Project,
                    "shell",
                    Some(pattern),
                    allow,
                    Some(reason),
                ));
            }
            store
        }

        let rules = [
            ("*test*", false, "deny test"),
            ("*cargo*", false, "deny cargo"),
            ("*cargo test*", true, "allow exact phrase"),
        ];
        let forward = populated(rules);
        let reverse = populated(rules.into_iter().rev());

        for store in [forward, reverse] {
            let matched = store
                .matching_rule("shell", Some(r#"{"command":"cargo test"}"#))
                .expect("one pattern should win");
            assert!(!matched.allow, "a denial wins an overlapping tie");
            assert_eq!(
                matched.key.pattern.as_deref(),
                Some("*cargo*"),
                "equally denying matches use stable RuleKey order"
            );
            assert_eq!(matched.reason.as_deref(), Some("deny cargo"));
        }
    }

    #[test]
    fn exact_revoke_is_idempotent_and_leaves_other_addresses() {
        let store = RuleStore::new();
        for scope in [
            PermissionRuleScope::Global,
            PermissionRuleScope::Project,
            PermissionRuleScope::Session,
            PermissionRuleScope::Process,
        ] {
            store.add_rule(rule_at(scope, "shell", None, true, None));
        }
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "files",
            None,
            false,
            None,
        ));
        let project_shell = PermissionRuleAddress {
            scope: PermissionRuleScope::Project,
            key: RuleKey {
                tool_name: "shell".to_owned(),
                pattern: None,
            },
        };

        assert!(store.revoke_rule(&project_shell));
        assert!(!store.revoke_rule(&project_shell));
        let rules = store.rules();
        assert_eq!(rules.len(), 4);
        assert!(rules.iter().any(|rule| {
            rule.scope == PermissionRuleScope::Global && rule.key.tool_name == "shell"
        }));
        assert!(rules.iter().any(|rule| {
            rule.scope == PermissionRuleScope::Session && rule.key.tool_name == "shell"
        }));
        assert!(rules.iter().any(|rule| {
            rule.scope == PermissionRuleScope::Process && rule.key.tool_name == "shell"
        }));
        assert!(rules.iter().any(|rule| rule.key.tool_name == "files"));
    }

    #[test]
    fn clear_scope_returns_the_number_removed() {
        let store = RuleStore::new();
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "shell",
            None,
            true,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "files",
            None,
            false,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Project,
            "shell",
            None,
            false,
            None,
        ));

        assert_eq!(store.clear_scope(PermissionRuleScope::Session), 2);
        assert_eq!(store.clear_scope(PermissionRuleScope::Session), 0);
        assert_eq!(store.rules().len(), 1);
        assert_eq!(store.rules()[0].scope, PermissionRuleScope::Project);
    }

    #[test]
    fn rules_are_listed_in_semantic_then_stable_key_order() {
        let store = RuleStore::new();
        store.add_rule(rule_at(
            PermissionRuleScope::Global,
            "shell",
            None,
            true,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Process,
            "shell",
            None,
            false,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "shell",
            None,
            true,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "files",
            Some("*read*"),
            true,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Session,
            "files",
            None,
            false,
            None,
        ));
        store.add_rule(rule_at(
            PermissionRuleScope::Project,
            "shell",
            None,
            false,
            None,
        ));

        let listed: Vec<_> = store
            .rules()
            .into_iter()
            .map(|rule| (rule.scope, rule.key.tool_name, rule.key.pattern))
            .collect();
        assert_eq!(
            listed,
            vec![
                (PermissionRuleScope::Process, "shell".to_owned(), None),
                (
                    PermissionRuleScope::Session,
                    "files".to_owned(),
                    Some("*read*".to_owned()),
                ),
                (PermissionRuleScope::Session, "files".to_owned(), None,),
                (PermissionRuleScope::Session, "shell".to_owned(), None),
                (PermissionRuleScope::Project, "shell".to_owned(), None),
                (PermissionRuleScope::Global, "shell".to_owned(), None),
            ]
        );
    }
}