agent-works 0.8.0

Batteries-included Agent toolbox built on agent-base
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
use super::NoopGuard;
use super::config::{DefaultGuardConfig, ReasoningOnlyAction};
use super::default::DefaultGuard;
use agent_base::engine::react_loop_guard::{GuardCtx, GuardDecision, ReactLoopGuard};
use agent_base::llm_trait::response::{
    ChatResponse, ChatStream, FinishReason as LlmFinishReason, StreamChunk,
};
use agent_base::llm_trait::{Capabilities, ChatRequest, LlmError, LlmProvider};
use agent_base::types::{FinishReason, SessionId};
use serde_json::Value;
use std::pin::Pin;
use std::sync::Arc;

fn make_ctx(
    reasoning_only_strikes: usize,
    empty_response_strikes: usize,
    run_has_tool_calls: bool,
    is_reasoning_only: bool,
    is_empty_response: bool,
    is_text_only: bool,
) -> GuardCtx {
    GuardCtx {
        session_id: SessionId {
            id: 1,
            external_id: None,
        },
        turn_count: 1,
        user_input: "test".to_string(),
        model_response: "response".to_string(),
        finish_reason: FinishReason::Stop,
        available_tools: vec![],
        reasoning_only_strikes,
        empty_response_strikes,
        run_has_tool_calls,
        last_tool_calls_invalid: false,
        all_user_inputs: vec!["test".to_string()],
        is_reasoning_only,
        is_empty_response,
        is_text_only,
        thinking_disabled: false,
        original_thinking_enabled: true,
        remaining_turns: 50,
    }
}

/// Build a GuardCtx with custom input/response text (for length-sensitive tests).
fn make_ctx_with_text(
    user_input: &str,
    model_response: &str,
    run_has_tool_calls: bool,
    is_text_only: bool,
) -> GuardCtx {
    GuardCtx {
        session_id: SessionId {
            id: 1,
            external_id: None,
        },
        turn_count: 2,
        user_input: user_input.to_string(),
        model_response: model_response.to_string(),
        finish_reason: FinishReason::Stop,
        available_tools: vec!["echo".to_string()],
        reasoning_only_strikes: 0,
        empty_response_strikes: 0,
        run_has_tool_calls,
        last_tool_calls_invalid: false,
        all_user_inputs: vec![user_input.to_string()],
        is_reasoning_only: false,
        is_empty_response: false,
        is_text_only,
        thinking_disabled: false,
        original_thinking_enabled: true,
        remaining_turns: 50,
    }
}

// ── Mock LLM clients for judge testing ──

/// Mock StreamClient that returns a fixed JSON response (for judge calls).
struct MockJudgeClient {
    response: String,
}

impl MockJudgeClient {
    fn new(response: Value) -> Self {
        Self {
            response: response.to_string(),
        }
    }
}

#[async_trait::async_trait]
impl LlmProvider for MockJudgeClient {
    async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
        let chunks = vec![
            Ok(StreamChunk::Text(self.response.clone())),
            Ok(StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            }),
        ];
        Ok(ChatStream::new(Box::pin(futures_util::stream::iter(
            chunks,
        ))))
    }

    async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
        Ok(ChatResponse {
            content: self.response.clone(),
            tool_calls: vec![],
            usage: agent_base::UsageInfo::default(),
            finish_reason: LlmFinishReason::Stop,
            raw: None,
            reasoning_content: None,
            thinking_signature: None,
        })
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities::default()
    }

    fn info(&self) -> agent_base::llm_trait::ProviderInfo {
        agent_base::llm_trait::ProviderInfo {
            name: "mock-judge".to_string(),
            model: "mock-model".to_string(),
            version: None,
        }
    }
}

/// Mock StreamClient that never resolves (for timeout testing).
struct MockTimeoutClient;

#[async_trait::async_trait]
impl LlmProvider for MockTimeoutClient {
    async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
        // Return a stream whose first item never resolves.
        struct HangingStream;
        impl futures_core::Stream for HangingStream {
            type Item = Result<StreamChunk, LlmError>;
            fn poll_next(
                self: Pin<&mut Self>,
                _cx: &mut std::task::Context<'_>,
            ) -> std::task::Poll<Option<Self::Item>> {
                std::task::Poll::Pending // never wakes
            }
        }
        Ok(ChatStream::new(Box::pin(HangingStream)))
    }

    async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
        // Never resolve — will be interrupted by timeout.
        std::future::pending().await
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities::default()
    }

    fn info(&self) -> agent_base::llm_trait::ProviderInfo {
        agent_base::llm_trait::ProviderInfo {
            name: "mock-timeout".to_string(),
            model: "mock-model".to_string(),
            version: None,
        }
    }
}

/// Mock StreamClient that always returns an error (for judge error testing).
struct MockErrorClient;

#[async_trait::async_trait]
impl LlmProvider for MockErrorClient {
    async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
        Err(LlmError::llm("simulated stream error"))
    }

    async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
        Err(LlmError::llm("simulated judge error"))
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities::default()
    }

    fn info(&self) -> agent_base::llm_trait::ProviderInfo {
        agent_base::llm_trait::ProviderInfo {
            name: "mock-error".to_string(),
            model: "mock-model".to_string(),
            version: None,
        }
    }
}

// ── Reasoning-only tests ──

#[tokio::test]
async fn test_reasoning_only_below_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(1, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(
        decision,
        GuardDecision::Continue { nudge: Some(_) }
    ));
}

#[tokio::test]
async fn test_reasoning_only_at_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(3, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Fail { .. }));
}

#[tokio::test]
async fn test_reasoning_only_with_tools_below_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let mut ctx = make_ctx(1, 0, false, true, false, false);
    ctx.available_tools = vec!["echo".to_string()];
    ctx.run_has_tool_calls = true;

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Continue { nudge: Some(_) }),
        "reasoning_only with tools, below threshold → Continue, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_reasoning_only_with_tools_at_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let mut ctx = make_ctx(3, 0, false, true, false, false);
    ctx.available_tools = vec!["echo".to_string()];
    ctx.run_has_tool_calls = true;

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "reasoning_only with tools, at threshold → Fail, got: {:?}",
        decision
    );
}

// ── Empty response tests ──

#[tokio::test]
async fn test_empty_response_below_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 1, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(
        decision,
        GuardDecision::Continue { nudge: Some(_) }
    ));
}

#[tokio::test]
async fn test_empty_response_at_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 3, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Fail { .. }));
}

#[tokio::test]
async fn test_empty_response_with_tool_calls() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 1, true, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Continue { nudge: Some(_) }),
        "empty response with tools → Continue (nudge), got: {:?}",
        decision
    );
}

// ── Text-only tests ──

#[tokio::test]
async fn test_text_only_without_tool_calls() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 0, false, false, false, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Complete));
}

#[tokio::test]
async fn test_text_only_with_tool_calls_no_llm_client() {
    let config = DefaultGuardConfig {
        use_llm_judge: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let ctx = make_ctx(0, 0, true, false, false, true);

    // No LLM client, judge_fail_open=false (default), should force continue
    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(
        decision,
        GuardDecision::Continue { nudge: Some(_) }
    ));
}

#[tokio::test]
async fn test_text_only_with_tool_calls_no_llm_client_fail_open() {
    let config = DefaultGuardConfig {
        use_llm_judge: true,
        judge_fail_open: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let ctx = make_ctx(0, 0, true, false, false, true);

    // No LLM client, judge_fail_open=true, should trust model (Complete)
    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Complete));
}

#[tokio::test]
async fn test_text_only_with_tool_calls_judge_disabled() {
    let config = DefaultGuardConfig {
        use_llm_judge: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let ctx = make_ctx(0, 0, true, false, false, true);

    // LLM judge disabled, should Complete
    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Complete));
}

#[tokio::test]
async fn test_text_only_no_tools_judge_enabled_no_client() {
    let config = DefaultGuardConfig {
        use_llm_judge: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let long_output = "x".repeat(300);
    let ctx = make_ctx_with_text("query", &long_output, false, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "no tools + judge enabled + no client → Complete (skips judge), got: {:?}",
        decision
    );
}

// ── Custom config tests ──

#[tokio::test]
async fn test_custom_config() {
    let config = DefaultGuardConfig {
        reasoning_only_max_strikes: 5,
        empty_response_max_strikes: 2,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // reasoning-only: 4 < 5, should continue
    let ctx = make_ctx(4, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(
        decision,
        GuardDecision::Continue { nudge: Some(_) }
    ));

    // empty response: 2 >= 2, should fail
    let ctx = make_ctx(0, 2, false, false, true, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(matches!(decision, GuardDecision::Fail { .. }));
}

// ── LLM judge tests ──

#[tokio::test]
async fn test_text_only_judge_says_done() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": true,
        "reason": "task is complete"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text("what is 2+2?", "The answer is 4.", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "judge says done → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_text_only_judge_says_not_done() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "only answered part of the question"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text(
        "list all files and explain each",
        "Here are the files:",
        true,
        true,
    );

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("incomplete"),
                "nudge should mention incomplete: {}",
                msg
            );
            assert!(
                msg.contains("only answered part"),
                "nudge should include judge reason: {}",
                msg
            );
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_text_only_judge_reason_propagated_to_nudge() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "missing file list and explanation"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text("list files and explain", "here are the files:", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("missing file list and explanation"),
                "nudge should include judge reason: {}",
                msg
            );
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

// ── Short response detection tests ──

#[tokio::test]
async fn test_text_only_short_response_detected_no_tools() {
    let long_input = "a".repeat(200);
    let short_output = "done";
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&long_input, short_output, false, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(msg.contains("incomplete"), "short response nudge: {}", msg);
        }
        other => panic!("expected Continue for short response, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_text_only_short_response_with_judge_done() {
    let long_input = "a".repeat(200);
    let short_output = "42";
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": true,
        "reason": "answer is correct"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text(&long_input, short_output, true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "short response + judge done → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_text_only_after_rejected_tool_calls_never_judges_complete() {
    // Session 20260904_efad759c: the truncation guard rejected a spawn_agent
    // call, the model answered with a fabricated text-only success narrative,
    // and the completion judge — blind to the rejected tool_result — passed
    // it, ending the run with zero children spawned. last_tool_calls_invalid
    // must short-circuit the judge: no client here, so a Complete decision
    // could only come from the old (buggy) judge path failing open.
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let mut ctx = make_ctx_with_text(
        "analyze 3 projects with sub-agents",
        "已启动 4 个子 agent 分析,稍后汇总。",
        true,
        true,
    );
    ctx.last_tool_calls_invalid = true;

    let decision = guard.on_turn(&ctx).await;
    match decision {
        GuardDecision::Continue { nudge: Some(msg) } => {
            assert!(
                msg.contains("NOT executed"),
                "nudge must tell the model the tool call never executed, got: {msg}"
            );
        }
        other => panic!(
            "text-only after rejected tool calls must Continue with a re-issue \
             nudge, got: {other:?}"
        ),
    }
}

// ── Skip threshold tests ──

#[tokio::test]
async fn test_text_only_skip_threshold() {
    let long_output = "x".repeat(300);
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "would be incomplete but skipped"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text("query", &long_output, true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "response >= skip_threshold → Complete without calling judge, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_text_only_skip_judge_when_input_too_large() {
    let long_input = "a".repeat(10_001);
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "would be incomplete but skipped"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text(&long_input, "short answer", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "input > 10k → skip judge → Complete, got: {:?}",
        decision
    );
}

// ── Judge timeout tests ──

#[tokio::test]
async fn test_text_only_judge_timeout_fail_open() {
    let judge_client = Arc::new(MockTimeoutClient);
    let config = DefaultGuardConfig {
        judge_fail_open: true,
        judge_timeout_secs: 1,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let ctx = make_ctx_with_text("query", "short answer", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "timeout + fail_open → Complete (trust model), got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_text_only_judge_timeout_fail_closed() {
    let judge_client = Arc::new(MockTimeoutClient);
    let config = DefaultGuardConfig {
        judge_fail_open: false,
        judge_timeout_secs: 1,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let ctx = make_ctx_with_text("query", "short answer", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "fail_closed timeout → Continue with verify message: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for timeout + fail_closed, got: {:?}",
            other
        ),
    }
}

// ── Judge error tests ──

#[tokio::test]
async fn test_text_only_judge_error_fail_closed() {
    let judge_client = Arc::new(MockErrorClient);
    let config = DefaultGuardConfig {
        judge_fail_open: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let ctx = make_ctx_with_text("query", "short", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "fail_closed error → Continue with verify message: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for judge error + fail_closed, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_text_only_judge_error_fail_open() {
    let judge_client = Arc::new(MockErrorClient);
    let config = DefaultGuardConfig {
        judge_fail_open: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let ctx = make_ctx_with_text("query", "short", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "fail_open + judge error → Complete (trust model), got: {:?}",
        decision
    );
}

// ── Short response + judge combination tests ──

#[tokio::test]
async fn test_text_only_short_response_judge_timeout_fail_closed() {
    let judge_client = Arc::new(MockTimeoutClient);
    let config = DefaultGuardConfig {
        judge_fail_open: false,
        judge_timeout_secs: 1,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let long_input = "a".repeat(200);
    let ctx = make_ctx_with_text(&long_input, "42", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "short + timeout + fail_closed → Continue: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for short response + timeout + fail_closed, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_text_only_short_response_judge_error_fail_closed() {
    let judge_client = Arc::new(MockErrorClient);
    let config = DefaultGuardConfig {
        judge_fail_open: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let long_input = "a".repeat(200);
    let ctx = make_ctx_with_text(&long_input, "42", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "short + error + fail_closed → Continue: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for short response + judge error + fail_closed, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_text_only_short_response_judge_error_fail_open() {
    let judge_client = Arc::new(MockErrorClient);
    let config = DefaultGuardConfig {
        judge_fail_open: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let long_input = "a".repeat(200);
    let ctx = make_ctx_with_text(&long_input, "42", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "short + error + fail_open → Complete, got: {:?}",
        decision
    );
}

// ── Multi-turn context tests ──

#[tokio::test]
async fn test_text_only_judge_with_multiple_user_messages() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "agent has not finished the task yet"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);

    let mut ctx = make_ctx_with_text("继续", "I'll continue working on it.", true, true);
    ctx.all_user_inputs = vec![
        "帮我分析一下这个 bug 的根因".to_string(),
        "好的,那你帮我修复一下".to_string(),
        "继续".to_string(),
    ];

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("incomplete"),
                "judge should see history and say incomplete: {}",
                msg
            );
        }
        other => panic!("expected Continue (judge says not done), got: {:?}", other),
    }
}

#[tokio::test]
async fn test_text_only_judge_respects_recent_user_count() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": true,
        "reason": "task complete"
    })));
    let config = DefaultGuardConfig {
        recent_user_count: 2,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);

    let mut ctx = make_ctx_with_text("继续", "done", true, true);
    ctx.all_user_inputs = vec![
        "msg1".to_string(),
        "msg2".to_string(),
        "msg3".to_string(),
        "msg4".to_string(),
        "继续".to_string(),
    ];

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "judge says done → Complete, got: {:?}",
        decision
    );
}

// ── Edge case: no scene flags ──

#[tokio::test]
async fn test_no_scene_flags_returns_complete() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 0, false, false, false, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "no scene flags → Complete, got: {:?}",
        decision
    );
}

// ═══════════════════════════════════════════════════════════════
// Phase 3: Boundary cases and coverage gaps
// ═══════════════════════════════════════════════════════════════

// ── Boundary: strikes = 0 (first occurrence) ──

#[tokio::test]
async fn test_reasoning_only_strikes_zero() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("reasoning") || msg.contains("tool call"),
                "nudge should mention the issue: {}",
                msg
            );
        }
        other => panic!("strikes=0 → Continue, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_empty_response_strikes_zero() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 0, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("empty") || msg.contains("response"),
                "nudge should mention empty response: {}",
                msg
            );
        }
        other => panic!("strikes=0 → Continue, got: {:?}", other),
    }
}

// ── Boundary: strikes = threshold - 1 (just below) ──

#[tokio::test]
async fn test_reasoning_only_just_below_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    // default threshold = 3, so 2 should Continue
    let ctx = make_ctx(2, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Continue { nudge: Some(_) }),
        "strikes=2, threshold=3 → Continue, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_empty_response_just_below_threshold() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 2, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Continue { nudge: Some(_) }),
        "strikes=2, threshold=3 → Continue, got: {:?}",
        decision
    );
}

// ── Nudge message content verification ──

#[tokio::test]
async fn test_reasoning_only_nudge_content() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(1, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert_eq!(msg, &DefaultGuardConfig::default().reasoning_only_nudge);
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_empty_response_nudge_content() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 1, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert_eq!(msg, &DefaultGuardConfig::default().empty_response_nudge);
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_short_response_nudge_content() {
    let long_input = "a".repeat(200);
    let short_output = "ok";
    let config = DefaultGuardConfig {
        use_llm_judge: false, // disable judge to get nudge path
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let ctx = make_ctx_with_text(&long_input, short_output, false, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert_eq!(msg, &DefaultGuardConfig::default().short_response_nudge);
        }
        other => panic!("expected Continue for short response, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_fail_error_message_reasoning_only() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(3, 0, false, true, false, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Fail { error } => {
            assert!(
                error.contains("reasoning"),
                "fail error should mention reasoning: {}",
                error
            );
        }
        other => panic!("expected Fail, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_fail_error_message_empty_response() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(0, 3, false, false, true, false);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Fail { error } => {
            assert!(
                error.contains("empty"),
                "fail error should mention empty: {}",
                error
            );
        }
        other => panic!("expected Fail, got: {:?}", other),
    }
}

// ── Config default values ──

#[test]
fn test_default_guard_config_values() {
    let config = DefaultGuardConfig::default();
    assert_eq!(config.reasoning_only_max_strikes, 3);
    assert_eq!(config.empty_response_max_strikes, 3);
    assert!(config.use_llm_judge);
    assert_eq!(config.judge_timeout_secs, 10);
    assert_eq!(config.judge_skip_threshold, 256);
    assert!(!config.judge_fail_open);
    assert!(config.detect_short_response);
    assert_eq!(config.short_response_min_input, 128);
    assert_eq!(config.short_response_max_output, 64);
    assert_eq!(config.recent_user_count, 5);
}

// ── Text-only: tools present + judge disabled ──

#[tokio::test]
async fn test_text_only_with_tools_judge_disabled_returns_complete() {
    let config = DefaultGuardConfig {
        use_llm_judge: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);
    let ctx = make_ctx(0, 0, true, false, false, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "tools + judge disabled → Complete, got: {:?}",
        decision
    );
}

// ── Text-only: short response without tools → nudge ──

#[tokio::test]
async fn test_text_only_short_response_without_tools_nudge() {
    let long_input = "a".repeat(200);
    let short_output = "done";
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&long_input, short_output, false, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            // Without tools, uses short_response_nudge
            assert!(
                msg.contains("incomplete"),
                "should use short_response_nudge: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for short response without tools, got: {:?}",
            other
        ),
    }
}

// ── Text-only: input shorter than output (not short response) ──

#[tokio::test]
async fn test_text_only_input_shorter_than_output_not_short() {
    let short_input = "hi";
    let long_output = "a".repeat(200);
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(short_input, &long_output, false, true);

    let decision = guard.on_turn(&ctx).await;
    // input_len (2) < output_len (200), and input_len (2) < min_input (128)
    // → not short response → no tools → Complete
    assert!(
        matches!(decision, GuardDecision::Complete),
        "short input + long output + no tools → Complete, got: {:?}",
        decision
    );
}

// ── Text-only: input just at short_response_min_input boundary ──

#[tokio::test]
async fn test_text_only_short_response_exact_min_input() {
    // Exactly at min_input (128) — uses strict `>`, so 128 > 128 is false → NOT short
    let input = "a".repeat(128);
    let output = "x"; // < max_output (64), and input_len > output_len
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&input, output, false, true);

    let decision = guard.on_turn(&ctx).await;
    // input_len=128 is NOT > min_input=128 (strict), so NOT short response
    // no tools → Complete
    assert!(
        matches!(decision, GuardDecision::Complete),
        "exact min_input (128 > 128 is false) → not short → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_text_only_short_response_just_above_min_input() {
    // One char above min_input — should trigger short response
    let input = "a".repeat(129);
    let output = "x";
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&input, output, false, true);

    let decision = guard.on_turn(&ctx).await;
    // input_len=129 > min_input=128, output=1 < max_output=64, 129 > 1
    // → short response → no tools → nudge
    match &decision {
        GuardDecision::Continue { nudge } => {
            assert!(nudge.is_some(), "just above min_input → short → nudge");
        }
        other => panic!(
            "expected Continue for just above boundary, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_text_only_not_short_response_just_below_min_input() {
    // One char below min_input — should NOT trigger short response
    let input = "a".repeat(127);
    let output = "x";
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&input, output, false, true);

    let decision = guard.on_turn(&ctx).await;
    // input_len=127 < min_input=128 → not short response → no tools → Complete
    assert!(
        matches!(decision, GuardDecision::Complete),
        "below min_input → not short → Complete, got: {:?}",
        decision
    );
}

// ── Text-only: output exactly at max_output boundary ──

#[tokio::test]
async fn test_text_only_short_response_output_at_max() {
    let input = "a".repeat(200);
    let output = "a".repeat(64); // exactly at max_output
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx_with_text(&input, &output, false, true);

    let decision = guard.on_turn(&ctx).await;
    // output_len=64 is NOT < max_output=64, so NOT short response
    // no tools → Complete
    assert!(
        matches!(decision, GuardDecision::Complete),
        "output at max_output → not short → Complete, got: {:?}",
        decision
    );
}

// ── Custom nudge messages ──

#[tokio::test]
async fn test_custom_nudge_messages() {
    let config = DefaultGuardConfig {
        reasoning_only_nudge: "custom reasoning nudge".to_string(),
        empty_response_nudge: "custom empty nudge".to_string(),
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // reasoning_only
    let ctx = make_ctx(1, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            assert_eq!(nudge.as_deref(), Some("custom reasoning nudge"));
        }
        other => panic!("expected Continue, got: {:?}", other),
    }

    // empty_response
    let ctx = make_ctx(0, 1, false, false, true, false);
    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            assert_eq!(nudge.as_deref(), Some("custom empty nudge"));
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

// ── Judge: malformed JSON response ──

#[tokio::test]
async fn test_judge_malformed_json_fail_closed() {
    // Mock that returns non-JSON
    struct MalformedJsonClient;
    #[async_trait::async_trait]
    impl LlmProvider for MalformedJsonClient {
        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
            let chunks = vec![
                Ok(StreamChunk::Text("not json at all".to_string())),
                Ok(StreamChunk::Stop {
                    finish_reason: Some("stop".to_string()),
                }),
            ];
            Ok(ChatStream::new(Box::pin(futures_util::stream::iter(
                chunks,
            ))))
        }
        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
            Ok(ChatResponse {
                content: "not json at all".to_string(),
                tool_calls: vec![],
                usage: agent_base::UsageInfo::default(),
                finish_reason: LlmFinishReason::Stop,
                raw: None,
                reasoning_content: None,
                thinking_signature: None,
            })
        }
        fn capabilities(&self) -> Capabilities {
            Capabilities::default()
        }
        fn info(&self) -> agent_base::llm_trait::ProviderInfo {
            agent_base::llm_trait::ProviderInfo {
                name: "malformed".to_string(),
                model: "malformed-model".to_string(),
                version: None,
            }
        }
    }

    let config = DefaultGuardConfig {
        judge_fail_open: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, Arc::new(MalformedJsonClient));
    let ctx = make_ctx_with_text("query", "short", true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "malformed JSON + fail_closed → Continue with verify: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for malformed JSON + fail_closed, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_judge_malformed_json_fail_open() {
    struct MalformedJsonClient;
    #[async_trait::async_trait]
    impl LlmProvider for MalformedJsonClient {
        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
            let chunks = vec![
                Ok(StreamChunk::Text("not json".to_string())),
                Ok(StreamChunk::Stop {
                    finish_reason: Some("stop".to_string()),
                }),
            ];
            Ok(ChatStream::new(Box::pin(futures_util::stream::iter(
                chunks,
            ))))
        }
        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
            Ok(ChatResponse {
                content: "not json".to_string(),
                tool_calls: vec![],
                usage: agent_base::UsageInfo::default(),
                finish_reason: LlmFinishReason::Stop,
                raw: None,
                reasoning_content: None,
                thinking_signature: None,
            })
        }
        fn capabilities(&self) -> Capabilities {
            Capabilities::default()
        }
        fn info(&self) -> agent_base::llm_trait::ProviderInfo {
            agent_base::llm_trait::ProviderInfo {
                name: "malformed".to_string(),
                model: "malformed-model".to_string(),
                version: None,
            }
        }
    }

    let config = DefaultGuardConfig {
        judge_fail_open: true,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, Arc::new(MalformedJsonClient));
    let ctx = make_ctx_with_text("query", "short", true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "malformed JSON + fail_open → Complete (trust model), got: {:?}",
        decision
    );
}

// ── Judge: partial JSON (missing fields) ──

#[tokio::test]
async fn test_judge_partial_json_missing_done() {
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "reason": "some reason"
        // missing "done" field
    })));
    let config = DefaultGuardConfig {
        judge_fail_open: false,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::with_llm_client(config, judge_client);
    let ctx = make_ctx_with_text("query", "short", true, true);

    let decision = guard.on_turn(&ctx).await;
    // serde will fail to deserialize because "done" is required
    // fail_closed → Continue
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("Cannot verify"),
                "missing field + fail_closed → Continue: {}",
                msg
            );
        }
        other => panic!(
            "expected Continue for partial JSON + fail_closed, got: {:?}",
            other
        ),
    }
}

// ── call_completion_judge direct tests ──

mod judge_function_tests {
    use super::super::judge::call_completion_judge;
    use super::*;

    /// Helper to cast a concrete Arc to Arc<dyn LlmProvider>.
    fn to_dyn<T: LlmProvider + 'static>(client: Arc<T>) -> Arc<dyn LlmProvider> {
        client
    }

    #[tokio::test]
    async fn test_judge_no_client_fail_open() {
        let result = call_completion_judge(
            None,
            "input",
            "response",
            &["input".to_string()],
            true, // fail_open
            10,
            5,
        )
        .await;

        assert!(result.is_ok());
        let judge = result.unwrap();
        assert!(judge.done, "no client + fail_open → done=true");
    }

    #[tokio::test]
    async fn test_judge_no_client_fail_closed() {
        let result = call_completion_judge(
            None,
            "input",
            "response",
            &["input".to_string()],
            false, // fail_closed
            10,
            5,
        )
        .await;

        assert!(result.is_err(), "no client + fail_closed → error");
    }

    #[tokio::test]
    async fn test_judge_with_valid_response() {
        let client = to_dyn(Arc::new(MockJudgeClient::new(serde_json::json!({
            "done": true,
            "reason": "all tasks complete"
        }))));

        let result = call_completion_judge(
            Some(&client),
            "do something",
            "done",
            &["do something".to_string()],
            false,
            10,
            5,
        )
        .await;

        assert!(result.is_ok());
        let judge = result.unwrap();
        assert!(judge.done);
        assert_eq!(judge.reason, "all tasks complete");
    }

    #[tokio::test]
    async fn test_judge_empty_user_inputs() {
        let client = to_dyn(Arc::new(MockJudgeClient::new(serde_json::json!({
            "done": false,
            "reason": "not enough context"
        }))));

        let result = call_completion_judge(
            Some(&client),
            "single input",
            "response",
            &[], // empty all_user_inputs
            false,
            10,
            5,
        )
        .await;

        assert!(result.is_ok());
        let judge = result.unwrap();
        assert!(!judge.done);
    }

    #[tokio::test]
    async fn test_judge_single_user_input() {
        let client = to_dyn(Arc::new(MockJudgeClient::new(serde_json::json!({
            "done": true,
            "reason": "complete"
        }))));

        let result = call_completion_judge(
            Some(&client),
            "only message",
            "response",
            &["only message".to_string()],
            false,
            10,
            5,
        )
        .await;

        assert!(result.is_ok());
        assert!(result.unwrap().done);
    }

    #[tokio::test]
    async fn test_judge_timeout_fail_open() {
        let client = to_dyn(Arc::new(MockTimeoutClient));

        let result = call_completion_judge(
            Some(&client),
            "input",
            "response",
            &["input".to_string()],
            true, // fail_open
            1,    // 1 second timeout
            5,
        )
        .await;

        assert!(result.is_ok(), "timeout + fail_open → Ok");
        assert!(result.unwrap().done);
    }

    #[tokio::test]
    async fn test_judge_timeout_fail_closed() {
        let client = to_dyn(Arc::new(MockTimeoutClient));

        let result = call_completion_judge(
            Some(&client),
            "input",
            "response",
            &["input".to_string()],
            false, // fail_closed
            1,
            5,
        )
        .await;

        assert!(result.is_err(), "timeout + fail_closed → Err");
    }

    #[tokio::test]
    async fn test_judge_error_fail_open() {
        let client = to_dyn(Arc::new(MockErrorClient));

        // fail_open=true → client errors also handled: trust model → Ok(done: true)
        let result = call_completion_judge(
            Some(&client),
            "input",
            "response",
            &["input".to_string()],
            true,
            10,
            5,
        )
        .await;

        assert!(result.is_ok(), "error + fail_open → Ok (trust model)");
        let judge = result.unwrap();
        assert!(judge.done, "fail_open → done=true");
        assert!(
            judge.reason.contains("trusting model"),
            "reason should mention trusting model: {}",
            judge.reason
        );
    }

    #[tokio::test]
    async fn test_judge_error_fail_closed() {
        let client = to_dyn(Arc::new(MockErrorClient));

        let result = call_completion_judge(
            Some(&client),
            "input",
            "response",
            &["input".to_string()],
            false,
            10,
            5,
        )
        .await;

        assert!(result.is_err(), "error + fail_closed → Err");
    }

    #[tokio::test]
    async fn test_judge_recent_user_count_truncation() {
        let client = to_dyn(Arc::new(MockJudgeClient::new(serde_json::json!({
            "done": true,
            "reason": "complete"
        }))));

        // recent_user_count=2 but 5 inputs → only last 2 used
        let result = call_completion_judge(
            Some(&client),
            "msg5",
            "response",
            &[
                "msg1".to_string(),
                "msg2".to_string(),
                "msg3".to_string(),
                "msg4".to_string(),
                "msg5".to_string(),
            ],
            false,
            10,
            2, // recent_user_count
        )
        .await;

        assert!(result.is_ok());
    }
}

// ── GuardDecision pattern matching ──

#[test]
fn test_guard_decision_continue_with_nudge() {
    let d = GuardDecision::Continue {
        nudge: Some("test nudge".to_string()),
    };
    match &d {
        GuardDecision::Continue { nudge } => {
            assert_eq!(nudge.as_deref(), Some("test nudge"));
        }
        _ => panic!("expected Continue"),
    }
}

#[test]
fn test_guard_decision_continue_without_nudge() {
    let d = GuardDecision::Continue { nudge: None };
    match &d {
        GuardDecision::Continue { nudge } => {
            assert!(nudge.is_none());
        }
        _ => panic!("expected Continue"),
    }
}

#[test]
fn test_guard_decision_complete() {
    let d = GuardDecision::Complete;
    assert!(matches!(d, GuardDecision::Complete));
}

#[test]
fn test_guard_decision_fail() {
    let d = GuardDecision::Fail {
        error: "something went wrong".to_string(),
    };
    match &d {
        GuardDecision::Fail { error } => {
            assert_eq!(error, "something went wrong");
        }
        _ => panic!("expected Fail"),
    }
}

// ── NoopGuard tests ──
// Note: NoopGuard returns Fail for reasoning_only/empty_response (safety),
// and Complete for text_only and normal scenarios.

#[tokio::test]
async fn test_noop_guard_normal_complete() {
    let guard = NoopGuard;
    let ctx = make_ctx(0, 0, false, false, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "NoopGuard normal → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_noop_guard_text_only_complete() {
    let guard = NoopGuard;
    let ctx = make_ctx(0, 0, false, false, false, true);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "NoopGuard text_only → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_noop_guard_reasoning_only_fails() {
    let guard = NoopGuard;
    let ctx = make_ctx(0, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "NoopGuard reasoning_only → Fail (safety), got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_noop_guard_empty_response_fails() {
    let guard = NoopGuard;
    let ctx = make_ctx(0, 0, false, false, true, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "NoopGuard empty_response → Fail (safety), got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_noop_guard_all_flags_reasoning_priority() {
    let guard = NoopGuard;
    let ctx = make_ctx(3, 3, true, true, true, true);
    let decision = guard.on_turn(&ctx).await;
    // reasoning_only || empty_response → Fail
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "NoopGuard all flags → Fail (reasoning/empty), got: {:?}",
        decision
    );
}

// ── Multiple scene flags set simultaneously ──

#[tokio::test]
async fn test_reasoning_only_takes_priority_over_empty() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    // Both reasoning_only and empty_response flags set
    let ctx = make_ctx(1, 1, false, true, true, false);

    let decision = guard.on_turn(&ctx).await;
    // on_turn checks is_reasoning_only first → should handle as reasoning_only
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert_eq!(msg, &DefaultGuardConfig::default().reasoning_only_nudge);
        }
        other => panic!(
            "reasoning_only takes priority, expected Continue, got: {:?}",
            other
        ),
    }
}

#[tokio::test]
async fn test_reasoning_only_takes_priority_over_text_only() {
    let guard = DefaultGuard::new(DefaultGuardConfig::default());
    let ctx = make_ctx(1, 0, false, true, false, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert_eq!(msg, &DefaultGuardConfig::default().reasoning_only_nudge);
        }
        other => panic!(
            "reasoning_only takes priority, expected Continue, got: {:?}",
            other
        ),
    }
}

// ── Short response + judge: non-short response fallback path ──

#[tokio::test]
async fn test_text_only_non_short_with_tools_judge_not_done() {
    // Response that's not short (> max_output=64) but < skip_threshold=256
    let medium_output = "a".repeat(100);
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "missing details"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text("query", &medium_output, true, true);

    let decision = guard.on_turn(&ctx).await;
    match &decision {
        GuardDecision::Continue { nudge } => {
            let msg = nudge.as_ref().unwrap();
            assert!(
                msg.contains("incomplete") && msg.contains("missing details"),
                "non-short + judge not done → Continue with reason: {}",
                msg
            );
        }
        other => panic!("expected Continue, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_text_only_non_short_with_tools_judge_done() {
    let medium_output = "a".repeat(100);
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": true,
        "reason": "task complete"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text("query", &medium_output, true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "non-short + judge done → Complete, got: {:?}",
        decision
    );
}

// ── Short response + skip_judge_when_input_too_large for short path ──

#[tokio::test]
async fn test_short_response_skip_judge_when_input_too_large() {
    let long_input = "a".repeat(10_001);
    let short_output = "42";
    let judge_client = Arc::new(MockJudgeClient::new(serde_json::json!({
        "done": false,
        "reason": "would be skipped"
    })));
    let guard = DefaultGuard::with_llm_client(DefaultGuardConfig::default(), judge_client);
    let ctx = make_ctx_with_text(&long_input, short_output, true, true);

    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "short response + input > 10k → skip judge → Complete, got: {:?}",
        decision
    );
}

// ── DisableThinking strategy tests ──────────────────────────────────────

#[tokio::test]
async fn test_disable_thinking_strategy_below_threshold() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        reasoning_only_max_strikes: 3,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Below threshold → Continue with nudge
    let ctx = make_ctx(2, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Continue { .. }),
        "below threshold → Continue, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_disable_thinking_strategy_at_threshold() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        reasoning_only_max_strikes: 3,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // At threshold → DisableThinking
    let ctx = make_ctx(3, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::DisableThinking { .. }),
        "at threshold → DisableThinking, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_disable_thinking_strategy_already_disabled() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        reasoning_only_max_strikes: 3,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Thinking already disabled but still reasoning-only → Fail
    let mut ctx = make_ctx(3, 0, false, true, false, false);
    ctx.thinking_disabled = true;
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "thinking disabled + reasoning-only → Fail, got: {:?}",
        decision
    );
}

// ── on_tool_call tests ──────────────────────────────────────────────────

#[tokio::test]
async fn test_on_tool_call_restores_thinking() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Thinking disabled + original enabled + tool call → RestoreThinking
    let mut ctx = make_ctx(0, 0, true, false, false, false);
    ctx.thinking_disabled = true;
    ctx.original_thinking_enabled = true;
    let decision = guard.on_tool_call(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::RestoreThinking),
        "thinking disabled + tool call → RestoreThinking, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_on_tool_call_no_restore_when_original_disabled() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Thinking disabled + original disabled + tool call → Complete
    let mut ctx = make_ctx(0, 0, true, false, false, false);
    ctx.thinking_disabled = true;
    ctx.original_thinking_enabled = false;
    let decision = guard.on_tool_call(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "original disabled + tool call → Complete, got: {:?}",
        decision
    );
}

#[tokio::test]
async fn test_on_tool_call_no_restore_when_thinking_enabled() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Thinking enabled + tool call → Complete
    let mut ctx = make_ctx(0, 0, true, false, false, false);
    ctx.thinking_disabled = false;
    ctx.original_thinking_enabled = true;
    let decision = guard.on_tool_call(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Complete),
        "thinking enabled + tool call → Complete, got: {:?}",
        decision
    );
}

// ── Fail strategy tests (default behavior) ──────────────────────────────

#[tokio::test]
async fn test_fail_strategy_at_threshold() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::Fail,
        reasoning_only_max_strikes: 3,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // At threshold → Fail
    let ctx = make_ctx(3, 0, false, true, false, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "at threshold → Fail, got: {:?}",
        decision
    );
}

// ── Empty response tests with DisableThinking ───────────────────────────

#[tokio::test]
async fn test_empty_response_with_disable_thinking_strategy() {
    let config = DefaultGuardConfig {
        reasoning_only_action: ReasoningOnlyAction::DisableThinking,
        empty_response_max_strikes: 3,
        ..DefaultGuardConfig::default()
    };
    let guard = DefaultGuard::new(config);

    // Empty response at threshold → Fail (even with DisableThinking strategy)
    let ctx = make_ctx(0, 3, false, false, true, false);
    let decision = guard.on_turn(&ctx).await;
    assert!(
        matches!(decision, GuardDecision::Fail { .. }),
        "empty response at threshold → Fail, got: {:?}",
        decision
    );
}