yoagent 0.26.6

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

use serde_json::json;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use yoagent::decision::*;
use yoagent::provider::mock::*;
use yoagent::provider::{
    CostConfig, MockProvider, ModelConfig, ProviderError, StreamConfig, StreamEvent, StreamProvider,
};
use yoagent::skills::SkillSet;
use yoagent::*;

/// The level-3 compaction marker (crate-private; `is_loop_injected` knows it).
const COMPACTION_MARKER_TEXT: &str =
    "[Context compacted: earlier messages removed to fit the context window]";

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// One request as the provider received it.
#[derive(Clone)]
struct Sent {
    system: String,
    messages: Vec<Message>,
    tools: usize,
}

impl Sent {
    /// Text of the last user message sent (hint notes included).
    fn last_user_text(&self) -> String {
        self.messages
            .iter()
            .rev()
            .find_map(|m| match m {
                Message::User { content, .. } => Some(
                    content
                        .iter()
                        .filter_map(|c| match c {
                            Content::Text { text } => Some(text.as_str()),
                            _ => None,
                        })
                        .collect::<Vec<_>>()
                        .join("|"),
                ),
                _ => None,
            })
            .unwrap_or_default()
    }
}

type Seen = Arc<Mutex<Vec<Sent>>>;

/// Records every request, then delegates.
struct Recording {
    inner: MockProvider,
    seen: Seen,
}

#[async_trait::async_trait]
impl StreamProvider for Recording {
    async fn stream(
        &self,
        config: StreamConfig,
        tx: mpsc::UnboundedSender<StreamEvent>,
        cancel: tokio_util::sync::CancellationToken,
    ) -> Result<Message, ProviderError> {
        self.seen.lock().unwrap().push(Sent {
            system: config.system_prompt.clone(),
            messages: config.messages.clone(),
            tools: config.tools.len(),
        });
        self.inner.stream(config, tx, cancel).await
    }
}

fn recording(inner: MockProvider) -> (Recording, Seen) {
    let seen: Seen = Arc::new(Mutex::new(Vec::new()));
    (
        Recording {
            inner,
            seen: seen.clone(),
        },
        seen,
    )
}

fn sent(seen: &Seen) -> Vec<Sent> {
    seen.lock().unwrap().clone()
}

/// A tool that records whether it ran.
struct Named {
    name: String,
    ran: Arc<Mutex<Vec<serde_json::Value>>>,
}

#[async_trait::async_trait]
impl AgentTool for Named {
    fn name(&self) -> &str {
        &self.name
    }
    fn label(&self) -> &str {
        &self.name
    }
    fn description(&self) -> &str {
        "A test tool."
    }
    fn parameters_schema(&self) -> serde_json::Value {
        json!({"type": "object"})
    }
    async fn execute(
        &self,
        params: serde_json::Value,
        _ctx: ToolContext,
    ) -> Result<ToolResult, ToolError> {
        self.ran.lock().unwrap().push(params);
        Ok(ToolResult {
            content: vec![Content::Text { text: "ok".into() }],
            details: serde_json::Value::Null,
        })
    }
}

type Ran = Arc<Mutex<Vec<serde_json::Value>>>;

fn make_tools(n: usize) -> (Vec<Box<dyn AgentTool>>, Ran) {
    let ran: Ran = Arc::new(Mutex::new(Vec::new()));
    let tools = (0..n)
        .map(|i| {
            Box::new(Named {
                name: if i == 0 {
                    "rm".into()
                } else {
                    format!("tool_{i}")
                },
                ran: ran.clone(),
            }) as Box<dyn AgentTool>
        })
        .collect();
    (tools, ran)
}

fn rm_call(args: serde_json::Value) -> MockResponse {
    MockResponse::ToolCalls(vec![MockToolCall {
        provider_metadata: None,
        name: "rm".into(),
        arguments: args,
    }])
}

/// The model calls `rm` once, then answers.
fn calls_rm() -> MockProvider {
    calls_rm_with(json!({"path": "/tmp/scratch.txt"}))
}

fn calls_rm_with(args: serde_json::Value) -> MockProvider {
    MockProvider::new(vec![rm_call(args), MockResponse::Text("done".into())])
}

fn skills(dir: &std::path::Path) -> SkillSet {
    for (name, desc) in [
        ("pdf-fill", "Fill in PDF forms."),
        ("git-release", "Cut a release with git tags."),
    ] {
        let d = dir.join(name);
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(
            d.join("SKILL.md"),
            format!("---\nname: {name}\ndescription: {desc}\n---\n\nSteps.\n"),
        )
        .unwrap();
    }
    SkillSet::load(&[dir]).unwrap()
}

/// Run one prompt; returns the agent and the run's `SessionStats`.
async fn run_stats(mut agent: Agent, prompt: &str) -> (Agent, SessionStats) {
    let mut rx = agent.prompt(prompt).await;
    let mut stats = None;
    while let Some(e) = rx.recv().await {
        if let AgentEvent::AgentEnd { stats: s, .. } = e {
            stats = Some(s);
        }
    }
    agent.finish().await;
    (agent, stats.expect("AgentEnd"))
}

async fn run(agent: Agent, prompt: &str) -> Agent {
    run_stats(agent, prompt).await.0
}

/// Every tool result's (text, is_error), in order.
fn tool_results(agent: &Agent) -> Vec<(String, bool)> {
    agent
        .messages()
        .iter()
        .filter_map(|m| match m {
            AgentMessage::Llm(Message::ToolResult {
                content, is_error, ..
            }) => match content.first() {
                Some(Content::Text { text }) => Some((text.clone(), *is_error)),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

fn tool_result_text(agent: &Agent) -> Option<(String, bool)> {
    tool_results(agent).into_iter().next()
}

/// Answers the advisory questions: `skill` picked by `pick(request)`,
/// `skill_needed` at `needed`, `tools` concentrated on three tools.
fn advisory_answers_by(pick: fn(&str) -> &'static str, needed: f64) -> MockBackend {
    MockBackend::from_fn(move |req| {
        // Judge the latest message when the request carries earlier context.
        let full = req.state["request"].as_str().unwrap_or_default();
        let request = full
            .rsplit("Latest user message: ")
            .next()
            .unwrap_or(full)
            .to_string();
        let mut eval = Evaluation::new("jev-test", DecisionUsage::new(100, 0));
        for (id, q) in &req.questions {
            match id.as_str() {
                "skill" => {
                    let opts = q.options().unwrap();
                    let chosen = pick(&request);
                    let rest = 0.1 / (opts.len() - 1) as f64;
                    eval = eval.with_answer(
                        id.clone(),
                        ChoiceAnswer::new(
                            opts.iter()
                                .map(|o| (o.to_string(), if *o == chosen { 0.9 } else { rest })),
                        ),
                    );
                }
                "skill_needed" => eval = eval.with_answer(id.clone(), NoulAnswer::new(needed)),
                "tools" => {
                    let opts = q.options().unwrap();
                    let p = |o: &str| match o {
                        "tool_7" => 0.5,
                        "tool_3" => 0.3,
                        "tool_9" => 0.15,
                        _ => 0.05 / (opts.len() - 3) as f64,
                    };
                    eval = eval.with_answer(
                        id.clone(),
                        ChoiceAnswer::new(opts.iter().map(|o| (o.to_string(), p(o)))),
                    );
                }
                other => panic!("unexpected advisory question {other}"),
            }
        }
        Ok(eval)
    })
}

fn advisory_answers(pick: &'static str, needed: f64) -> MockBackend {
    match pick {
        "pdf-fill" => advisory_answers_by(|_| "pdf-fill", needed),
        "none" => advisory_answers_by(|_| "none", needed),
        other => panic!("fixture: {other}"),
    }
}

/// Answers the gate's questions with fixed probabilities (`p` for any other
/// check id).
fn gate_answers(destructive: f64, requested: f64) -> MockBackend {
    MockBackend::from_fn(move |req| {
        let mut eval = Evaluation::new("jev-test", DecisionUsage::new(50, 0));
        for (id, _) in &req.questions {
            let p = match id.as_str() {
                "destructive" => destructive,
                "requested" => requested,
                _ => 0.0,
            };
            eval = eval.with_answer(id.clone(), NoulAnswer::new(p));
        }
        Ok(eval)
    })
}

/// A backend that never answers in time.
struct Slow;

#[async_trait::async_trait]
impl DecisionBackend for Slow {
    fn capabilities(&self) -> Capabilities {
        Capabilities::new(QuestionKind::all())
    }
    async fn evaluate(&self, _request: &Request) -> Result<Evaluation, DecisionError> {
        tokio::time::sleep(Duration::from_secs(30)).await;
        Err(DecisionError::transport("unreachable"))
    }
}

fn model(mock: &MockBackend) -> DecisionModel {
    DecisionModel::from_backend(mock.clone(), "jev-test")
}

// ---------------------------------------------------------------------------
// Advisory: skill hint
// ---------------------------------------------------------------------------

const SKILL_LINE: &str = "Relevant to the current request: pdf-fill. Ignore this if it does not \
                          fit what the user actually asked for.";

#[tokio::test]
async fn skill_hint_goes_to_the_latest_user_turn_and_asks_once_per_request() {
    let tmp = tempfile::tempdir().unwrap();
    let mock = advisory_answers("pdf-fill", 0.9);
    let (provider, seen) = recording(calls_rm());
    let (tools, _) = make_tools(1);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_system_prompt("Base.")
        .with_skills(skills(tmp.path()))
        .with_tools(tools)
        .with_decision_model(model(&mock));
    let base = agent.system_prompt.clone();
    let agent = run(agent, "fill in the tax form PDF").await;

    let sent = sent(&seen);
    assert_eq!(sent.len(), 2, "tool turn + final turn");
    for s in &sent {
        assert_eq!(s.system, base, "the system prompt is never touched");
        assert_eq!(
            s.last_user_text(),
            format!("fill in the tax form PDF|{SKILL_LINE}")
        );
    }
    // One decision request for the whole user request, batching both
    // questions; memoized for the second turn.
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 1);
    let ids: Vec<&str> = reqs[0]
        .questions
        .iter()
        .map(|(id, _)| id.as_str())
        .collect();
    assert_eq!(
        ids,
        ["skill", "skill_needed"],
        "no tool question under 40 tools"
    );
    assert_eq!(
        reqs[0].state,
        json!({"request": "fill in the tax form PDF"})
    );
    assert_eq!(
        reqs[0].get("skill").unwrap().options().unwrap(),
        ["git-release", "pdf-fill", "none"]
    );
    // Transient: never stored.
    for m in agent.messages() {
        assert!(!serde_json::to_string(m).unwrap().contains("Relevant to"));
    }
}

#[tokio::test]
async fn hints_keep_the_system_prompt_and_history_prefix_byte_identical() {
    let tmp = tempfile::tempdir().unwrap();
    let mock = advisory_answers_by(
        |r| {
            if r.contains("PDF") {
                "pdf-fill"
            } else {
                "git-release"
            }
        },
        0.9,
    );
    let (provider, seen) = recording(MockProvider::texts(vec!["a1", "a2"]));
    let history = vec![
        AgentMessage::Llm(Message::user("an earlier question")),
        AgentMessage::Llm(Message::assistant(
            vec![Content::Text {
                text: "an earlier answer".into(),
            }],
            StopReason::Stop,
            "mock",
            "mock",
            Usage::default(),
        )),
    ];
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_system_prompt("Base.")
        .with_skills(skills(tmp.path()))
        .with_messages(history.clone())
        .with_decision_model(model(&mock));
    let agent = run(agent, "fill in the PDF").await;
    let stored_before_second: Vec<Message> = agent
        .messages()
        .iter()
        .filter_map(|m| m.as_llm().cloned())
        .collect();
    let agent = run(agent, "cut the release").await;

    let sent = sent(&seen);
    assert_eq!(sent.len(), 2);
    assert_eq!(sent[0].system, sent[1].system, "identical system prompts");
    let h = serde_json::to_value(&history).unwrap();
    let prefix = |s: &Sent, n: usize| serde_json::to_value(&s.messages[..n]).unwrap();
    assert_eq!(prefix(&sent[0], 2), h);
    assert_eq!(prefix(&sent[1], 2), h);
    // Everything before the second request's latest user turn is exactly the
    // stored history — no earlier hint survives into it.
    let n = sent[1].messages.len() - 1;
    assert_eq!(
        prefix(&sent[1], n),
        serde_json::to_value(&stored_before_second).unwrap()
    );
    // Positive control: each request did carry its own, different hint.
    assert!(sent[0].last_user_text().contains("pdf-fill"));
    assert!(sent[1].last_user_text().contains("git-release"));
    assert!(!sent[1].last_user_text().contains("pdf-fill"));
    drop(agent);
}

#[tokio::test]
async fn skill_hint_stays_silent_when_not_confident() {
    for (pick, needed) in [("pdf-fill", 0.1), ("none", 0.9)] {
        let tmp = tempfile::tempdir().unwrap();
        let mock = advisory_answers(pick, needed);
        let (provider, seen) = recording(MockProvider::text("ok"));
        let agent = Agent::from_provider(provider, ModelConfig::mock())
            .with_skills(skills(tmp.path()))
            .with_decision_model(model(&mock));
        run(agent, "explain what a monad is").await;
        assert_eq!(mock.request_count(), 1, "asked");
        assert_eq!(
            sent(&seen)[0].last_user_text(),
            "explain what a monad is",
            "{pick}/{needed}: no note"
        );
    }
}

// ---------------------------------------------------------------------------
// Advisory: tool hint
// ---------------------------------------------------------------------------

#[tokio::test]
async fn tool_hint_names_the_top_tools_and_removes_none() {
    let mock = advisory_answers("none", 0.0);
    let (provider, seen) = recording(MockProvider::text("ok"));
    let (tools, _) = make_tools(45);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_system_prompt("Base.")
        .with_tools(tools)
        .with_decision_model(model(&mock));
    run(agent, "do the thing").await;

    let s = &sent(&seen)[0];
    assert_eq!(s.tools, 45, "every tool still offered");
    assert_eq!(s.system, "Base.");
    assert_eq!(
        s.last_user_text(),
        "do the thing|Tools likely relevant to the current request: tool_7, tool_3, tool_9. \
         This is a hint only; every tool remains available."
    );
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 1);
    let ids: Vec<&str> = reqs[0]
        .questions
        .iter()
        .map(|(id, _)| id.as_str())
        .collect();
    assert_eq!(ids, ["tools"], "no skills, so no skill questions");
    assert_eq!(reqs[0].get("tools").unwrap().options().unwrap().len(), 45);
}

#[tokio::test]
async fn tool_hint_threshold_is_configurable() {
    let mock = advisory_answers("none", 0.0);
    let (provider, seen) = recording(MockProvider::text("ok"));
    let (tools, _) = make_tools(12);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_tools(tools)
        .with_decision_advisory(
            Advisory::new(model(&mock))
                .with_tool_hint_min_tools(10)
                .with_max_tool_hints(1),
        );
    run(agent, "do the thing").await;
    assert_eq!(mock.request_count(), 1);
    assert!(sent(&seen)[0]
        .last_user_text()
        .contains("Tools likely relevant to the current request: tool_7. "));
}

#[test]
#[should_panic(expected = "must be a probability")]
fn advisory_thresholds_must_be_probabilities() {
    let _ = Advisory::new(DecisionModel::local("http://x")).with_skill_need_threshold(f64::NAN);
}

// ---------------------------------------------------------------------------
// Advisory fails open
// ---------------------------------------------------------------------------

#[tokio::test]
async fn advisory_errors_timeouts_and_missing_keys_add_nothing_and_are_counted() {
    let tmp = tempfile::tempdir().unwrap();
    // Error.
    let mock = MockBackend::new().push_error(DecisionError::http(500, "down"));
    let (provider, seen) = recording(MockProvider::text("answer"));
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_decision_model(model(&mock));
    let (agent, stats) = run_stats(agent, "fill in the PDF").await;
    assert_eq!(mock.request_count(), 1);
    assert_eq!(sent(&seen)[0].last_user_text(), "fill in the PDF");
    assert!(matches!(
        agent.messages().last(),
        Some(AgentMessage::Llm(Message::Assistant { .. }))
    ));
    assert_eq!((stats.decision.requests, stats.decision.failures), (1, 1));

    // Timeout: bounded by the advisory's limit, not the backend's.
    let (provider, seen) = recording(MockProvider::text("answer"));
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_decision_advisory(
            Advisory::new(DecisionModel::from_backend(Slow, "jev-test"))
                .with_timeout(Duration::from_millis(50)),
        );
    let start = Instant::now();
    let (_, stats) = run_stats(agent, "fill in the PDF").await;
    assert!(start.elapsed() < Duration::from_secs(5));
    assert_eq!(sent(&seen)[0].last_user_text(), "fill in the PDF");
    assert_eq!(
        (stats.decision.failures, stats.decision.timeouts),
        (1, 1),
        "{:?}",
        stats.decision
    );

    // A missing API key fails at first use, is counted, and sends nothing.
    let keyless = DecisionModel::from_backend(
        SystemOneBackend::typesafe()
            .with_base_url("http://127.0.0.1:9")
            .with_api_key_env("YOAGENT_DECISION_TEST_NEVER_SET"),
        "jev-latest",
    );
    let agent = Agent::from_provider(MockProvider::text("answer"), ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_decision_model(keyless);
    let (_, stats) = run_stats(agent, "fill in the PDF").await;
    assert_eq!((stats.decision.requests, stats.decision.failures), (1, 1));
}

// ---------------------------------------------------------------------------
// Nothing is sent when nothing needs asking
// ---------------------------------------------------------------------------

#[tokio::test]
async fn nothing_is_sent_without_skills_and_with_few_tools() {
    let mock = MockBackend::neutral();
    let (provider, seen) = recording(calls_rm());
    let (tools, ran) = make_tools(5);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_system_prompt("Base.")
        .with_tools(tools)
        .with_decision_model(model(&mock));
    let (_, stats) = run_stats(agent, "delete the scratch file").await;
    assert_eq!(mock.request_count(), 0, "no decision request");
    assert!(stats.decision.is_empty());
    assert_eq!(ran.lock().unwrap().len(), 1, "the tool ran: no gate");
    for s in sent(&seen) {
        assert_eq!(s.system, "Base.");
        assert_eq!(s.last_user_text(), "delete the scratch file");
    }

    // Positive control: the same agent with skills does ask.
    let tmp = tempfile::tempdir().unwrap();
    let (tools, _) = make_tools(5);
    let agent = Agent::from_provider(MockProvider::text("ok"), ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_tools(tools)
        .with_decision_model(model(&mock));
    run(agent, "delete the scratch file").await;
    assert_eq!(mock.request_count(), 1);
}

// ---------------------------------------------------------------------------
// Tool gate
// ---------------------------------------------------------------------------

fn gated(mock: &MockBackend) -> (Agent, Ran) {
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(mock)));
    (agent, ran)
}

#[tokio::test]
async fn gate_allows_a_destructive_call_the_user_asked_for() {
    let mock = gate_answers(0.95, 0.9);
    let (agent, ran) = gated(&mock);
    let agent = run(agent, "delete /tmp/scratch.txt").await;
    assert_eq!(ran.lock().unwrap().len(), 1, "allowed");
    assert!(!tool_result_text(&agent).unwrap().1, "not an error result");
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 1);
    assert_eq!(reqs[0].state["user_request"], "delete /tmp/scratch.txt");
    assert_eq!(reqs[0].state["tool_call"]["tool"], "rm");
    assert_eq!(
        reqs[0].state["tool_call"]["arguments"],
        json!({"path": "/tmp/scratch.txt"})
    );
    let ids: Vec<&str> = reqs[0]
        .questions
        .iter()
        .map(|(id, _)| id.as_str())
        .collect();
    assert_eq!(ids, ["destructive", "requested"]);
}

#[tokio::test]
async fn gate_allows_a_harmless_call_even_when_unrequested() {
    let mock = gate_answers(0.1, 0.1);
    let (agent, ran) = gated(&mock);
    run(agent, "what's in /tmp?").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn gate_denies_a_destructive_unrequested_call() {
    let mock = gate_answers(0.9, 0.2);
    let (agent, ran) = gated(&mock);
    let agent = run(agent, "summarize the README").await;
    assert!(ran.lock().unwrap().is_empty(), "denied: never ran");
    let (text, is_error) = tool_result_text(&agent).unwrap();
    assert!(is_error);
    assert!(text.contains("Tool gate"), "{text}");
    assert!(text.contains("destructive"), "{text}");
    assert!(matches!(
        agent.messages().last(),
        Some(AgentMessage::Llm(Message::Assistant { .. }))
    ));
}

#[tokio::test]
async fn gate_denies_malformed_answers() {
    type Answer = fn() -> Evaluation;
    let cases: [(&str, Answer); 5] = [
        ("NaN", || {
            Evaluation::new("m", DecisionUsage::default())
                .with_answer("destructive", NoulAnswer::new(0.0))
                .with_answer("requested", NoulAnswer::new(f64::NAN))
        }),
        ("negative", || {
            Evaluation::new("m", DecisionUsage::default())
                .with_answer("destructive", NoulAnswer::new(-0.5))
                .with_answer("requested", NoulAnswer::new(1.0))
        }),
        ("wrong kind", || {
            Evaluation::new("m", DecisionUsage::default())
                .with_answer(
                    "destructive",
                    ChoiceAnswer::new([("no", 1.0), ("yes", 0.0)]),
                )
                .with_answer("requested", NoulAnswer::new(1.0))
        }),
        ("missing", || {
            Evaluation::new("m", DecisionUsage::default())
                .with_answer("requested", NoulAnswer::new(1.0))
        }),
        ("NaN confidence", || {
            Evaluation::new("m", DecisionUsage::default())
                .with_answer("destructive", NoulAnswer::new(0.0))
                .with_answer(
                    "requested",
                    NoulAnswer::new(1.0).with_confidence(f64::INFINITY),
                )
        }),
    ];
    for (what, answer) in cases {
        let mock = MockBackend::from_fn(move |_| Ok(answer()));
        let (agent, ran) = gated(&mock);
        let agent = run(agent, "delete /tmp/scratch.txt").await;
        assert!(ran.lock().unwrap().is_empty(), "{what}: must deny");
        let (text, _) = tool_result_text(&agent).unwrap();
        assert!(text.contains("could not be consulted"), "{what}: {text}");
    }
    // Positive control: the same shape, well formed, is allowed.
    let mock = MockBackend::from_fn(|_| {
        Ok(Evaluation::new("m", DecisionUsage::default())
            .with_answer("destructive", NoulAnswer::new(0.0))
            .with_answer("requested", NoulAnswer::new(1.0)))
    });
    let (agent, ran) = gated(&mock);
    run(agent, "delete /tmp/scratch.txt").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn gate_fails_closed_on_error() {
    let mock = MockBackend::new().push_error(DecisionError::http(503, "unavailable"));
    let (agent, ran) = gated(&mock);
    let agent = run(agent, "delete /tmp/scratch.txt").await;
    assert!(ran.lock().unwrap().is_empty());
    let (text, is_error) = tool_result_text(&agent).unwrap();
    assert!(is_error);
    assert!(text.contains("could not be consulted"), "{text}");
    assert!(text.contains("fails closed"), "{text}");
}

#[tokio::test]
async fn gate_fails_closed_on_timeout() {
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(
            ToolGate::new(DecisionModel::from_backend(Slow, "jev-test"))
                .with_timeout(Duration::from_millis(50)),
        );
    let start = Instant::now();
    let (agent, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert!(start.elapsed() < Duration::from_secs(5));
    assert!(ran.lock().unwrap().is_empty());
    assert!(tool_result_text(&agent).unwrap().0.contains("timed out"));
    assert_eq!(stats.decision.timeouts, 1);
}

// --- long arguments --------------------------------------------------------

/// The arguments and `omitted` list of the first request the gate sent.
fn gate_saw(mock: &MockBackend) -> (serde_json::Value, serde_json::Value) {
    let call = &mock.requests()[0].state["tool_call"];
    (call["arguments"].clone(), call["omitted"].clone())
}

/// `decide` on a call outside the loop, with a run prompt to judge against.
async fn decide(gate: &ToolGate, tool: &str, args: serde_json::Value) -> ToolDecision {
    let prompts = [Message::user("rewrite the notes")];
    gate.decide(&ToolCallRequest::new("c1", tool, &args).with_run_prompts(&prompts))
        .await
}

fn denied_with(decision: &ToolDecision, needle: &str) -> bool {
    matches!(decision, ToolDecision::Deny(reason) if reason.contains(needle))
}

#[tokio::test]
async fn gate_sends_a_large_write_whole_when_it_fits() {
    // A full-file rewrite of 30k characters: judged on all of it.
    let content = format!("{}MIDDLE-MARK{}", "x".repeat(15_000), "y".repeat(15_000));
    let mock = gate_answers(0.1, 0.9);
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(
        calls_rm_with(json!({"path": "notes.md", "content": content})),
        ModelConfig::mock(),
    )
    .with_tools(tools)
    .with_tool_gate(ToolGate::new(model(&mock)));
    run(agent, "rewrite the notes").await;
    assert_eq!(ran.lock().unwrap().len(), 1, "allowed");
    let (args, omitted) = gate_saw(&mock);
    assert_eq!(args["content"], content.as_str(), "sent whole");
    assert!(omitted.is_null(), "nothing omitted: {omitted}");
}

#[tokio::test]
async fn gate_shortens_only_as_needed_and_says_what_it_cut() {
    let content = format!("{}END-OF-FILE", "x".repeat(100_000));
    let mock = gate_answers(0.1, 0.9);
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(
        calls_rm_with(json!({"path": "/etc/app/config.toml", "content": content, "append": false})),
        ModelConfig::mock(),
    )
    .with_tools(tools)
    .with_tool_gate(ToolGate::new(model(&mock)));
    run(agent, "update the config").await;
    assert_eq!(ran.lock().unwrap().len(), 1, "allowed");
    let (args, omitted) = gate_saw(&mock);
    assert_eq!(args["path"], "/etc/app/config.toml");
    assert_eq!(args["append"], false);
    let shown = args["content"].as_str().unwrap();
    assert!(shown.ends_with("END-OF-FILE"), "the tail is visible");
    assert!(shown.contains("[truncated "), "the cut is explicit");
    // Cut only as far as the 48,000-character budget needs, not to a fixed size.
    let sent = serde_json::to_string(&args).unwrap().chars().count();
    assert!((46_000..=48_000).contains(&sent), "{sent}");
    let cut = omitted[0]["chars"].as_u64().unwrap() as usize;
    assert_eq!(omitted[0]["argument"], "/content");
    assert_eq!(omitted.as_array().unwrap().len(), 1);
    assert!((50_000..56_000).contains(&cut), "cut {cut}");
    // Positive control: the executed call still got the full content.
    assert_eq!(
        ran.lock().unwrap()[0]["content"].as_str().unwrap().len(),
        content.len()
    );
}

#[tokio::test]
async fn gate_fits_the_backends_token_limits() {
    // A backend that takes at most 4,000 tokens of state plus question
    // (about 16,000 bytes): the call is cut to fit it, not refused by it.
    let mock = gate_answers(0.1, 0.9).with_capabilities(
        Capabilities::new(QuestionKind::all()).with_token_limits(None, Some(4_000)),
    );
    let gate = ToolGate::new(model(&mock));
    let content = "z".repeat(60_000);
    let decision = decide(
        &gate,
        "write_file",
        json!({"path": "a.md", "content": content}),
    )
    .await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    let state = &mock.requests()[0].state;
    let bytes = serde_json::to_vec(state).unwrap().len();
    assert!((12_000..16_000).contains(&bytes), "{bytes}");
    assert_eq!(state["tool_call"]["omitted"][0]["argument"], "/content");
}

#[tokio::test]
async fn gate_reads_a_command_whole_or_not_at_all() {
    // `bash`'s command is a full view by default: a dangerous line can sit
    // anywhere in it, so it is never judged from its head and tail.
    let command = |filler: usize| {
        format!(
            "echo start\n{}rm -rf ~\n{}echo done",
            "true\n".repeat(filler),
            "true\n".repeat(filler)
        )
    };
    let mock = gate_answers(0.9, 0.1);
    let gate = ToolGate::new(model(&mock));

    // Fits: sent whole, the middle line included.
    let decision = decide(&gate, "bash", json!({"command": command(2_000)})).await;
    assert!(denied_with(&decision, "looks destructive"), "{decision:?}");
    let (args, omitted) = gate_saw(&mock);
    assert!(args["command"].as_str().unwrap().contains("rm -rf ~"));
    assert!(omitted.is_null());

    // Does not fit: denied without asking.
    let decision = decide(&gate, "bash", json!({"command": command(10_000)})).await;
    assert!(
        denied_with(&decision, "`bash`'s `/command` argument is"),
        "{decision:?}"
    );
    assert!(denied_with(&decision, "review in full"), "{decision:?}");
    assert_eq!(
        mock.request_count(),
        1,
        "the oversized command was never sent"
    );

    // Without the default full view the same call is judged shortened.
    let gate = ToolGate::new(model(&mock)).without_default_full_views();
    decide(&gate, "bash", json!({"command": command(10_000)})).await;
    assert_eq!(mock.request_count(), 2);
    assert!(mock.requests()[1].state["tool_call"]["omitted"].is_array());
}

#[tokio::test]
async fn gate_full_views_cover_custom_tools_and_whole_subtrees() {
    let mock = gate_answers(0.1, 0.9);
    let gate = ToolGate::new(model(&mock)).with_full_view("sql", "/queries");
    let big = "SELECT 1; ".repeat(3_000); // 30k each: the two together do not fit
                                          // Everything under `/queries` is a full view; `/note` is not.
    let args = json!({"queries": [big.clone()], "note": big.clone()});
    let decision = decide(&gate, "sql", args).await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    let (args, omitted) = gate_saw(&mock);
    assert_eq!(args["queries"][0], big.as_str(), "full view kept whole");
    assert_eq!(omitted[0]["argument"], "/note");
    // Another tool's arguments of the same name are not full views.
    let decision = decide(&gate, "other", json!({"queries": [big.clone(), big]})).await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
}

#[tokio::test]
#[should_panic(expected = "JSON pointer")]
async fn gate_full_view_must_be_a_pointer() {
    let _ = ToolGate::new(model(&MockBackend::new())).with_full_view("bash", "command");
}

#[tokio::test]
async fn gate_denies_arguments_too_large_to_read() {
    // 200 strings of 500 characters: even cut to 400 each, over the budget.
    let fields: serde_json::Map<String, serde_json::Value> = (0..200)
        .map(|i| (format!("f{i}"), json!("y".repeat(500))))
        .collect();
    let mock = gate_answers(0.0, 1.0);
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm_with(json!(fields)), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let agent = run(agent, "go").await;
    assert!(ran.lock().unwrap().is_empty());
    assert!(tool_result_text(&agent).unwrap().0.contains("too large"));
    assert_eq!(mock.request_count(), 0, "denied before asking");
}

#[tokio::test]
async fn gate_budget_is_configurable() {
    let mock = gate_answers(0.1, 0.9);
    let gate = ToolGate::new(model(&mock)).with_max_argument_chars(100_000);
    let content = "q".repeat(90_000);
    decide(
        &gate,
        "write_file",
        json!({"path": "a", "content": content}),
    )
    .await;
    let (args, omitted) = gate_saw(&mock);
    assert_eq!(args["content"], content.as_str());
    assert!(omitted.is_null());
}

// --- what the user asked -----------------------------------------------------

/// Requested only when the state shows the confirmation of a deletion.
fn confirmation_aware() -> MockBackend {
    MockBackend::from_fn(|req| {
        let ur = req.state["user_request"].as_str().unwrap_or_default();
        let confirmed = ur.contains("Latest user message: yes, go ahead")
            && ur.contains("Should I delete /tmp/scratch.txt?")
            && ur.contains("Earlier user request: clean up the workspace");
        Ok(Evaluation::new("m", DecisionUsage::default())
            .with_answer("destructive", NoulAnswer::new(0.9))
            .with_answer(
                "requested",
                NoulAnswer::new(if confirmed { 0.95 } else { 0.1 }),
            ))
    })
}

#[tokio::test]
async fn a_confirmation_after_a_denial_is_allowed() {
    let mock = confirmation_aware();
    let (tools, ran) = make_tools(1);
    let provider = MockProvider::new(vec![
        rm_call(json!({"path": "/tmp/scratch.txt"})),
        MockResponse::Text("The gate blocked that. Should I delete /tmp/scratch.txt?".into()),
        rm_call(json!({"path": "/tmp/scratch.txt"})),
        MockResponse::Text("Deleted.".into()),
    ]);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let agent = run(agent, "clean up the workspace").await;
    assert!(ran.lock().unwrap().is_empty(), "first attempt denied");
    let agent = run(agent, "yes, go ahead").await;
    assert_eq!(ran.lock().unwrap().len(), 1, "confirmed attempt allowed");
    let results = tool_results(&agent);
    assert!(results[0].1 && !results[1].1, "{results:?}");
    let reqs = mock.requests();
    assert_eq!(reqs[0].state["user_request"], "clean up the workspace");
}

#[tokio::test]
async fn a_loop_nudge_does_not_become_the_user_request() {
    let mock = gate_answers(0.1, 0.9);
    let (tools, _) = make_tools(1);
    let same = json!({"path": "/tmp/a"});
    let provider = MockProvider::new(vec![
        rm_call(same.clone()),
        rm_call(same.clone()),
        rm_call(same),
        rm_call(json!({"path": "/tmp/b"})),
        MockResponse::Text("done".into()),
    ]);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let agent = run(agent, "tidy up the temp directory please").await;
    // Positive control: the loop did inject its nudge before the last call.
    let nudged = agent.messages().iter().any(|m| {
        serde_json::to_string(m)
            .unwrap()
            .contains("[You have called ")
    });
    assert!(nudged, "loop detection nudged");
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 4);
    for r in &reqs {
        assert_eq!(r.state["user_request"], "tidy up the temp directory please");
    }
}

// --- configuration -------------------------------------------------------

#[tokio::test]
async fn gate_thresholds_and_checks_are_overridable() {
    // A stricter requested threshold turns the allow above into a deny.
    let mock = gate_answers(0.95, 0.9);
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)).with_requested_threshold(0.95));
    run(agent, "delete /tmp/scratch.txt").await;
    assert!(ran.lock().unwrap().is_empty());

    // An added check denies on its own.
    let mock = MockBackend::from_fn(|req| {
        let mut eval = Evaluation::new("m", DecisionUsage::default());
        for (id, _) in &req.questions {
            let p = if id == "secrets" { 0.8 } else { 0.0 };
            eval = eval.with_answer(id.clone(), NoulAnswer::new(p));
        }
        Ok(eval)
    });
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)).with_check(
            "secrets",
            "Does `tool_call` read or send credentials?",
            0.5,
        ));
    let agent = run(agent, "clean up").await;
    assert!(ran.lock().unwrap().is_empty());
    assert!(tool_result_text(&agent).unwrap().0.contains("`secrets`"));
    assert_eq!(mock.requests()[0].questions.len(), 3);
}

#[test]
#[should_panic(expected = "collides with a built-in question")]
fn a_check_cannot_reuse_a_built_in_id() {
    let _ = ToolGate::new(DecisionModel::local("http://x")).with_check("requested", "q?", 0.5);
}

#[test]
#[should_panic(expected = "used twice")]
fn a_check_id_cannot_repeat() {
    let _ = ToolGate::new(DecisionModel::local("http://x"))
        .with_check("a", "q?", 0.5)
        .with_check("a", "r?", 0.5);
}

#[test]
#[should_panic(expected = "must be a probability")]
fn gate_thresholds_must_be_probabilities() {
    let _ = ToolGate::new(DecisionModel::local("http://x")).with_destructive_threshold(f64::NAN);
}

#[test]
#[should_panic(expected = "must be a probability")]
fn check_thresholds_must_be_probabilities() {
    let _ = ToolGate::new(DecisionModel::local("http://x")).with_check("c", "q?", 1.5);
}

/// Rewrites every call's path.
struct Sandbox;

#[async_trait::async_trait]
impl ToolMiddleware for Sandbox {
    async fn before_tool(&self, _call: &ToolCallRequest<'_>) -> ToolDecision {
        ToolDecision::Modify(json!({"path": "/sandbox/scratch.txt"}))
    }
}

#[tokio::test]
async fn gate_runs_after_user_middleware() {
    let mock = gate_answers(0.1, 0.9);
    let (tools, ran) = make_tools(1);
    // The gate is set *before* the user middleware is added, and still runs
    // last.
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)))
        .with_tool_middleware(Sandbox);
    run(agent, "delete it").await;
    assert_eq!(
        mock.requests()[0].state["tool_call"]["arguments"],
        json!({"path": "/sandbox/scratch.txt"})
    );
    assert_eq!(
        ran.lock().unwrap()[0],
        json!({"path": "/sandbox/scratch.txt"})
    );
}

#[tokio::test]
async fn sub_agent_gate_denies_its_own_calls() {
    let mock = gate_answers(0.9, 0.1);
    let ran: Ran = Arc::new(Mutex::new(Vec::new()));
    let sub = SubAgentTool::from_provider("helper", Arc::new(calls_rm()), ModelConfig::mock())
        .with_tools(vec![Arc::new(Named {
            name: "rm".into(),
            ran: ran.clone(),
        })])
        .with_tool_gate(ToolGate::new(model(&mock)));
    let result = sub
        .execute(
            json!({"task": "tidy up"}),
            ToolContext::new("call-1", "helper"),
        )
        .await;
    assert!(result.is_ok(), "{result:?}");
    assert!(
        ran.lock().unwrap().is_empty(),
        "the sub-agent's rm was denied"
    );
    assert_eq!(mock.request_count(), 1);
    // In a sub-agent, the "user request" is the parent model's task text.
    assert_eq!(mock.requests()[0].state["user_request"], "tidy up");
}

// ---------------------------------------------------------------------------
// Spend
// ---------------------------------------------------------------------------

#[tokio::test]
async fn advisory_and_gate_spend_is_reported_in_session_stats() {
    let tmp = tempfile::tempdir().unwrap();
    // Answers both the advisory and the gate questions.
    let mock = MockBackend::from_fn(|req| {
        let mut eval = Evaluation::new("jev-test", DecisionUsage::new(1_000, 0));
        for (id, q) in &req.questions {
            eval = match q.kind() {
                QuestionKind::Choice => {
                    let opts = q.options().unwrap();
                    let p = 1.0 / opts.len() as f64;
                    eval.with_answer(
                        id.clone(),
                        ChoiceAnswer::new(opts.iter().map(|o| (o.to_string(), p))),
                    )
                }
                _ => eval.with_answer(
                    id.clone(),
                    NoulAnswer::new(if id == "requested" { 1.0 } else { 0.0 }),
                ),
            };
        }
        Ok(eval)
    });
    let priced = model(&mock).with_cost(Some(CostConfig::new(1.0, 0.0)));
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_tools(tools)
        .with_decision_model(priced.clone())
        .with_tool_gate(ToolGate::new(priced));
    let (agent, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
    let d = &stats.decision;
    assert_eq!(d.requests, 2, "one advisory + one gate request: {d:?}");
    assert_eq!(d.failures, 0);
    assert_eq!(d.usage.input, 2_000);
    let cost = d.cost_usd.expect("priced");
    assert!((cost - 0.002).abs() < 1e-12, "{cost}");
    // Part of the whole bill (the mock LLM spent nothing).
    assert_eq!(stats.total_cost_usd(), Some(cost));
    assert_eq!(agent.total_cost_usd(), Some(cost));

    // Unpriced decision spend makes the bill unknown, never low.
    let (tools, _) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&gate_answers(0.0, 1.0))));
    let (_, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert!(stats.decision.is_unpriced());
    assert_eq!(stats.total_cost_usd(), None);
}

/// A `Budget` counts the gate's spend at the decision model's own rates, and
/// an unpriced decision model's at the budget's rates.
#[tokio::test]
async fn a_budget_counts_the_gate_spend() {
    // 50 input tokens per evaluation (`gate_answers`).
    for (gate_cost, expected) in [
        (Some(CostConfig::new(1_000.0, 0.0)), 0.05),
        (None, 50.0 * 2.0 / 1e6),
    ] {
        let budget = Arc::new(
            yoagent::extension::Budget::usd(f64::INFINITY, CostConfig::new(2.0, 0.0)).across_runs(),
        );
        let (tools, ran) = make_tools(1);
        let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
            .with_tools(tools)
            .with_extension(Arc::clone(&budget))
            .with_tool_gate(ToolGate::new(
                model(&gate_answers(0.0, 1.0)).with_cost(gate_cost.clone()),
            ));
        let (_, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
        assert_eq!(ran.lock().unwrap().len(), 1);
        assert_eq!(stats.decision.requests, 1);
        let spent = budget.spent_usd().unwrap();
        assert!((spent - expected).abs() < 1e-12, "{gate_cost:?}: {spent}");
    }
}

/// The limit acts on gate spend: the model itself costs nothing here, so
/// only the gate's evaluation can stop the run before its second request.
#[tokio::test]
async fn gate_spend_can_stop_a_run_on_budget() {
    let (tools, ran) = make_tools(1);
    let mut agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_extension(yoagent::extension::Budget::usd(
            0.05,
            CostConfig::new(1.0, 0.0),
        ))
        .with_tool_gate(ToolGate::new(
            model(&gate_answers(0.0, 1.0)).with_cost(Some(CostConfig::new(1_000.0, 0.0))),
        ));
    let mut rx = agent.prompt("delete /tmp/scratch.txt").await;
    let mut last = Vec::new();
    while let Some(e) = rx.recv().await {
        if let AgentEvent::AgentEnd { messages, .. } = e {
            last = messages;
        }
    }
    agent.finish().await;
    assert_eq!(ran.lock().unwrap().len(), 1, "the call was allowed and ran");
    assert!(
        matches!(last.last(), Some(AgentMessage::Llm(Message::User { content, .. }))
            if matches!(content.first(), Some(Content::Text { text })
                if text.starts_with("[Agent stopped: budget"))),
        "stopped before the second request: {last:?}"
    );
}

// --- compaction must not make the gate judge an older request ------------

/// Keeps the session's head, a marker, and the last two messages — the
/// shape level-3 compaction and `LlmCompaction` leave — on every turn, so
/// the run's own prompt is dropped after the first turn.
struct HeadMarkerTail(&'static str);

impl yoagent::context::CompactionStrategy for HeadMarkerTail {
    fn compact(
        &self,
        messages: Vec<AgentMessage>,
        _config: &yoagent::context::ContextConfig,
    ) -> Vec<AgentMessage> {
        if messages.len() <= 4 {
            return messages;
        }
        let mut out = vec![
            messages[0].clone(),
            AgentMessage::Llm(Message::user(self.0)),
        ];
        out.extend_from_slice(&messages[messages.len() - 2..]);
        out
    }
}

/// Requested only when the user's request asks for the deletion.
fn deletion_aware() -> MockBackend {
    MockBackend::from_fn(|req| {
        let ur = req.state["user_request"].as_str().unwrap_or_default();
        let asked = ur.contains("delete every file in /srv/prod");
        Ok(Evaluation::new("m", DecisionUsage::default())
            .with_answer("destructive", NoulAnswer::new(0.9))
            .with_answer("requested", NoulAnswer::new(if asked { 0.95 } else { 0.1 })))
    })
}

/// Seeds a session whose FIRST prompt asked for a destructive deletion, runs
/// `prompt` under head+marker+tail compaction, and returns how many of the
/// two `rm` calls ran plus the gate's `user_request`s.
async fn compacted_run(marker: &'static str, prompt: &str) -> (usize, Vec<String>) {
    let mock = deletion_aware();
    let (tools, ran) = make_tools(1);
    let args = json!({"path": "/srv/prod"});
    let provider = MockProvider::new(vec![
        rm_call(args.clone()),
        rm_call(args),
        MockResponse::Text("done".into()),
    ]);
    let head = vec![
        AgentMessage::Llm(Message::user("delete every file in /srv/prod")),
        AgentMessage::Llm(Message::assistant(
            vec![Content::Text {
                text: "I will not do that without a backup.".into(),
            }],
            StopReason::Stop,
            "mock",
            "mock",
            Usage::default(),
        )),
    ];
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_messages(head)
        .with_tools(tools)
        .with_compaction_strategy(HeadMarkerTail(marker))
        .with_tool_gate(ToolGate::new(model(&mock)));
    run(agent, prompt).await;
    let requests = mock
        .requests()
        .iter()
        .map(|r| {
            r.state["user_request"]
                .as_str()
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    let ran = ran.lock().unwrap().len();
    (ran, requests)
}

#[tokio::test]
async fn compaction_does_not_make_the_first_prompt_the_request() {
    let llm_summary = "[Context compacted — summary of earlier conversation]\n\nThe user \
                       asked to list files; the assistant began.";
    for marker in [
        COMPACTION_MARKER_TEXT,
        yoagent::llm_compaction::SUMMARY_MARKER,
        llm_summary,
    ] {
        let prompt = "list the files under /srv/prod, change nothing";
        let (ran, requests) = compacted_run(marker, prompt).await;
        assert_eq!(requests.len(), 2, "{marker}");
        // After compaction dropped the run's prompt, the gate judges against
        // the run prompt — never the session's first, unrelated request.
        for r in &requests {
            assert_eq!(r, prompt, "{marker}");
        }
        assert_eq!(ran, 0, "{marker}: neither destructive call was requested");

        // Positive control: when the run's prompt does ask for the deletion,
        // the same compacted history allows it.
        let (ran, requests) = compacted_run(marker, "delete every file in /srv/prod").await;
        assert_eq!(ran, 2, "{marker}: {requests:?}");
    }
}

#[tokio::test]
async fn gate_denies_when_no_user_request_survives() {
    // A continued run (no prompts) over a history compacted down to its
    // head: nothing after the marker says what the user wants now.
    let mock = gate_answers(0.0, 1.0);
    let (tools, ran) = make_tools(1);
    let mut agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_messages(vec![
            AgentMessage::Llm(Message::user("delete every file in /srv/prod")),
            AgentMessage::Llm(Message::user(COMPACTION_MARKER_TEXT)),
        ])
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let mut rx = agent.continue_loop().await;
    while rx.recv().await.is_some() {}
    agent.finish().await;
    assert!(ran.lock().unwrap().is_empty());
    let (text, _) = tool_result_text(&agent).unwrap();
    assert!(text.contains("restate the request"), "{text}");
    assert_eq!(mock.request_count(), 0, "denied before asking");

    // Positive control: the same history continued after a real user
    // message is judged normally.
    let mock = gate_answers(0.0, 1.0);
    let (tools, ran) = make_tools(1);
    let mut agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_messages(vec![
            AgentMessage::Llm(Message::user("delete every file in /srv/prod")),
            AgentMessage::Llm(Message::user(COMPACTION_MARKER_TEXT)),
            AgentMessage::Llm(Message::user("list /tmp")),
        ])
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let mut rx = agent.continue_loop().await;
    while rx.recv().await.is_some() {}
    agent.finish().await;
    assert_eq!(ran.lock().unwrap().len(), 1);
    assert_eq!(mock.requests()[0].state["user_request"], "list /tmp");
}

// ---------------------------------------------------------------------------
// Round 4: consent, merging, filters, spend
// ---------------------------------------------------------------------------

fn image_only() -> AgentMessage {
    AgentMessage::Llm(Message::User {
        content: vec![Content::Image {
            data: "iVBORw0KGgo=".into(),
            mime_type: "image/png".into(),
        }],
        timestamp: 0,
    })
}

/// Requested only when the request names the deletion of /tmp/scratch.txt.
fn names_the_deletion() -> MockBackend {
    MockBackend::from_fn(|req| {
        let ur = req.state["user_request"].as_str().unwrap_or_default();
        Ok(Evaluation::new("m", DecisionUsage::default())
            .with_answer("destructive", NoulAnswer::new(0.9))
            .with_answer(
                "requested",
                NoulAnswer::new(if ur.contains("delete /tmp/scratch.txt") {
                    0.95
                } else {
                    0.1
                }),
            ))
    })
}

async fn run_after_earlier_request(prompt: AgentMessage) -> (Agent, Ran, MockBackend) {
    let mock = names_the_deletion();
    let (tools, ran) = make_tools(1);
    let mut agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_messages(vec![
            AgentMessage::Llm(Message::user("delete /tmp/scratch.txt")),
            AgentMessage::Llm(Message::assistant(
                vec![Content::Text {
                    text: "Done.".into(),
                }],
                StopReason::Stop,
                "mock",
                "mock",
                Usage::default(),
            )),
        ])
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)));
    let mut rx = agent.prompt_messages(vec![prompt]).await;
    while rx.recv().await.is_some() {}
    agent.finish().await;
    (agent, ran, mock)
}

#[tokio::test]
async fn an_image_only_prompt_never_borrows_an_earlier_runs_consent() {
    let (agent, ran, mock) = run_after_earlier_request(image_only()).await;
    assert!(ran.lock().unwrap().is_empty(), "denied");
    let (text, _) = tool_result_text(&agent).unwrap();
    assert!(text.contains("restate the request"), "{text}");
    assert_eq!(mock.request_count(), 0, "nothing to judge against");

    // Positive control: the same history with a text prompt that asks for
    // the deletion is allowed.
    let (_, ran, _) =
        run_after_earlier_request(AgentMessage::Llm(Message::user("delete /tmp/scratch.txt")))
            .await;
    assert_eq!(ran.lock().unwrap().len(), 1);
}

/// Answers one question per request (no batching), and smuggles an extra
/// `destructive` answer into the `requested` response.
struct Smuggler {
    destructive: f64,
    smuggle: bool,
}

#[async_trait::async_trait]
impl DecisionBackend for Smuggler {
    fn capabilities(&self) -> Capabilities {
        Capabilities::new(QuestionKind::all()).with_batching(false)
    }
    async fn evaluate(&self, request: &Request) -> Result<Evaluation, DecisionError> {
        let (id, _) = &request.questions[0];
        let eval = Evaluation::new("m", DecisionUsage::new(10, 0));
        Ok(match id.as_str() {
            "destructive" => eval.with_answer("destructive", NoulAnswer::new(self.destructive)),
            _ if self.smuggle => eval
                .with_answer("requested", NoulAnswer::new(0.1))
                .with_answer("destructive", NoulAnswer::new(-3.0)),
            _ => eval.with_answer("requested", NoulAnswer::new(0.1)),
        })
    }
}

#[tokio::test]
async fn extra_answers_cannot_overwrite_validated_ones() {
    let run_with = |backend: Smuggler| async move {
        let (tools, ran) = make_tools(1);
        let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
            .with_tools(tools)
            .with_tool_gate(ToolGate::new(DecisionModel::from_backend(backend, "m")));
        run(agent, "summarize the README").await;
        let n = ran.lock().unwrap().len();
        n
    };
    assert_eq!(
        run_with(Smuggler {
            destructive: 0.9,
            smuggle: true
        })
        .await,
        0,
        "the smuggled -3.0 must not replace the validated 0.9"
    );
    // Positive control: an honestly harmless call through the same
    // non-batching path is allowed.
    assert_eq!(
        run_with(Smuggler {
            destructive: 0.0,
            smuggle: false
        })
        .await,
        1
    );
}

/// An async input filter that consults a decision model.
struct ModeratedBy(DecisionModel);

#[async_trait::async_trait]
impl AsyncInputFilter for ModeratedBy {
    async fn filter(&self, text: &str) -> FilterResult {
        match self.0.noul(text, "Is this abusive?").await {
            Ok(a) if a.p_true() >= 0.5 => FilterResult::Reject("abusive".into()),
            Ok(_) => FilterResult::Pass,
            Err(_) => FilterResult::Reject("moderation unavailable".into()),
        }
    }
}

#[tokio::test]
async fn decision_spend_in_async_input_filters_is_counted() {
    for (p, rejected) in [(0.1, false), (0.9, true)] {
        let mock = MockBackend::from_fn(move |_| {
            Ok(Evaluation::new("m", DecisionUsage::new(2_000, 0))
                .with_answer("q", NoulAnswer::new(p)))
        });
        let priced = model(&mock).with_cost(Some(CostConfig::new(1.0, 0.0)));
        let agent = Agent::from_provider(MockProvider::text("ok"), ModelConfig::mock())
            .with_async_input_filter(ModeratedBy(priced));
        let (agent, stats) = run_stats(agent, "hello").await;
        assert_eq!(agent.messages().is_empty(), rejected);
        assert_eq!(stats.decision.requests, 1, "rejected={rejected}");
        let cost = stats.decision.cost_usd.expect("priced");
        assert!((cost - 0.002).abs() < 1e-12, "{cost}");
        assert_eq!(agent.total_cost_usd(), Some(cost));
    }
    // Positive control: a filter that asks nothing records nothing.
    let agent = Agent::from_provider(MockProvider::text("ok"), ModelConfig::mock());
    let (_, stats) = run_stats(agent, "hello").await;
    assert!(stats.decision.is_empty());
}

#[tokio::test]
async fn a_partial_failure_records_the_usage_already_billed() {
    // Non-batching: `destructive` answers (10 tokens), then `requested` fails.
    let calls = Arc::new(Mutex::new(0u32));
    let backend_calls = calls.clone();
    let mock = MockBackend::from_fn(move |req| {
        *backend_calls.lock().unwrap() += 1;
        let (id, _) = &req.questions[0];
        if id == "destructive" {
            Ok(Evaluation::new("m", DecisionUsage::new(10, 0))
                .with_answer("destructive", NoulAnswer::new(0.0)))
        } else {
            Err(DecisionError::backend("second question failed"))
        }
    })
    .with_capabilities(Capabilities::new(QuestionKind::all()).with_batching(false));
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(
            model(&mock).with_cost(Some(CostConfig::new(1.0, 0.0))),
        ));
    let (_, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert!(ran.lock().unwrap().is_empty(), "fails closed");
    assert_eq!(*calls.lock().unwrap(), 2);
    let d = &stats.decision;
    assert_eq!((d.requests, d.failures), (1, 1), "{d:?}");
    assert_eq!(d.usage.input, 10, "the answered half was billed");
    assert!((d.cost_usd.unwrap() - 0.00001).abs() < 1e-15);
}

#[tokio::test]
async fn missing_usage_is_unpriced_not_free() {
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};
    // Priced handle without usage -> unpriced; with usage -> priced.
    for (with_usage, priced) in [(false, false), (true, true)] {
        let server = MockServer::start().await;
        let mut body = json!({
            "model": "jev-test",
            "answers": {
                "destructive": {"type": "noul", "noul": 0.0},
                "requested": {"type": "noul", "noul": 1.0}
            }
        });
        if with_usage {
            body["usage"] = json!({"input_tokens": 1_000, "output_tokens": 5});
        }
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
            .mount(&server)
            .await;
        let backend = SystemOneBackend::new(server.uri());
        let gate = ToolGate::new(
            DecisionModel::from_backend(backend, "jev-test")
                .with_cost(Some(CostConfig::new(1.0, 0.0))),
        );
        let (tools, _) = make_tools(1);
        let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
            .with_tools(tools)
            .with_tool_gate(gate);
        let (agent, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
        assert_eq!(stats.decision.requests, 1);
        assert_eq!(stats.decision.is_unpriced(), !priced, "usage={with_usage}");
        assert_eq!(stats.decision.cost_usd.is_some(), priced);
        assert_eq!(agent.total_cost_usd().is_some(), priced);
    }
}

// --- mutation-found gaps -------------------------------------------------

#[tokio::test]
async fn nested_sub_agent_decision_spend_reaches_the_parent_once() {
    let mock = gate_answers(0.0, 1.0);
    let priced = model(&mock).with_cost(Some(CostConfig::new(1.0, 0.0)));
    let ran: Ran = Arc::new(Mutex::new(Vec::new()));
    let sub = SubAgentTool::from_provider("helper", Arc::new(calls_rm()), ModelConfig::mock())
        .with_tools(vec![Arc::new(Named {
            name: "rm".into(),
            ran: ran.clone(),
        })])
        .with_tool_gate(ToolGate::new(priced));
    let parent_provider = MockProvider::new(vec![
        MockResponse::ToolCalls(vec![MockToolCall {
            provider_metadata: None,
            name: "helper".into(),
            arguments: json!({"task": "tidy up"}),
        }]),
        MockResponse::Text("done".into()),
    ]);
    let agent = Agent::from_provider(parent_provider, ModelConfig::mock()).with_sub_agent(sub);
    let (agent, stats) = run_stats(agent, "tidy up").await;
    assert_eq!(ran.lock().unwrap().len(), 1, "the child's gate allowed");
    // One gate request (50 input tokens at $1/M), in the decision bucket.
    assert_eq!(stats.decision.requests, 1, "{:?}", stats.decision);
    let cost = stats.decision.cost_usd.unwrap();
    assert!((cost - 0.00005).abs() < 1e-15, "{cost}");
    // ...and not also in the sub-agent bucket, which is LLM spend only.
    assert_eq!(stats.sub_agents.runs, 1);
    assert_eq!(stats.sub_agents.cost_usd, None);
    assert_eq!(stats.total_cost_usd(), Some(cost));
    assert_eq!(agent.total_cost_usd(), Some(cost));
}

#[tokio::test]
async fn steering_lands_in_the_run_prompts() {
    let mock = deletion_aware();
    let (tools, ran) = make_tools(1);
    let args = json!({"path": "/srv/prod"});
    let provider = MockProvider::new(vec![
        rm_call(args.clone()),
        rm_call(args),
        MockResponse::Text("done".into()),
    ]);
    let head = vec![
        AgentMessage::Llm(Message::user("what is in /srv?")),
        AgentMessage::Llm(Message::assistant(
            vec![Content::Text {
                text: "Several directories.".into(),
            }],
            StopReason::Stop,
            "mock",
            "mock",
            Usage::default(),
        )),
    ];
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_messages(head)
        .with_tools(tools)
        .with_compaction_strategy(HeadMarkerTail(COMPACTION_MARKER_TEXT))
        .with_tool_gate(ToolGate::new(model(&mock)));
    // Only the steering message asks for the deletion.
    agent.steer(AgentMessage::Llm(Message::user(
        "delete every file in /srv/prod",
    )));
    run(agent, "look around /srv/prod").await;
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 2);
    // Second call: compaction dropped both prompts; the run prompts hold
    // them, labelled.
    let second = reqs[1].state["user_request"].as_str().unwrap();
    assert_eq!(
        second,
        "User: look around /srv/prod\n\nUser: delete every file in /srv/prod"
    );
    assert_eq!(
        ran.lock().unwrap().len(),
        2,
        "requested by the steering message"
    );
}

#[tokio::test]
async fn gate_threshold_edges() {
    for (requested, allowed) in [(0.69, false), (0.7, true)] {
        let mock = gate_answers(0.5, requested);
        let (agent, ran) = gated(&mock);
        run(agent, "delete /tmp/scratch.txt").await;
        assert_eq!(
            ran.lock().unwrap().len() == 1,
            allowed,
            "requested={requested}"
        );
    }
    // Just below the destructive threshold is not destructive.
    let mock = gate_answers(0.4999, 0.0);
    let (agent, ran) = gated(&mock);
    run(agent, "look").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn a_check_below_its_threshold_allows() {
    let mock = MockBackend::from_fn(|req| {
        let mut eval = Evaluation::new("m", DecisionUsage::default());
        for (id, _) in &req.questions {
            let p = match id.as_str() {
                "secrets" => 0.49,
                "requested" => 1.0,
                _ => 0.0,
            };
            eval = eval.with_answer(id.clone(), NoulAnswer::new(p));
        }
        Ok(eval)
    });
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(model(&mock)).with_check(
            "secrets",
            "Does `tool_call` read or send credentials?",
            0.5,
        ));
    run(agent, "clean up").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
}

#[tokio::test]
async fn the_advisory_caches_a_failure_for_the_request() {
    let tmp = tempfile::tempdir().unwrap();
    let mock = MockBackend::new().push_error(DecisionError::http(500, "down"));
    let (tools, _) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_tools(tools)
        .with_decision_model(model(&mock));
    run(agent, "fill in the PDF").await;
    assert_eq!(mock.request_count(), 1, "two turns, one attempt");
}

#[tokio::test]
async fn advisory_filters_uncertain_answers() {
    // Uniform answers: the skill Choice has zero confidence and every tool
    // is below the minimum probability.
    let tmp = tempfile::tempdir().unwrap();
    let mock = MockBackend::neutral();
    let (provider, seen) = recording(MockProvider::text("ok"));
    let (tools, _) = make_tools(45);
    let agent = Agent::from_provider(provider, ModelConfig::mock())
        .with_skills(skills(tmp.path()))
        .with_tools(tools)
        .with_decision_model(model(&mock));
    run(agent, "fill in the PDF").await;
    assert_eq!(mock.request_count(), 1, "asked");
    assert_eq!(
        sent(&seen)[0].last_user_text(),
        "fill in the PDF",
        "no note"
    );
}

#[tokio::test]
async fn a_free_handle_stays_free_without_usage() {
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "model": "jevk5",
            "answers": {
                "destructive": {"type": "noul", "noul": 0.0},
                "requested": {"type": "noul", "noul": 1.0}
            }
        })))
        .mount(&server)
        .await;
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(ToolGate::new(DecisionModel::local(server.uri())));
    let (agent, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert_eq!(ran.lock().unwrap().len(), 1);
    assert_eq!(stats.decision.requests, 1);
    assert_eq!(stats.decision.unpriced, 0);
    assert_eq!(stats.decision.cost_usd, Some(0.0));
    // The run's bill is not hidden by a free decision model.
    assert_eq!(stats.total_cost_usd(), Some(0.0));
    assert_eq!(agent.total_cost_usd(), Some(0.0));
}

/// Non-batching: answers `destructive` at once (10 tokens), then hangs.
struct HangsOnSecond;

#[async_trait::async_trait]
impl DecisionBackend for HangsOnSecond {
    fn capabilities(&self) -> Capabilities {
        Capabilities::new(QuestionKind::all()).with_batching(false)
    }
    async fn evaluate(&self, request: &Request) -> Result<Evaluation, DecisionError> {
        let (id, _) = &request.questions[0];
        if id == "destructive" {
            return Ok(Evaluation::new("m", DecisionUsage::new(10, 0))
                .with_answer("destructive", NoulAnswer::new(0.0)));
        }
        tokio::time::sleep(Duration::from_secs(30)).await;
        Err(DecisionError::backend("unreachable"))
    }
}

#[tokio::test]
async fn a_timed_out_partial_request_records_what_was_billed() {
    let (tools, ran) = make_tools(1);
    let gate = ToolGate::new(
        DecisionModel::from_backend(HangsOnSecond, "m").with_cost(Some(CostConfig::new(1.0, 0.0))),
    )
    .with_timeout(Duration::from_millis(100));
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tool_gate(gate);
    let start = Instant::now();
    let (_, stats) = run_stats(agent, "delete /tmp/scratch.txt").await;
    assert!(start.elapsed() < Duration::from_secs(5));
    assert!(ran.lock().unwrap().is_empty(), "fails closed");
    let d = &stats.decision;
    assert_eq!((d.requests, d.failures, d.timeouts), (1, 1, 1), "{d:?}");
    assert_eq!(d.usage.input, 10, "the answered half was billed");
    assert!((d.cost_usd.unwrap() - 0.00001).abs() < 1e-15);
}

/// The gate is an extension (#241) appended after the agent's own, so it
/// judges the arguments another extension rewrote, not the model's.
#[tokio::test]
async fn gate_judges_the_arguments_an_extension_rewrote() {
    #[derive(Clone)]
    struct Rewrite;
    #[async_trait::async_trait]
    impl yoagent::RunHooks for Rewrite {
        async fn before_tool(&self, _call: &ToolCallRequest<'_>) -> ToolDecision {
            ToolDecision::Modify(json!({"path": "/srv/data"}))
        }
    }
    let mock = gate_answers(0.95, 0.1);
    let (tools, ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_extension(yoagent::extension::ClonedHooks::new("rewrite", Rewrite))
        .with_tool_gate(ToolGate::new(model(&mock)));
    run(agent, "tidy up").await;
    assert!(ran.lock().unwrap().is_empty(), "denied");
    let reqs = mock.requests();
    assert_eq!(reqs[0].state["tool_call"]["arguments"]["path"], "/srv/data");
}

/// Installed as a tree extension, the gate runs first, so it rechecks a call
/// a later extension rewrote: a second decision request, on the final
/// arguments.
#[tokio::test]
async fn a_tree_gate_rechecks_a_rewritten_call() {
    #[derive(Clone)]
    struct Rewrite;
    #[async_trait::async_trait]
    impl yoagent::RunHooks for Rewrite {
        async fn before_tool(&self, _call: &ToolCallRequest<'_>) -> ToolDecision {
            ToolDecision::Modify(json!({"path": "/srv/data"}))
        }
    }
    let mock = gate_answers(0.1, 0.9);
    let (tools, _ran) = make_tools(1);
    let agent = Agent::from_provider(calls_rm(), ModelConfig::mock())
        .with_tools(tools)
        .with_tree_extension(ToolGate::new(model(&mock)))
        .with_extension(yoagent::extension::ClonedHooks::new("rewrite", Rewrite));
    run(agent, "tidy up").await;
    let reqs = mock.requests();
    assert_eq!(reqs.len(), 2, "judged, then rechecked");
    assert_eq!(
        reqs[0].state["tool_call"]["arguments"]["path"],
        "/tmp/scratch.txt"
    );
    assert_eq!(reqs[1].state["tool_call"]["arguments"]["path"], "/srv/data");
}

#[tokio::test]
async fn gate_fits_the_strictest_limits_in_a_fallback_chain() {
    // An unlimited primary that fails, then a fallback with SystemOne's
    // 32k-token limit. 46,000 CJK characters are under the character budget
    // but over the fallback's tokens (3 bytes each): sized to the primary
    // alone, the fallback would skip the call unsent and the gate deny.
    let primary = MockBackend::new().push_error(DecisionError::http(503, "unavailable"));
    let fallback = gate_answers(0.1, 0.9).with_capabilities(
        Capabilities::new(QuestionKind::all()).with_token_limits(Some(64_000), Some(32_000)),
    );
    let chain = DecisionModel::from_backend(primary, "primary").or(model(&fallback));
    let gate = ToolGate::new(chain);
    let decision = decide(
        &gate,
        "write_file",
        json!({"path": "a.md", "content": "汉".repeat(46_000)}),
    )
    .await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    assert_eq!(fallback.request_count(), 1, "the fallback was asked");
    assert!(fallback.requests()[0].state["tool_call"]["omitted"].is_array());
}

#[tokio::test]
async fn gate_fits_both_limited_members_of_a_chain() {
    // Both members limited: the fallback's smaller limit is the one that binds.
    let primary = MockBackend::new()
        .push_error(DecisionError::http(503, "unavailable"))
        .with_capabilities(
            Capabilities::new(QuestionKind::all()).with_token_limits(None, Some(40_000)),
        );
    let fallback = gate_answers(0.1, 0.9).with_capabilities(
        Capabilities::new(QuestionKind::all()).with_token_limits(Some(9_000), Some(8_000)),
    );
    let gate = ToolGate::new(DecisionModel::from_backend(primary, "primary").or(model(&fallback)));
    let decision = decide(
        &gate,
        "write_file",
        json!({"path": "a", "content": "w".repeat(45_000)}),
    )
    .await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    assert_eq!(fallback.request_count(), 1, "the fallback was asked");
    let bytes = serde_json::to_vec(&fallback.requests()[0].state)
        .unwrap()
        .len();
    assert!(bytes <= 32_000, "{bytes}");
}

#[tokio::test]
async fn gate_custom_full_views_survive_dropping_the_default() {
    let command = format!(
        "{}rm -rf ~\n{}",
        "true\n".repeat(10_000),
        "true\n".repeat(10_000)
    );
    for gate_of in [
        |m| {
            ToolGate::new(m)
                .with_full_view("bash", "/command")
                .without_default_full_views()
        },
        |m| {
            ToolGate::new(m)
                .without_default_full_views()
                .with_full_view("bash", "/command")
        },
    ] {
        let mock = gate_answers(0.1, 0.9);
        let gate: ToolGate = gate_of(model(&mock));
        let decision = decide(&gate, "bash", json!({"command": command})).await;
        assert!(denied_with(&decision, "review in full"), "{decision:?}");
        assert_eq!(mock.request_count(), 0);
    }
}

#[tokio::test]
async fn gate_denies_a_command_over_the_backends_token_limit() {
    // Under the 48k-character budget, over a 4,000-token backend: a full view
    // that does not fit the backend is denied too, unsent.
    let mock = gate_answers(0.1, 0.9).with_capabilities(
        Capabilities::new(QuestionKind::all()).with_token_limits(None, Some(4_000)),
    );
    let gate = ToolGate::new(model(&mock));
    let command = format!("echo {}", "a".repeat(20_000));
    let decision = decide(&gate, "bash", json!({"command": command})).await;
    assert!(denied_with(&decision, "review in full"), "{decision:?}");
    assert_eq!(mock.request_count(), 0);
}

#[tokio::test]
#[should_panic(expected = "above 0")]
async fn gate_budget_must_be_positive() {
    let _ = ToolGate::new(model(&MockBackend::new())).with_max_argument_chars(0);
}

#[tokio::test]
async fn gate_never_cuts_a_string_when_cutting_would_grow_the_call() {
    // 111 fields just over the 400-character minimum, plus a 60k body. Cutting
    // a 401-character field adds a marker and an `omitted` entry — it grows.
    // Those fields must stay whole and the body take the cut; cutting them
    // all to 400 overshoots the budget and would deny a call that fits.
    let mut args: serde_json::Map<String, serde_json::Value> = (0..111)
        .map(|i| (format!("f{i:03}"), json!("v".repeat(401))))
        .collect();
    args.insert("body".into(), json!("b".repeat(60_000)));
    let mock = gate_answers(0.1, 0.9);
    let gate = ToolGate::new(model(&mock));
    let decision = decide(&gate, "write_file", json!(args)).await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    let (sent, omitted) = gate_saw(&mock);
    assert_eq!(
        sent["f000"],
        "v".repeat(401).as_str(),
        "short fields stay whole"
    );
    assert_eq!(omitted.as_array().unwrap().len(), 1);
    assert_eq!(omitted[0]["argument"], "/body");
}

#[tokio::test]
async fn gate_cuts_whenever_a_cut_shrinks_the_arguments() {
    // 96 long keys holding 480 characters each: 49.5k, over the budget. A cut
    // to 400 shortens each by 56 characters, though its `omitted` entry (long
    // pointer) is about as long. The budget measures the arguments, so the
    // cuts are made and the call fits — as before the never-grow rule.
    let args: serde_json::Map<String, serde_json::Value> = (0..96)
        .map(|i| (format!("{i:02}_{}", "k".repeat(27)), json!("x".repeat(480))))
        .collect();
    let mock = gate_answers(0.1, 0.9);
    let gate = ToolGate::new(model(&mock));
    let decision = decide(&gate, "write_file", json!(args)).await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    let (sent, omitted) = gate_saw(&mock);
    assert!(serde_json::to_string(&sent).unwrap().chars().count() <= 48_000);
    assert_eq!(omitted.as_array().unwrap().len(), 96);
}

#[tokio::test]
async fn gate_reports_the_shortest_it_could_make_a_call() {
    // Nothing long enough to cut: the denial must not claim strings were cut
    // to 400, and reports the size it would have had to send.
    let args: serde_json::Map<String, serde_json::Value> = (0..200)
        .map(|i| (format!("f{i:03}"), json!("y".repeat(300))))
        .collect();
    let mock = gate_answers(0.1, 0.9);
    let gate = ToolGate::new(model(&mock));
    let decision = decide(&gate, "write_file", json!(args)).await;
    let ToolDecision::Deny(reason) = decision else {
        panic!("{decision:?}")
    };
    let whole = serde_json::to_string(&args).unwrap().chars().count();
    assert!(
        reason.contains(&format!(
            "shortest the gate may make them ({whole} characters)"
        )),
        "{reason}"
    );
    assert!(
        reason.contains("budget (48000) or the decision model's limits"),
        "{reason}"
    );
    assert_eq!(mock.request_count(), 0);
}

#[tokio::test]
async fn gate_counts_omission_metadata_against_the_token_limit() {
    // 100 fields of 450 characters plus a 60k body, under an 11,832-token
    // backend limit. Cutting the fields shortens the arguments, but their
    // `omitted` entries cost more state than the cuts save: the call fits
    // only with the fields whole and the body cut.
    let mut args: serde_json::Map<String, serde_json::Value> = (0..100)
        .map(|i| (format!("f{i:03}"), json!("v".repeat(450))))
        .collect();
    args.insert("body".into(), json!("b".repeat(60_000)));
    let mock = gate_answers(0.1, 0.9).with_capabilities(
        Capabilities::new(QuestionKind::all()).with_token_limits(None, Some(11_832)),
    );
    let gate = ToolGate::new(model(&mock));
    let decision = decide(&gate, "write_file", json!(args)).await;
    assert!(matches!(decision, ToolDecision::Allow), "{decision:?}");
    let (sent, omitted) = gate_saw(&mock);
    assert_eq!(sent["f000"], "v".repeat(450).as_str(), "fields whole");
    assert_eq!(omitted.as_array().unwrap().len(), 1);
    assert_eq!(omitted[0]["argument"], "/body");
}