everruns-core 0.15.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
// Declarative guardrails capability.
//
// Attaches the deterministic check engine (`crate::guardrail_checks`) to the
// existing interception seams — streaming output guardrails and pre/post
// tool hooks — driven entirely by per-agent config. No checks configured
// means no hooks contributed: an agent without this capability (or with an
// empty config) runs exactly as before. See specs/guardrails.md.

use std::collections::HashSet;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::json;

use crate::atoms::{
    PostToolExecHook, PostToolExecHookPriority, PreToolUseDecision, PreToolUseHook,
};
use crate::capabilities::{Capability, CapabilityLocalization};
use crate::guardrail_checks::{
    CompiledGuardrails, DEFAULT_OUTPUT_REPLACEMENT, DEFAULT_TOOL_OUTPUT_REPLACEMENT,
    GuardrailAction, GuardrailStage, GuardrailsConfig, MAX_CHECK_ID_LEN, MAX_CHECKS,
    MAX_ENTRIES_PER_CHECK, MAX_ENTRY_LEN, MAX_JUDGE_PROMPT_LEN, MAX_MCP_REF_LEN,
    MAX_REPLACEMENT_LEN,
};
use crate::mcp_server::mcp_tool_name;
use crate::output_guardrail::{
    GuardrailDecision, OutputGuardrail, OutputGuardrailContext, OutputGuardrailRun,
};
use crate::tool_types::{ToolCall, ToolDefinition, ToolResult};
use crate::traits::ToolContext;
use crate::utility_llm::{UtilityLlmReasoningEffort, UtilityLlmRequest};
use crate::{LlmMessage, LlmMessageRole};

pub const GUARDRAILS_CAPABILITY_ID: &str = "guardrails";

pub struct GuardrailsCapability;

impl Capability for GuardrailsCapability {
    fn id(&self) -> &str {
        GUARDRAILS_CAPABILITY_ID
    }

    fn name(&self) -> &str {
        "Guardrails"
    }

    fn description(&self) -> &str {
        "Guardrail checks over model output and tool calls: regex and blocklist \
         matching, tool-call restrictions, an LLM judge, and delegation to an \
         external guardrail served over scoped MCP. Checks block or log per \
         configuration; advisory mode logs without enforcing."
    }

    fn localizations(&self) -> Vec<CapabilityLocalization> {
        vec![CapabilityLocalization::text(
            "uk",
            "Запобіжники",
            "Детерміновані перевірки виводу моделі та викликів інструментів: \
             регулярні вирази, списки заборонених слів, обмеження інструментів. \
             Перевірки блокують або лише журналюють згідно з конфігурацією.",
        )]
    }

    fn category(&self) -> Option<&str> {
        Some("Safety")
    }

    fn icon(&self) -> Option<&str> {
        Some("shield")
    }

    fn is_guardrail(&self) -> bool {
        true
    }

    fn config_schema(&self) -> Option<serde_json::Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "mode": {
                    "type": "string",
                    "enum": ["active", "advisory"],
                    "default": "active",
                    "description": "Advisory runs all checks but only logs hits — use it to tune checks against false positives before enforcing."
                },
                "checks": {
                    "type": "array",
                    "maxItems": MAX_CHECKS,
                    "items": {
                        "type": "object",
                        "required": ["stage", "type"],
                        "properties": {
                            "id": {
                                "type": "string",
                                "maxLength": MAX_CHECK_ID_LEN,
                                "description": "Stable identifier surfaced in reason codes and logs."
                            },
                            "stage": {
                                "type": "string",
                                "enum": ["output", "tool_use", "tool_output"],
                                "description": "Where the check runs: streamed model output, tool calls before execution, or tool results before they enter context."
                            },
                            "type": {
                                "type": "string",
                                "enum": ["regex", "blocklist", "tool_pattern", "llm_judge", "mcp"],
                                "description": "regex/blocklist match stage text; tool_pattern matches tool names (tool_use stage only); llm_judge evaluates a natural-language policy via the utility LLM (tool_use/tool_output stages only); mcp delegates the decision to an external guardrail served over scoped MCP (tool_use/tool_output stages only — sends stage content off-platform)."
                            },
                            "patterns": {
                                "type": "array",
                                "items": {"type": "string", "maxLength": MAX_ENTRY_LEN},
                                "maxItems": MAX_ENTRIES_PER_CHECK,
                                "description": "Regex patterns (type=regex)."
                            },
                            "words": {
                                "type": "array",
                                "items": {"type": "string", "maxLength": MAX_ENTRY_LEN},
                                "maxItems": MAX_ENTRIES_PER_CHECK,
                                "description": "Words or phrases matched as substrings (type=blocklist)."
                            },
                            "case_sensitive": {
                                "type": "boolean",
                                "default": false,
                                "description": "Blocklist matching case sensitivity."
                            },
                            "tools": {
                                "type": "array",
                                "items": {"type": "string", "maxLength": MAX_ENTRY_LEN},
                                "maxItems": MAX_ENTRIES_PER_CHECK,
                                "description": "Tool name patterns with * wildcards (type=tool_pattern)."
                            },
                            "on_fail": {
                                "type": "string",
                                "enum": ["block", "log"],
                                "default": "block",
                                "description": "block stops the output/tool call; log records the hit and continues."
                            },
                            "prompt": {
                                "type": "string",
                                "maxLength": MAX_JUDGE_PROMPT_LEN,
                                "description": "Natural-language policy prompt for llm_judge. Example: 'Block any tool call that reads files outside /home/user.' Evaluated by the utility LLM; fails open on timeout or error."
                            },
                            "server": {
                                "type": "string",
                                "maxLength": MAX_MCP_REF_LEN,
                                "description": "Scoped-MCP server reference for type=mcp (sanitized server name). Required for mcp checks."
                            },
                            "tool": {
                                "type": "string",
                                "maxLength": MAX_MCP_REF_LEN,
                                "description": "Guardrail tool/method to call on the MCP server for type=mcp. Required for mcp checks. Sends a bounded stage payload off-platform; fails open on timeout, connection error, parse failure, or server-not-configured."
                            },
                            "replacement": {
                                "type": "string",
                                "maxLength": MAX_REPLACEMENT_LEN,
                                "description": "Text shown in place of blocked output or as the user-facing message for blocked tool calls."
                            }
                        }
                    }
                }
            }
        }))
    }

    fn validate_config(&self, config: &serde_json::Value) -> Result<(), String> {
        GuardrailsConfig::from_value(config)?.compile().map(|_| ())
    }

    fn output_guardrails(&self) -> Vec<Arc<dyn OutputGuardrail>> {
        vec![Arc::new(DeclarativeOutputGuardrail)]
    }

    fn pre_tool_use_hooks_with_config(
        &self,
        config: &serde_json::Value,
    ) -> Vec<Arc<dyn PreToolUseHook>> {
        match compile_config_for_stage(config, GuardrailStage::ToolUse) {
            Some(compiled) => vec![Arc::new(GuardrailPreToolHook { compiled })],
            None => vec![],
        }
    }

    fn post_tool_exec_hooks_with_config(
        &self,
        config: &serde_json::Value,
    ) -> Vec<Arc<dyn PostToolExecHook>> {
        match compile_config_for_stage(config, GuardrailStage::ToolOutput) {
            Some(compiled) => vec![Arc::new(GuardrailPostToolHook { compiled })],
            None => vec![],
        }
    }
}

/// Timeout for a single LLM judge call. Fail-open on expiry.
const JUDGE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Maximum judge checks evaluated per single tool call invocation.
const MAX_JUDGE_CALLS_PER_INVOCATION: usize = 4;

/// Timeout for a single MCP guardrail call. Fail-open on expiry. Mirrors
/// `JUDGE_TIMEOUT` — an external guardrail outage must never wedge a turn.
const MCP_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Maximum MCP guardrail checks evaluated per single tool call invocation.
/// Mirrors `MAX_JUDGE_CALLS_PER_INVOCATION` to bound added latency (TM-DOS).
///
/// NOTE: this cap is per-check-type. `llm_judge` and `mcp` checks run serially
/// in the same hook, so when both are configured on a stage the additive
/// worst-case latency is
/// `(MAX_JUDGE_CALLS_PER_INVOCATION + MAX_MCP_CALLS_PER_INVOCATION) × 10 s`
/// (= 80 s today), not 40 s. There is intentionally no shared cross-type
/// budget yet — each async check type bounds itself independently and fails
/// open on its own timeout. See TM-DOS-020.
const MAX_MCP_CALLS_PER_INVOCATION: usize = 4;
/// Bound on the stage payload (UTF-8 char-boundary safe) sent to an MCP
/// guardrail endpoint. Mirrors the judge content cap.
const MCP_CONTENT_CAP: usize = 2_000;

/// System prompt sent to the utility LLM for all judge evaluations.
const JUDGE_SYSTEM_PROMPT: &str = r#"You are a guardrail policy evaluator for an AI agent runtime.
Your task: determine whether the provided content violates the given policy.
Respond ONLY with valid JSON on a single line. No explanation, no prose, no markdown.
Format: {"verdict":"allow"} or {"verdict":"block","reason":"<concise reason>"}"#;

/// Evaluate one llm_judge check against `content` via the utility LLM.
/// Returns `Some(GuardrailAction)` on a block/log verdict, `None` on error
/// (fail-open). The caller is responsible for applying advisory-mode
/// downgrade via `compiled.judge_action()`.
async fn run_judge_check(
    service: &dyn crate::UtilityLlmService,
    check: &crate::guardrail_checks::CompiledJudgeCheck,
    stage: GuardrailStage,
    tool_name: &str,
    content: &str,
) -> Option<GuardrailAction> {
    // Bound content sent to judge; find a safe UTF-8 char boundary.
    let content_cap = {
        let mut end = content.len().min(2_000);
        while end > 0 && !content.is_char_boundary(end) {
            end -= 1;
        }
        end
    };
    let user_prompt = format!(
        "Policy: {}\nStage: {}\nTool: {}\nContent:\n{}",
        check.prompt,
        stage.as_str(),
        xml_escape(tool_name),
        &content[..content_cap],
    );
    let request = UtilityLlmRequest::new(vec![
        LlmMessage::text(LlmMessageRole::System, JUDGE_SYSTEM_PROMPT),
        LlmMessage::text(LlmMessageRole::User, user_prompt),
    ])
    .with_reasoning_effort(UtilityLlmReasoningEffort::Low)
    .with_max_tokens(64);

    let response = match tokio::time::timeout(JUDGE_TIMEOUT, service.chat_completion(request)).await
    {
        Ok(Ok(r)) => r,
        Ok(Err(e)) => {
            tracing::warn!(
                check = %check.label,
                error = %e,
                "guardrails: judge call failed, failing open"
            );
            return None;
        }
        Err(_) => {
            tracing::warn!(
                check = %check.label,
                "guardrails: judge call timed out, failing open"
            );
            return None;
        }
    };

    // Parse the verdict from the first JSON-like fragment in the response.
    let text = response.text.trim();
    let start = text.find('{').unwrap_or(0);
    let end = text.rfind('}').map(|i| i + 1).unwrap_or(text.len());
    let fragment = &text[start..end];

    match serde_json::from_str::<serde_json::Value>(fragment) {
        Ok(v) if v.get("verdict").and_then(|v| v.as_str()) == Some("block") => {
            tracing::warn!(
                check = %check.label,
                reason = v.get("reason").and_then(|r| r.as_str()).unwrap_or(""),
                "guardrails: judge verdict block"
            );
            Some(GuardrailAction::Block)
        }
        Ok(_) => Some(GuardrailAction::Log), // "allow" or unrecognized → no-op
        Err(e) => {
            tracing::warn!(
                check = %check.label,
                parse_error = %e,
                raw = %fragment,
                "guardrails: judge response parse failed, failing open"
            );
            None // fail-open
        }
    }
}

/// Truncate `content` to at most `cap` bytes on a UTF-8 char boundary.
fn truncate_on_char_boundary(content: &str, cap: usize) -> &str {
    let mut end = content.len().min(cap);
    while end > 0 && !content.is_char_boundary(end) {
        end -= 1;
    }
    &content[..end]
}

/// Parse a `{"verdict":"allow"|"block","reason":"..."}` verdict out of a JSON
/// value (or a string holding such JSON). Mirrors the judge verdict shape.
/// Returns `Some(Block)` on an explicit block verdict, `Some(Log)` for allow /
/// unrecognized, and `None` (fail-open) when no verdict can be parsed.
fn parse_verdict(value: &serde_json::Value, label: &str) -> Option<GuardrailAction> {
    // The MCP result may be a JSON object directly, or a string carrying JSON
    // (servers that return text content). Handle both.
    let parsed_owned;
    let verdict_obj = match value {
        serde_json::Value::String(s) => {
            let text = s.trim();
            let start = text.find('{').unwrap_or(0);
            let end = text.rfind('}').map(|i| i + 1).unwrap_or(text.len());
            match serde_json::from_str::<serde_json::Value>(&text[start..end]) {
                Ok(v) => {
                    parsed_owned = v;
                    &parsed_owned
                }
                Err(e) => {
                    tracing::warn!(
                        check = %label,
                        parse_error = %e,
                        "guardrails: mcp verdict parse failed, failing open"
                    );
                    return None;
                }
            }
        }
        other => other,
    };
    match verdict_obj.get("verdict").and_then(|v| v.as_str()) {
        Some("block") => {
            tracing::warn!(
                check = %label,
                reason = verdict_obj.get("reason").and_then(|r| r.as_str()).unwrap_or(""),
                "guardrails: mcp verdict block"
            );
            Some(GuardrailAction::Block)
        }
        Some(_) => Some(GuardrailAction::Log), // "allow" → no-op
        None => {
            // No recognizable verdict field — fail open rather than guess.
            tracing::warn!(
                check = %label,
                "guardrails: mcp response missing verdict field, failing open"
            );
            None
        }
    }
}

/// Evaluate one `mcp` check against `content` by calling the configured
/// scoped-MCP guardrail tool. Returns `Some(GuardrailAction)` on a parsed
/// verdict, `None` on any failure (fail-open). The caller applies advisory-mode
/// downgrade via `compiled.async_action()`.
async fn run_mcp_check(
    invoker: &dyn crate::McpToolInvoker,
    check: &crate::guardrail_checks::CompiledMcpCheck,
    stage: GuardrailStage,
    tool_name: &str,
    content: &str,
) -> Option<GuardrailAction> {
    let payload = truncate_on_char_boundary(content, MCP_CONTENT_CAP);
    // The guardrail tool receives a structured payload describing the stage
    // under inspection. Tenant scoping is enforced by the host's per-session
    // connection resolver, which only resolves servers scoped to this session.
    let call = ToolCall {
        id: String::new(),
        name: mcp_tool_name(&check.server, &check.tool),
        arguments: json!({
            "stage": stage.as_str(),
            "tool": tool_name,
            "content": payload,
        }),
    };

    let result = match tokio::time::timeout(MCP_CHECK_TIMEOUT, invoker.invoke(&call)).await {
        Ok(Ok(r)) => r,
        Ok(Err(e)) => {
            tracing::warn!(
                check = %check.label,
                error = %e,
                "guardrails: mcp call failed, failing open"
            );
            return None;
        }
        Err(_) => {
            tracing::warn!(
                check = %check.label,
                "guardrails: mcp call timed out, failing open"
            );
            return None;
        }
    };

    // A tool-level error from the endpoint (server not found, transport error)
    // fails open — never block execution on a guardrail outage.
    if let Some(error) = &result.error {
        tracing::warn!(
            check = %check.label,
            error = %error,
            "guardrails: mcp endpoint returned error, failing open"
        );
        return None;
    }
    let Some(value) = &result.result else {
        tracing::warn!(
            check = %check.label,
            "guardrails: mcp endpoint returned no result, failing open"
        );
        return None;
    };
    parse_verdict(value, &check.label)
}

fn xml_escape(s: &str) -> std::borrow::Cow<'_, str> {
    if s.bytes()
        .any(|b| matches!(b, b'<' | b'>' | b'&' | b'\'' | b'"'))
    {
        std::borrow::Cow::Owned(
            s.replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;")
                .replace('\'', "&#39;")
                .replace('"', "&quot;"),
        )
    } else {
        std::borrow::Cow::Borrowed(s)
    }
}

/// Compile `config` and return it only when at least one check targets
/// `stage`. Invalid configs (possible only if persisted before validation
/// existed) are logged and treated as no checks — guardrails must never
/// take down the turn pipeline.
fn compile_config_for_stage(
    config: &serde_json::Value,
    stage: GuardrailStage,
) -> Option<Arc<CompiledGuardrails>> {
    let parsed = match GuardrailsConfig::from_value(config).and_then(|c| c.compile()) {
        Ok(compiled) => compiled,
        Err(error) => {
            tracing::warn!(%error, "guardrails: skipping invalid config");
            return None;
        }
    };
    parsed.has_stage(stage).then(|| Arc::new(parsed))
}

// ============================================================================
// Output stage: streaming output guardrail
// ============================================================================

struct DeclarativeOutputGuardrail;

impl OutputGuardrail for DeclarativeOutputGuardrail {
    fn id(&self) -> &str {
        "guardrail_checks"
    }

    fn arm(&self, ctx: &OutputGuardrailContext<'_>) -> Option<Box<dyn OutputGuardrailRun>> {
        let compiled = compile_config_for_stage(ctx.config, GuardrailStage::Output)?;
        Some(Box::new(DeclarativeOutputRun {
            compiled,
            logged: HashSet::new(),
        }))
    }
}

struct DeclarativeOutputRun {
    compiled: Arc<CompiledGuardrails>,
    /// Checks already reported as log-only hits for this stream. Without
    /// this, an advisory hit would re-log on every subsequent delta because
    /// evaluation always sees the full accumulated text.
    logged: HashSet<usize>,
}

impl OutputGuardrailRun for DeclarativeOutputRun {
    fn check(&mut self, accumulated: &str, _delta: &str) -> GuardrailDecision {
        // Evaluating against the full accumulated text keeps matches that
        // span delta boundaries correct. Cost is O(|accumulated|) per delta
        // — same asymptotics the canary guardrail accepts — and bounded by
        // assistant message size.
        let logged = &self.logged;
        let hits = self
            .compiled
            .evaluate(GuardrailStage::Output, accumulated, None, &|i| {
                logged.contains(&i)
            });
        for hit in hits {
            match hit.action {
                GuardrailAction::Block => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        "guardrails: blocking model output"
                    );
                    return GuardrailDecision::Block(crate::output_guardrail::GuardrailBlock {
                        reason_code: hit.reason_code,
                        replacement: hit
                            .replacement
                            .unwrap_or_else(|| DEFAULT_OUTPUT_REPLACEMENT.to_string()),
                    });
                }
                GuardrailAction::Log => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        "guardrails: output check hit (log only)"
                    );
                    self.logged.insert(hit.check_index);
                }
            }
        }
        GuardrailDecision::Pass
    }
}

// ============================================================================
// Tool-use stage: pre-tool hook
// ============================================================================

struct GuardrailPreToolHook {
    compiled: Arc<CompiledGuardrails>,
}

#[async_trait]
impl PreToolUseHook for GuardrailPreToolHook {
    async fn before_exec(
        &self,
        tool_call: ToolCall,
        _tool_def: &ToolDefinition,
        context: &ToolContext,
    ) -> PreToolUseDecision {
        // tool_pattern rules match the tool name; regex/blocklist rules
        // match the serialized arguments.
        let args_text = tool_call.arguments.to_string();
        let hits = self.compiled.evaluate(
            GuardrailStage::ToolUse,
            &args_text,
            Some(&tool_call.name),
            &|_| false,
        );
        for hit in hits {
            match hit.action {
                GuardrailAction::Block => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        tool = %tool_call.name,
                        "guardrails: blocking tool call"
                    );
                    return PreToolUseDecision::Block {
                        tool_call,
                        reason: format!(
                            "Tool call blocked by guardrail check '{}' ({})",
                            hit.check_label, hit.reason_code
                        ),
                        user_message: hit.replacement,
                    };
                }
                GuardrailAction::Log => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        tool = %tool_call.name,
                        "guardrails: tool call check hit (log only)"
                    );
                }
            }
        }
        // LLM-judge checks run after deterministic checks; skipped when
        // the utility LLM is absent or disabled.
        if let Some(service) = &context.utility_llm_service
            && service.is_configured()
        {
            for (calls, check) in self
                .compiled
                .judge_checks_for_stage(GuardrailStage::ToolUse)
                .enumerate()
            {
                if calls >= MAX_JUDGE_CALLS_PER_INVOCATION {
                    tracing::warn!(
                        tool = %tool_call.name,
                        "guardrails: judge call cap reached for tool_use, skipping remaining"
                    );
                    break;
                }
                let Some(raw_action) = run_judge_check(
                    service.as_ref(),
                    check,
                    GuardrailStage::ToolUse,
                    &tool_call.name,
                    &args_text,
                )
                .await
                else {
                    continue; // fail-open
                };
                let action = self.compiled.judge_action(check.on_fail);
                match action {
                    GuardrailAction::Block if raw_action == GuardrailAction::Block => {
                        tracing::warn!(
                            check = %check.label,
                            tool = %tool_call.name,
                            "guardrails: judge blocking tool call"
                        );
                        return PreToolUseDecision::Block {
                            tool_call,
                            reason: format!(
                                "Tool call blocked by guardrail check '{}' (guardrail.llm_judge)",
                                check.label
                            ),
                            user_message: check.replacement.clone(),
                        };
                    }
                    _ => {
                        if raw_action == GuardrailAction::Block {
                            tracing::warn!(
                                check = %check.label,
                                tool = %tool_call.name,
                                "guardrails: judge hit (log only)"
                            );
                        }
                    }
                }
            }
        }
        // MCP-served checks run after judge checks; skipped when no scoped-MCP
        // invoker is wired into the context.
        if let Some(invoker) = &context.mcp_invoker {
            for (calls, check) in self
                .compiled
                .mcp_checks_for_stage(GuardrailStage::ToolUse)
                .enumerate()
            {
                if calls >= MAX_MCP_CALLS_PER_INVOCATION {
                    tracing::warn!(
                        tool = %tool_call.name,
                        "guardrails: mcp call cap reached for tool_use, skipping remaining"
                    );
                    break;
                }
                let Some(raw_action) = run_mcp_check(
                    invoker.as_ref(),
                    check,
                    GuardrailStage::ToolUse,
                    &tool_call.name,
                    &args_text,
                )
                .await
                else {
                    continue; // fail-open
                };
                let action = self.compiled.async_action(check.on_fail);
                match action {
                    GuardrailAction::Block if raw_action == GuardrailAction::Block => {
                        tracing::warn!(
                            check = %check.label,
                            tool = %tool_call.name,
                            "guardrails: mcp blocking tool call"
                        );
                        return PreToolUseDecision::Block {
                            tool_call,
                            reason: format!(
                                "Tool call blocked by guardrail check '{}' (guardrail.mcp)",
                                check.label
                            ),
                            user_message: check.replacement.clone(),
                        };
                    }
                    _ => {
                        if raw_action == GuardrailAction::Block {
                            tracing::warn!(
                                check = %check.label,
                                tool = %tool_call.name,
                                "guardrails: mcp hit (log only)"
                            );
                        }
                    }
                }
            }
        }
        PreToolUseDecision::Continue(tool_call)
    }
}

// ============================================================================
// Tool-output stage: post-tool hook
// ============================================================================

struct GuardrailPostToolHook {
    compiled: Arc<CompiledGuardrails>,
}

#[async_trait]
impl PostToolExecHook for GuardrailPostToolHook {
    fn priority(&self) -> PostToolExecHookPriority {
        PostToolExecHookPriority::Guardrail
    }

    async fn after_exec(
        &self,
        tool_call: &ToolCall,
        _tool_def: &ToolDefinition,
        result: &mut ToolResult,
        context: &ToolContext,
    ) {
        let mut haystack = String::new();
        if let Some(value) = &result.result {
            match value {
                serde_json::Value::String(s) => haystack.push_str(s),
                other => haystack.push_str(&other.to_string()),
            }
        }
        if let Some(error) = &result.error {
            haystack.push('\n');
            haystack.push_str(error);
        }
        // Exec-style tools budget the visible `result` JSON but keep the full,
        // untruncated content in `raw_output`, which is persisted to `/outputs`.
        // Include it in the haystack so sensitive content that only survives in
        // `raw_output` is caught before this hook clears it on a block.
        if let Some(raw_output) = &result.raw_output {
            haystack.push('\n');
            haystack.push_str(raw_output);
        }
        if haystack.is_empty() {
            return;
        }
        let hits = self
            .compiled
            .evaluate(GuardrailStage::ToolOutput, &haystack, None, &|_| false);
        for hit in hits {
            match hit.action {
                GuardrailAction::Block => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        tool = %tool_call.name,
                        "guardrails: withholding tool output"
                    );
                    let notice = hit
                        .replacement
                        .unwrap_or_else(|| DEFAULT_TOOL_OUTPUT_REPLACEMENT.to_string());
                    // The original content never reaches model context.
                    result.result = Some(serde_json::Value::String(notice));
                    result.error = None;
                    result.images = None;
                    result.raw_output = None;
                    return;
                }
                GuardrailAction::Log => {
                    tracing::warn!(
                        check = %hit.check_label,
                        reason_code = %hit.reason_code,
                        tool = %tool_call.name,
                        "guardrails: tool output check hit (log only)"
                    );
                }
            }
        }
        // LLM-judge checks for tool_output; skipped when utility LLM is absent or disabled.
        if let Some(service) = &context.utility_llm_service
            && service.is_configured()
        {
            for (calls, check) in self
                .compiled
                .judge_checks_for_stage(GuardrailStage::ToolOutput)
                .enumerate()
            {
                if calls >= MAX_JUDGE_CALLS_PER_INVOCATION {
                    tracing::warn!(
                        tool = %tool_call.name,
                        "guardrails: judge call cap reached for tool_output, skipping remaining"
                    );
                    break;
                }
                let Some(raw_action) = run_judge_check(
                    service.as_ref(),
                    check,
                    GuardrailStage::ToolOutput,
                    &tool_call.name,
                    &haystack,
                )
                .await
                else {
                    continue; // fail-open
                };
                let action = self.compiled.judge_action(check.on_fail);
                match action {
                    GuardrailAction::Block if raw_action == GuardrailAction::Block => {
                        tracing::warn!(
                            check = %check.label,
                            tool = %tool_call.name,
                            "guardrails: judge withholding tool output"
                        );
                        let notice = check
                            .replacement
                            .clone()
                            .unwrap_or_else(|| DEFAULT_TOOL_OUTPUT_REPLACEMENT.to_string());
                        result.result = Some(serde_json::Value::String(notice));
                        result.error = None;
                        result.images = None;
                        result.raw_output = None;
                        return;
                    }
                    _ => {
                        if raw_action == GuardrailAction::Block {
                            tracing::warn!(
                                check = %check.label,
                                tool = %tool_call.name,
                                "guardrails: judge tool_output hit (log only)"
                            );
                        }
                    }
                }
            }
        }
        // MCP-served checks for tool_output; skipped when no scoped-MCP invoker
        // is wired into the context.
        if let Some(invoker) = &context.mcp_invoker {
            for (calls, check) in self
                .compiled
                .mcp_checks_for_stage(GuardrailStage::ToolOutput)
                .enumerate()
            {
                if calls >= MAX_MCP_CALLS_PER_INVOCATION {
                    tracing::warn!(
                        tool = %tool_call.name,
                        "guardrails: mcp call cap reached for tool_output, skipping remaining"
                    );
                    break;
                }
                let Some(raw_action) = run_mcp_check(
                    invoker.as_ref(),
                    check,
                    GuardrailStage::ToolOutput,
                    &tool_call.name,
                    &haystack,
                )
                .await
                else {
                    continue; // fail-open
                };
                let action = self.compiled.async_action(check.on_fail);
                match action {
                    GuardrailAction::Block if raw_action == GuardrailAction::Block => {
                        tracing::warn!(
                            check = %check.label,
                            tool = %tool_call.name,
                            "guardrails: mcp withholding tool output"
                        );
                        let notice = check
                            .replacement
                            .clone()
                            .unwrap_or_else(|| DEFAULT_TOOL_OUTPUT_REPLACEMENT.to_string());
                        result.result = Some(serde_json::Value::String(notice));
                        result.error = None;
                        result.images = None;
                        result.raw_output = None;
                        return;
                    }
                    _ => {
                        if raw_action == GuardrailAction::Block {
                            tracing::warn!(
                                check = %check.label,
                                tool = %tool_call.name,
                                "guardrails: mcp tool_output hit (log only)"
                            );
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typed_id::SessionId;
    use crate::utility_llm::UtilityLlmService;
    use crate::{AgentLoopError, LlmCompletionMetadata, LlmResponse, LlmResponseStream};
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::Arc;

    /// Stub utility LLM that returns a fixed verdict string.
    struct StubJudge {
        response: String,
    }

    impl StubJudge {
        fn block() -> Arc<Self> {
            Arc::new(Self {
                response: r#"{"verdict":"block","reason":"test"}"#.to_string(),
            })
        }
        fn allow() -> Arc<Self> {
            Arc::new(Self {
                response: r#"{"verdict":"allow"}"#.to_string(),
            })
        }
        fn error() -> Arc<Self> {
            Arc::new(Self {
                response: "".to_string(), // unused; chat_completion errors
            })
        }
    }

    #[async_trait]
    impl UtilityLlmService for StubJudge {
        fn is_configured(&self) -> bool {
            true
        }

        async fn chat_completion(
            &self,
            _request: crate::utility_llm::UtilityLlmRequest,
        ) -> crate::Result<LlmResponse> {
            if self.response.is_empty() {
                return Err(AgentLoopError::llm("stub error"));
            }
            Ok(LlmResponse {
                text: self.response.clone(),
                thinking: None,
                thinking_signature: None,
                tool_calls: None,
                metadata: LlmCompletionMetadata {
                    total_tokens: None,
                    prompt_tokens: None,
                    completion_tokens: None,
                    cache_read_tokens: None,
                    cache_creation_tokens: None,
                    provider_cost_usd: None,
                    model: None,
                    finish_reason: None,
                    retry_metadata: None,
                    response_id: None,
                    phase: None,
                },
            })
        }

        async fn chat_completion_stream(
            &self,
            _request: crate::utility_llm::UtilityLlmRequest,
        ) -> crate::Result<LlmResponseStream> {
            Err(AgentLoopError::llm("stub: no stream"))
        }
    }

    /// What a stubbed MCP guardrail endpoint should do for a call.
    enum McpBehavior {
        /// Return a result `Value` (object or JSON string).
        Result(serde_json::Value),
        /// Return a tool-level error.
        Error(String),
        /// Never respond in time (sleep past the timeout).
        Timeout,
        /// Return the call's `content` argument back as the verdict-bearing
        /// result string — used to assert payload truncation.
        EchoContent,
    }

    /// Stub scoped-MCP invoker returning a fixed verdict, recording calls.
    struct StubMcpInvoker {
        behavior: McpBehavior,
        last_call: std::sync::Mutex<Option<ToolCall>>,
    }

    impl StubMcpInvoker {
        fn new(behavior: McpBehavior) -> Arc<Self> {
            Arc::new(Self {
                behavior,
                last_call: std::sync::Mutex::new(None),
            })
        }
        fn block() -> Arc<Self> {
            Self::new(McpBehavior::Result(
                json!({"verdict": "block", "reason": "test"}),
            ))
        }
        fn allow() -> Arc<Self> {
            Self::new(McpBehavior::Result(json!({"verdict": "allow"})))
        }
    }

    #[async_trait]
    impl crate::McpToolInvoker for StubMcpInvoker {
        async fn invoke(&self, tool_call: &ToolCall) -> crate::Result<ToolResult> {
            *self.last_call.lock().unwrap() = Some(tool_call.clone());
            let result = match &self.behavior {
                McpBehavior::Result(v) => ToolResult {
                    tool_call_id: tool_call.id.clone(),
                    result: Some(v.clone()),
                    images: None,
                    error: None,
                    connection_required: None,
                    raw_output: None,
                },
                McpBehavior::Error(msg) => {
                    return Err(AgentLoopError::tool(msg.clone()));
                }
                McpBehavior::Timeout => {
                    tokio::time::sleep(MCP_CHECK_TIMEOUT + std::time::Duration::from_secs(2)).await;
                    unreachable!("timeout fires before sleep completes")
                }
                McpBehavior::EchoContent => {
                    let content = tool_call.arguments["content"].as_str().unwrap_or_default();
                    ToolResult {
                        tool_call_id: tool_call.id.clone(),
                        // Not a valid verdict — fails open — but the recorded
                        // call's content is what the truncation test inspects.
                        result: Some(serde_json::Value::String(content.to_string())),
                        images: None,
                        error: None,
                        connection_required: None,
                        raw_output: None,
                    }
                }
            };
            Ok(result)
        }
    }

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

    fn tool_def() -> ToolDefinition {
        ToolDefinition::Builtin(crate::tool_types::BuiltinTool {
            name: "test_tool".to_string(),
            display_name: None,
            description: "test".to_string(),
            parameters: json!({}),
            policy: crate::tool_types::ToolPolicy::Auto,
            category: None,
            deferrable: crate::tool_types::DeferrablePolicy::Never,
            hints: Default::default(),
            full_parameters: None,
        })
    }

    fn arm_output(config: serde_json::Value) -> Option<Box<dyn OutputGuardrailRun>> {
        let ctx = OutputGuardrailContext {
            system_prompt: "irrelevant",
            config: &config,
        };
        DeclarativeOutputGuardrail.arm(&ctx)
    }

    #[test]
    fn validate_config_accepts_valid_and_rejects_invalid() {
        let cap = GuardrailsCapability;
        assert!(cap.validate_config(&json!({})).is_ok());
        assert!(
            cap.validate_config(&json!({
                "checks": [{"stage": "output", "type": "blocklist", "words": ["x"]}]
            }))
            .is_ok()
        );
        assert!(
            cap.validate_config(&json!({
                "checks": [{"stage": "output", "type": "regex", "patterns": ["("]}]
            }))
            .is_err()
        );
    }

    #[test]
    fn output_guardrail_declines_to_arm_without_output_checks() {
        assert!(arm_output(json!({})).is_none());
        assert!(
            arm_output(json!({
                "checks": [{"stage": "tool_use", "type": "tool_pattern", "tools": ["bash*"]}]
            }))
            .is_none()
        );
    }

    #[test]
    fn output_guardrail_blocks_with_custom_replacement() {
        let mut run = arm_output(json!({
            "checks": [{
                "stage": "output", "type": "blocklist", "words": ["forbidden"],
                "replacement": "nope"
            }]
        }))
        .expect("armed");
        assert!(matches!(
            run.check("all good here", "here"),
            GuardrailDecision::Pass
        ));
        match run.check("this is forbidden text", " text") {
            GuardrailDecision::Block(b) => {
                assert_eq!(b.reason_code, "guardrail.blocklist");
                assert_eq!(b.replacement, "nope");
            }
            other => panic!("expected Block, got {other:?}"),
        }
    }

    #[test]
    fn output_guardrail_advisory_logs_once_and_passes() {
        let mut run = arm_output(json!({
            "mode": "advisory",
            "checks": [{"stage": "output", "type": "blocklist", "words": ["forbidden"]}]
        }))
        .expect("armed");
        assert!(matches!(
            run.check("forbidden", "forbidden"),
            GuardrailDecision::Pass
        ));
        // Subsequent deltas keep passing (and the hit is not re-reported).
        assert!(matches!(
            run.check("forbidden and more", " and more"),
            GuardrailDecision::Pass
        ));
    }

    #[tokio::test]
    async fn pre_tool_hook_blocks_matching_tool_name() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{
                "stage": "tool_use", "type": "tool_pattern", "tools": ["bash*"],
                "replacement": "Shell access is not allowed for this agent."
            }]
        }));
        assert_eq!(hooks.len(), 1);
        let ctx = ToolContext::new(SessionId::new());
        let decision = hooks[0]
            .before_exec(
                tool_call("bashkit_exec", json!({"cmd": "ls"})),
                &tool_def(),
                &ctx,
            )
            .await;
        match decision {
            PreToolUseDecision::Block {
                reason,
                user_message,
                ..
            } => {
                assert!(reason.contains("guardrail"), "{reason}");
                assert_eq!(
                    user_message.as_deref(),
                    Some("Shell access is not allowed for this agent.")
                );
            }
            other => panic!("expected Block, got {other:?}"),
        }
        let decision = hooks[0]
            .before_exec(tool_call("read_file", json!({})), &tool_def(), &ctx)
            .await;
        assert!(matches!(decision, PreToolUseDecision::Continue(_)));
    }

    #[tokio::test]
    async fn pre_tool_hook_matches_arguments_with_regex() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{
                "stage": "tool_use", "type": "regex",
                "patterns": ["(?i)drop\\s+table"]
            }]
        }));
        let ctx = ToolContext::new(SessionId::new());
        let decision = hooks[0]
            .before_exec(
                tool_call("sql_query", json!({"query": "DROP TABLE users"})),
                &tool_def(),
                &ctx,
            )
            .await;
        assert!(matches!(decision, PreToolUseDecision::Block { .. }));
    }

    #[tokio::test]
    async fn pre_tool_hook_advisory_continues() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "mode": "advisory",
            "checks": [{"stage": "tool_use", "type": "tool_pattern", "tools": ["bash*"]}]
        }));
        let ctx = ToolContext::new(SessionId::new());
        let decision = hooks[0]
            .before_exec(tool_call("bashkit_exec", json!({})), &tool_def(), &ctx)
            .await;
        assert!(matches!(decision, PreToolUseDecision::Continue(_)));
    }

    #[tokio::test]
    async fn post_tool_hook_withholds_matching_output() {
        let cap = GuardrailsCapability;
        let hooks = cap.post_tool_exec_hooks_with_config(&json!({
            "checks": [{
                "id": "aws_key", "stage": "tool_output", "type": "regex",
                "patterns": ["AKIA[0-9A-Z]{16}"]
            }]
        }));
        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0].priority(), PostToolExecHookPriority::Guardrail);
        let ctx = ToolContext::new(SessionId::new());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("key is AKIAIOSFODNN7EXAMPLE ok")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(
            result.result,
            Some(json!(DEFAULT_TOOL_OUTPUT_REPLACEMENT)),
            "matched output must be replaced with the notice"
        );
        assert!(result.error.is_none());
    }

    #[tokio::test]
    async fn post_tool_hook_scans_raw_output_persistence_surface() {
        // Exec-style tools keep the full, untruncated content in `raw_output`
        // (persisted to /outputs) while the visible `result` is budgeted. A
        // secret that only survives in `raw_output` must still be blocked.
        let cap = GuardrailsCapability;
        let hooks = cap.post_tool_exec_hooks_with_config(&json!({
            "checks": [{
                "id": "aws_key", "stage": "tool_output", "type": "regex",
                "patterns": ["AKIA[0-9A-Z]{16}"]
            }]
        }));
        let ctx = ToolContext::new(SessionId::new());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("(truncated output)")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: Some("full log: AKIAIOSFODNN7EXAMPLE trailing".to_string()),
        };
        hooks[0]
            .after_exec(
                &tool_call("bashkit_exec", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(
            result.result,
            Some(json!(DEFAULT_TOOL_OUTPUT_REPLACEMENT)),
            "a secret only present in raw_output must trigger the block"
        );
        assert!(
            result.raw_output.is_none(),
            "raw_output must be cleared on a block so it is not persisted"
        );
    }

    #[tokio::test]
    async fn post_tool_hook_leaves_clean_output_untouched() {
        let cap = GuardrailsCapability;
        let hooks = cap.post_tool_exec_hooks_with_config(&json!({
            "checks": [{"stage": "tool_output", "type": "blocklist", "words": ["secret"]}]
        }));
        let ctx = ToolContext::new(SessionId::new());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("nothing to see")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(result.result, Some(json!("nothing to see")));
    }

    #[test]
    fn no_hooks_contributed_without_matching_stage_checks() {
        let cap = GuardrailsCapability;
        assert!(cap.pre_tool_use_hooks_with_config(&json!({})).is_empty());
        assert!(cap.post_tool_exec_hooks_with_config(&json!({})).is_empty());
        let output_only = json!({
            "checks": [{"stage": "output", "type": "blocklist", "words": ["x"]}]
        });
        assert!(cap.pre_tool_use_hooks_with_config(&output_only).is_empty());
        assert!(
            cap.post_tool_exec_hooks_with_config(&output_only)
                .is_empty()
        );
    }

    #[test]
    fn capability_metadata() {
        let cap = GuardrailsCapability;
        assert_eq!(cap.id(), GUARDRAILS_CAPABILITY_ID);
        assert!(cap.is_guardrail());
        assert!(cap.config_schema().is_some());
        assert_eq!(cap.output_guardrails().len(), 1);
    }

    // --- llm_judge hook tests ---

    #[tokio::test]
    async fn judge_pre_tool_hook_blocks_when_judge_says_block() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block requests to delete data."}]
        }));
        assert_eq!(hooks.len(), 1);
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::block());
        let decision = hooks[0]
            .before_exec(
                tool_call("delete_record", json!({"id": 42})),
                &tool_def(),
                &ctx,
            )
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Block { .. }),
            "judge block verdict should block the tool call"
        );
    }

    #[tokio::test]
    async fn judge_pre_tool_hook_continues_when_judge_says_allow() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block requests to delete data."}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::allow());
        let decision = hooks[0]
            .before_exec(tool_call("read_file", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "judge allow verdict should continue"
        );
    }

    #[tokio::test]
    async fn judge_pre_tool_hook_fails_open_on_error() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block bad things."}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::error());
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "judge error must fail open"
        );
    }

    #[tokio::test]
    async fn judge_pre_tool_hook_skipped_without_utility_llm() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block everything."}]
        }));
        // No utility LLM service configured → judge checks are skipped
        let ctx = ToolContext::new(SessionId::new());
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "without utility LLM, judge checks are silently skipped"
        );
    }

    #[tokio::test]
    async fn judge_pre_tool_hook_skipped_when_service_not_configured() {
        // Service is present in the context but reports is_configured() == false
        // (e.g. DisabledUtilityLlmService). Judge checks must be silently skipped.
        use crate::utility_llm::DisabledUtilityLlmService;
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block everything."}]
        }));
        let ctx = ToolContext::new(SessionId::new())
            .with_utility_llm_service(Arc::new(DisabledUtilityLlmService));
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "disabled utility LLM service must skip judge checks without warn logs"
        );
    }

    #[tokio::test]
    async fn judge_advisory_mode_continues_even_on_block_verdict() {
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "mode": "advisory",
            "checks": [{"stage": "tool_use", "type": "llm_judge",
                        "prompt": "Block everything.", "on_fail": "block"}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::block());
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "advisory mode must not block even when judge says block"
        );
    }

    #[tokio::test]
    async fn judge_post_tool_hook_withholds_output_on_block() {
        let cap = GuardrailsCapability;
        let hooks = cap.post_tool_exec_hooks_with_config(&json!({
            "checks": [{"stage": "tool_output", "type": "llm_judge",
                        "prompt": "Block PII in tool output."}]
        }));
        assert_eq!(hooks.len(), 1);
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::block());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("user email: alice@example.com")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(
            result.result,
            Some(json!(DEFAULT_TOOL_OUTPUT_REPLACEMENT)),
            "judge block should replace tool output with notice"
        );
        assert!(result.error.is_none());
    }

    #[tokio::test]
    async fn judge_post_tool_hook_passes_clean_output_on_allow() {
        let cap = GuardrailsCapability;
        let hooks = cap.post_tool_exec_hooks_with_config(&json!({
            "checks": [{"stage": "tool_output", "type": "llm_judge",
                        "prompt": "Block PII."}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::allow());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("no pii here")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(result.result, Some(json!("no pii here")));
    }

    #[tokio::test]
    async fn judge_handles_multibyte_content_without_panic() {
        // Verifies the 2 000-byte content cap doesn't slice mid-char.
        let cap = GuardrailsCapability;
        let hooks = cap.pre_tool_use_hooks_with_config(&json!({
            "checks": [{"stage": "tool_use", "type": "llm_judge", "prompt": "p"}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_utility_llm_service(StubJudge::allow());
        // 700 × 3-byte chars = 2 100 bytes, boundary at 2 000 falls mid-char
        let multibyte_args = "".repeat(700);
        let decision = hooks[0]
            .before_exec(
                tool_call("any_tool", json!({"x": multibyte_args})),
                &tool_def(),
                &ctx,
            )
            .await;
        // Just must not panic; allow verdict continues
        assert!(matches!(decision, PreToolUseDecision::Continue(_)));
    }

    #[test]
    fn xml_escape_escapes_special_chars() {
        assert_eq!(xml_escape("normal"), "normal");
        assert_eq!(xml_escape("<tag>"), "&lt;tag&gt;");
        assert_eq!(xml_escape("a&b"), "a&amp;b");
        assert_eq!(xml_escape("\"quoted\""), "&quot;quoted&quot;");
        assert_eq!(xml_escape("it's"), "it&#39;s");
    }

    #[test]
    fn config_schema_includes_llm_judge() {
        let cap = GuardrailsCapability;
        let schema = cap.config_schema().unwrap();
        let type_enum = &schema["properties"]["checks"]["items"]["properties"]["type"]["enum"];
        let values: Vec<&str> = type_enum
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert!(
            values.contains(&"llm_judge"),
            "schema enum must include llm_judge"
        );
    }

    // --- mcp hook tests ---

    #[test]
    fn config_schema_includes_mcp() {
        let cap = GuardrailsCapability;
        let schema = cap.config_schema().unwrap();
        let type_enum = &schema["properties"]["checks"]["items"]["properties"]["type"]["enum"];
        let values: Vec<&str> = type_enum
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert!(values.contains(&"mcp"), "schema enum must include mcp");
        let props = &schema["properties"]["checks"]["items"]["properties"];
        assert!(props["server"].is_object(), "schema must define server");
        assert!(props["tool"].is_object(), "schema must define tool");
    }

    fn mcp_pre_hooks(on_fail: &str, mode: &str) -> Vec<Arc<dyn PreToolUseHook>> {
        GuardrailsCapability.pre_tool_use_hooks_with_config(&json!({
            "mode": mode,
            "checks": [{"stage": "tool_use", "type": "mcp",
                        "server": "guard", "tool": "screen", "on_fail": on_fail}]
        }))
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_blocks_when_endpoint_says_block() {
        let hooks = mcp_pre_hooks("block", "active");
        assert_eq!(hooks.len(), 1);
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::block());
        let decision = hooks[0]
            .before_exec(
                tool_call("delete_record", json!({"id": 42})),
                &tool_def(),
                &ctx,
            )
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Block { .. }),
            "mcp block verdict should block the tool call"
        );
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_continues_when_endpoint_says_allow() {
        let hooks = mcp_pre_hooks("block", "active");
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::allow());
        let decision = hooks[0]
            .before_exec(tool_call("read_file", json!({})), &tool_def(), &ctx)
            .await;
        assert!(matches!(decision, PreToolUseDecision::Continue(_)));
    }

    #[tokio::test]
    async fn mcp_advisory_continues_even_on_block_verdict() {
        let hooks = mcp_pre_hooks("block", "advisory");
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::block());
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "advisory mode must not block even when mcp says block"
        );
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_fails_open_on_connection_error() {
        let hooks = mcp_pre_hooks("block", "active");
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::new(
            McpBehavior::Error("MCP server not found".into()),
        ));
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "connection error must fail open"
        );
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_fails_open_on_timeout() {
        // Pause time so the 10 s timeout fires instantly.
        tokio::time::pause();
        let hooks = mcp_pre_hooks("block", "active");
        let ctx = ToolContext::new(SessionId::new())
            .with_mcp_invoker(StubMcpInvoker::new(McpBehavior::Timeout));
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "timeout must fail open"
        );
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_fails_open_on_unparseable_response() {
        let hooks = mcp_pre_hooks("block", "active");
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::new(
            McpBehavior::Result(json!("not json at all, no braces")),
        ));
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "unparseable response must fail open"
        );
    }

    #[tokio::test]
    async fn mcp_pre_tool_hook_skipped_without_invoker() {
        let hooks = mcp_pre_hooks("block", "active");
        // No MCP invoker wired into the context → mcp checks are skipped.
        let ctx = ToolContext::new(SessionId::new());
        let decision = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert!(
            matches!(decision, PreToolUseDecision::Continue(_)),
            "without an MCP invoker, mcp checks are silently skipped"
        );
    }

    #[tokio::test]
    async fn mcp_call_cap_evaluates_first_n_and_skips_rest() {
        // 6 active block checks, cap is 4. The recording invoker counts how many
        // times it is called; allow-verdict so none actually block.
        let checks: Vec<_> = (0..6)
            .map(|i| {
                json!({"id": format!("m{i}"), "stage": "tool_use", "type": "mcp",
                       "server": "guard", "tool": "screen"})
            })
            .collect();
        let hooks = GuardrailsCapability.pre_tool_use_hooks_with_config(&json!({
            "checks": checks
        }));
        // A counting invoker.
        struct Counter {
            calls: std::sync::atomic::AtomicUsize,
        }
        #[async_trait]
        impl crate::McpToolInvoker for Counter {
            async fn invoke(&self, tool_call: &ToolCall) -> crate::Result<ToolResult> {
                self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Ok(ToolResult {
                    tool_call_id: tool_call.id.clone(),
                    result: Some(json!({"verdict": "allow"})),
                    images: None,
                    error: None,
                    connection_required: None,
                    raw_output: None,
                })
            }
        }
        let counter = Arc::new(Counter {
            calls: std::sync::atomic::AtomicUsize::new(0),
        });
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(counter.clone());
        let _ = hooks[0]
            .before_exec(tool_call("any_tool", json!({})), &tool_def(), &ctx)
            .await;
        assert_eq!(
            counter.calls.load(std::sync::atomic::Ordering::SeqCst),
            MAX_MCP_CALLS_PER_INVOCATION,
            "only the first N mcp checks should be evaluated"
        );
    }

    #[tokio::test]
    async fn mcp_payload_truncated_on_char_boundary() {
        let hooks = mcp_pre_hooks("block", "active");
        let echo = StubMcpInvoker::new(McpBehavior::EchoContent);
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(echo.clone());
        // 700 × 3-byte chars = 2 100 bytes; the 2 000-byte cap falls mid-char.
        let multibyte = "".repeat(700);
        let decision = hooks[0]
            .before_exec(
                tool_call("any_tool", json!({"x": multibyte})),
                &tool_def(),
                &ctx,
            )
            .await;
        // Must not panic; echo result is not a valid verdict so it fails open.
        assert!(matches!(decision, PreToolUseDecision::Continue(_)));
        let call = echo
            .last_call
            .lock()
            .unwrap()
            .clone()
            .expect("invoker called");
        let sent = call.arguments["content"].as_str().unwrap();
        assert!(sent.len() <= MCP_CONTENT_CAP, "payload must be capped");
        assert!(
            std::str::from_utf8(sent.as_bytes()).is_ok(),
            "payload must remain valid UTF-8 (no mid-char split)"
        );
    }

    #[tokio::test]
    async fn mcp_post_tool_hook_withholds_output_on_block() {
        let hooks = GuardrailsCapability.post_tool_exec_hooks_with_config(&json!({
            "checks": [{"stage": "tool_output", "type": "mcp",
                        "server": "guard", "tool": "scan"}]
        }));
        assert_eq!(hooks.len(), 1);
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::block());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("user email: alice@example.com")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(
            result.result,
            Some(json!(DEFAULT_TOOL_OUTPUT_REPLACEMENT)),
            "mcp block should replace tool output with notice"
        );
        assert!(result.error.is_none());
    }

    #[tokio::test]
    async fn mcp_post_tool_hook_passes_clean_output_on_allow() {
        let hooks = GuardrailsCapability.post_tool_exec_hooks_with_config(&json!({
            "checks": [{"stage": "tool_output", "type": "mcp",
                        "server": "guard", "tool": "scan"}]
        }));
        let ctx = ToolContext::new(SessionId::new()).with_mcp_invoker(StubMcpInvoker::allow());
        let mut result = ToolResult {
            tool_call_id: "call_1".to_string(),
            result: Some(json!("no pii here")),
            images: None,
            error: None,
            connection_required: None,
            raw_output: None,
        };
        hooks[0]
            .after_exec(
                &tool_call("web_fetch", json!({})),
                &tool_def(),
                &mut result,
                &ctx,
            )
            .await;
        assert_eq!(result.result, Some(json!("no pii here")));
    }
}